From d7f454789afd41f419bc78542baf90f8c7ba76e9 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Thu, 12 Nov 2026 19:57:29 -0500 Subject: [PATCH 01/32] refactor(dicom): unify loading and extract core and vtk modules 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 packages/dicom. Core reads instances from byte sources with an AbortSignal, plans collections with a pure registry reducer, and fills a Volume buffer it owns. The vtk entry point wraps that buffer in vtkImageData and widens its scalar range as slices arrive. VolView keeps its stores and UI; each series commits in one synchronous step, so a failed series changes nothing. The viewed slice loads first, then the rest coarse to fine, on a pool of GDCM decode workers. Uncompressed pixel data is decoded per frame without GDCM. Volumes use Float32 buffers where integer or fractional rescale allows, which vtk.js renders without conversion. --- .github/workflows/checks.yml | 4 +- .github/workflows/e2e-datasets.yml | 2 +- .github/workflows/e2e.yml | 2 +- .gitignore | 2 + .prettierignore | 1 - eslint.config.js | 52 +- package-lock.json | 98 +- package.json | 20 +- packages/dicom/README.md | 247 ++++ packages/dicom/__tests__/boundaries.spec.ts | 95 ++ .../__tests__/assignCollectionIds.spec.ts | 331 +++++ .../collections/__tests__/dicomTags.spec.ts | 12 + .../__tests__/idcSeriesFixtures.ts | 202 +++ .../__tests__/instanceFacts.spec.ts | 404 ++++++ .../__tests__/instanceFactsFixture.ts | 60 + .../__tests__/instanceRegistry.spec.ts | 204 +++ .../__tests__/planDicomCollections.spec.ts | 1040 +++++++++++++++ .../__tests__/reconstructVolume.spec.ts | 252 ++++ .../__tests__/registryAcrossImports.spec.ts | 456 +++++++ .../collections/__tests__/sliceFixture.ts | 52 + .../splitOverlappingAcquisitions.spec.ts | 635 +++++++++ .../core/collections/assignCollectionIds.ts | 104 ++ .../dicom/core/collections/datasetDetails.ts | 16 + packages/dicom/core/collections/groupBy.ts | 11 + .../dicom/core/collections/instanceFacts.ts | 205 +++ .../dicom/core/collections/instanceKey.ts | 16 + .../core/collections/instanceRegistry.ts | 241 ++++ .../core/collections/multiframeGeometry.ts | 72 ++ .../dicom/core/collections/orientation.ts | 11 + .../core/collections/planDicomCollections.ts | 595 +++++++++ .../core/collections/reconstructVolume.ts | 220 ++++ .../splitOverlappingAcquisitions.ts | 292 +++++ .../instance/__tests__/instanceFixture.ts | 19 + .../instance/__tests__/readInstance.spec.ts | 102 ++ .../__tests__/readInstanceSources.spec.ts | 246 ++++ packages/dicom/core/instance/readInstance.ts | 67 + .../metadata/__tests__/dcmjsParser.spec.ts | 331 +++++ .../metadata/__tests__/dicomDataset.spec.ts | 356 ++++++ .../metadata/__tests__/dicomLayout.spec.ts | 63 + .../metadata/__tests__/metadataReader.spec.ts | 67 + .../__tests__/spatialMetadata.spec.ts | 52 + packages/dicom/core/metadata/datasetAccess.ts | 30 + packages/dicom/core/metadata/dcmjs.d.ts | 83 ++ packages/dicom/core/metadata/dcmjsParser.ts | 444 +++++++ .../dicom/core/metadata/dicomCharacterSet.ts | 206 +++ packages/dicom/core/metadata/dicomDataset.ts | 269 ++++ packages/dicom/core/metadata/dicomLayout.ts | 90 ++ .../dicom/core/metadata}/dicomTags.ts | 17 +- .../dicom/core/metadata/functionalGroups.ts | 54 + .../dicom/core/metadata/modalityRescale.ts | 32 + .../dicom/core/metadata/nmReconstruction.ts | 146 +++ .../core/metadata/readDicomDataset.worker.ts | 5 + .../dicom/core/metadata/spatialMetadata.ts | 70 + .../pixels/__tests__/decoderTable.spec.ts | 61 + .../core/pixels/__tests__/frameIndex.spec.ts | 96 ++ .../core/pixels/__tests__/nativeFrame.spec.ts | 238 ++++ .../core/pixels/__tests__/pixelFixture.ts | 33 + packages/dicom/core/pixels/decoderTable.ts | 128 ++ packages/dicom/core/pixels/frameIndex.ts | 123 ++ packages/dicom/core/pixels/nativeFrame.ts | 236 ++++ .../__tests__/decoderCalibration.spec.ts | 33 + .../runtime/__tests__/dicomRuntime.spec.ts | 105 ++ .../dicom/core/runtime/createDicomRuntime.ts | 204 +++ packages/dicom/core/runtime/decoder.ts | 101 ++ packages/dicom/core/runtime/metadataReader.ts | 80 ++ .../core/source/__tests__/byteSource.spec.ts | 166 +++ .../core/source/__tests__/sourceFixtures.ts | 57 + packages/dicom/core/source/byteSource.ts | 220 ++++ .../streaming/__tests__/byteDeque.spec.ts | 2 +- .../__tests__/cachedStreamFetcher.spec.ts | 29 +- .../streaming/__tests__/requestPool.spec.ts | 144 +++ .../__tests__/streamingByteReader.spec.ts | 2 +- .../dicom}/core/streaming/byteDeque.ts | 0 .../core/streaming/cachedStreamFetcher.ts | 63 +- .../__tests__/dicomHeaderEncodings.spec.ts | 120 ++ .../dicom/__tests__/ultrasoundRegion.spec.ts | 89 ++ .../core/streaming/dicom/dicomParser.ts | 197 ++- .../core/streaming/dicom/readDicomHeader.ts | 159 +++ .../core/streaming/dicom/ultrasoundRegion.ts | 60 + .../dicom}/core/streaming/httpCodes.ts | 0 packages/dicom/core/streaming/requestPool.ts | 110 ++ .../core/streaming/streamingByteReader.ts | 4 +- packages/dicom/core/streaming/types.ts | 20 + packages/dicom/core/utils.ts | 77 ++ .../__tests__/parseContentRangeHeader.spec.ts | 2 +- packages/dicom/core/utils/abort.ts | 37 + .../core}/utils/parseContentRangeHeader.ts | 0 .../volume/__tests__/allocateVolume.spec.ts | 119 ++ .../volume/__tests__/functionalGroups.spec.ts | 563 ++++++++ .../core/volume/__tests__/loadFrames.spec.ts | 239 ++++ .../core/volume/__tests__/loadVolume.spec.ts | 265 ++++ .../volume/__tests__/pixelValidation.spec.ts | 47 + .../core/volume/__tests__/slotOrder.spec.ts | 44 + .../core/volume/__tests__/volumeFixture.ts | 69 + .../volume/__tests__/volumeLayout.spec.ts | 315 ++++- packages/dicom/core/volume/allocateVolume.ts | 179 +++ packages/dicom/core/volume/loadVolume.ts | 454 +++++++ packages/dicom/core/volume/nmGeometry.ts | 25 + packages/dicom/core/volume/pixelFormat.ts | 251 ++++ packages/dicom/core/volume/pixelValidation.ts | 115 ++ packages/dicom/core/volume/slotOrder.ts | 27 + .../dicom/core/volume/ultrasoundSpacing.ts | 85 ++ packages/dicom/core/volume/volumeLayout.ts | 269 ++++ packages/dicom/package.json | 38 + packages/dicom/scripts/build.mjs | 95 ++ packages/dicom/scripts/check-consumers.mjs | 97 ++ packages/dicom/tsconfig.build.json | 23 + .../dicom/vtk/__tests__/volumeImage.spec.ts | 124 ++ packages/dicom/vtk/thumbnail.ts | 99 ++ packages/dicom/vtk/volumeImage.ts | 74 ++ scripts/checks/complexity.mjs | 2 +- src/components/ImageSpacingDetails.vue | 113 ++ src/components/PatientStudyVolumeBrowser.vue | 99 +- .../ControlsStripTools.enFace.spec.ts | 6 +- ...tientStudyVolumeBrowser.thumbnails.spec.ts | 329 +++++ .../vtk/VtkBaseVolumeRepresentation.vue | 18 +- src/core/cine/DicomCineImage.ts | 74 +- src/core/progressiveImage.ts | 11 +- src/core/stateMachine.ts | 113 -- .../__tests__/chunkStateMachine.spec.ts | 38 - .../__tests__/dicomChunkImage.spec.ts | 507 -------- .../__tests__/dicomThumbnail.spec.ts | 121 ++ .../__tests__/dicomVolumeImage.spec.ts | 575 +++++++++ .../streaming/__tests__/requestPool.spec.ts | 57 - src/core/streaming/chunk.ts | 186 --- src/core/streaming/chunkImage.ts | 41 - src/core/streaming/chunkStateMachine.ts | 41 - src/core/streaming/concatStreams.ts | 36 - .../dicom/__tests__/dicomMetaLoader.spec.ts | 27 - .../dicom/__tests__/octMetadata.spec.ts | 182 +-- .../__tests__/octStructuredMetadata.spec.ts | 105 ++ .../dicom/__tests__/ultrasoundRegion.spec.ts | 219 ---- src/core/streaming/dicom/dicomDataLoader.ts | 19 - .../streaming/dicom/dicomFileDataLoader.ts | 15 - .../streaming/dicom/dicomFileMetaLoader.ts | 47 - src/core/streaming/dicom/dicomMetaLoader.ts | 151 --- src/core/streaming/dicom/octDataset.ts | 22 + src/core/streaming/dicom/octMetadata.ts | 103 +- src/core/streaming/dicom/octMetadataTags.ts | 7 +- src/core/streaming/dicom/seriesGeometry.ts | 18 +- src/core/streaming/dicom/ultrasoundRegion.ts | 145 --- src/core/streaming/dicomChunkImage.ts | 646 ---------- src/core/streaming/dicomVolumeImage.ts | 361 ++++++ src/core/streaming/requestPool.ts | 126 -- src/core/streaming/types.ts | 51 - src/enface/__tests__/availability.spec.ts | 51 +- src/enface/__tests__/calibration.spec.ts | 32 +- src/enface/__tests__/dicomMetadataFixture.ts | 45 + src/enface/__tests__/inputCalibration.spec.ts | 16 +- .../__tests__/occupiedDepthSupport.spec.ts | 63 +- src/enface/__tests__/seriesGeometry.spec.ts | 190 +-- src/enface/__tests__/viewer.spec.ts | 7 +- src/enface/availability.ts | 15 +- src/enface/occupiedDepthSupport.ts | 21 +- .../readDicomTags.differential.spec.ts | 50 + src/io/__tests__/readDicomTags.spec.ts | 476 +++++++ src/io/__tests__/readDicomTagsFixtures.ts | 342 +++++ src/io/dicom.ts | 165 --- src/io/import/__tests__/dataSource.spec.ts | 12 +- .../__tests__/dicomImportResults.spec.ts | 147 +++ .../__tests__/dicomInstanceProvenance.spec.ts | 85 ++ .../__tests__/missingArchiveMember.spec.ts | 20 + .../__tests__/restoreStateFileLeaves.spec.ts | 142 ++- .../import/__tests__/stateFileLeaves.spec.ts | 72 +- src/io/import/dataSource.ts | 23 +- src/io/import/importDataSources.ts | 283 ++++- .../processors/__tests__/handleDicom.spec.ts | 209 +++ src/io/import/processors/extractArchive.ts | 45 +- src/io/import/processors/handleDicom.ts | 118 ++ src/io/import/processors/handleDicomFile.ts | 59 - src/io/import/processors/handleDicomStream.ts | 81 -- src/io/import/processors/openUriStream.ts | 38 +- src/io/import/processors/restoreStateFile.ts | 101 +- src/io/import/processors/updateUriType.ts | 2 +- src/io/itk-dicom/.gitignore | 5 - src/io/itk-dicom/CMakeLists.txt | 71 -- src/io/itk-dicom/dicom.cpp | 319 ----- src/io/itk-dicom/emscripten-build/dicom.js | 16 - src/io/itk-dicom/emscripten-build/dicom.wasm | Bin 7777161 -> 0 bytes .../itk-dicom/emscripten-build/dicom.wasm.zst | Bin 2202242 -> 0 bytes src/io/itk/worker.ts | 85 +- src/io/magic.ts | 2 +- src/io/readDicomTags.ts | 99 ++ src/io/zip.ts | 3 +- .../engine/__tests__/mintInput.spec.ts | 21 +- src/processing/engine/mintInput.ts | 5 +- .../__tests__/artifactParentRestore.spec.ts | 55 +- src/segmentation/io/import.ts | 24 +- .../datasets-dicom-acquisition-split.spec.ts | 231 ++++ .../__tests__/datasets-dicom-cine.spec.ts | 371 +++--- .../__tests__/datasets-dicom-geometry.spec.ts | 92 ++ .../__tests__/datasets-dicom-lifetime.spec.ts | 29 + .../__tests__/datasets-dicom-reimport.spec.ts | 327 +++-- .../datasets-dicom-transaction.spec.ts | 535 ++++++++ .../__tests__/dicom-viewed-slice.spec.ts | 67 + src/store/__tests__/dicom-web-store.spec.ts | 119 ++ src/store/__tests__/dicomImportFixtures.ts | 150 +++ src/store/__tests__/dicomTagFixtures.ts | 2 +- .../__tests__/duplicateDatasetSave.spec.ts | 142 ++- src/store/__tests__/image-cache.spec.ts | 29 + src/store/datasets-dicom.ts | 596 ++++++--- src/store/datasets.ts | 75 +- src/store/dicom-runtime.ts | 21 + src/store/dicom-viewed-slice.ts | 28 + src/store/dicom-web/dicom-web-store.ts | 59 +- src/store/image-cache.ts | 1 + src/store/view-configs/layers.ts | 9 +- src/types/image.ts | 7 +- src/utils/__tests__/dicomWindowRange.spec.ts | 6 +- src/utils/__tests__/fetch.spec.ts | 15 +- src/utils/allocateImageFromChunks.ts | 300 ----- src/utils/dicom/windowMetadata.ts | 10 + src/utils/dicomWindowRange.ts | 2 +- src/utils/index.ts | 19 - tests/datasets.ts | 111 +- tests/dicomCompositionCorpus.json | 1129 +++++++++++++++++ tests/dicomConsumer.ts | 23 + tests/dicomDataset.ts | 18 + tests/dicomOrientationFixtures.ts | 19 + tests/dicomSourceFixtures.ts | 100 ++ tests/dicomVolumeCorpus.json | 853 +++++++++++++ .../fixtures/dicom-consumer/composition.html | 13 + tests/fixtures/dicom-consumer/composition.ts | 117 ++ .../dicom-consumer/compositionReference.py | 99 ++ tests/fixtures/dicom-consumer/core.html | 25 + tests/fixtures/dicom-consumer/core.ts | 53 + tests/fixtures/dicom-consumer/corpus.html | 12 + tests/fixtures/dicom-consumer/corpus.ts | 35 + .../fixtures/dicom-consumer/describeVolume.ts | 28 + .../dicom-consumer/enhancedFixtures.ts | 100 ++ tests/fixtures/dicom-consumer/fixtureData.ts | 44 + tests/fixtures/dicom-consumer/loadVolume.ts | 45 + tests/fixtures/dicom-consumer/parity.html | 12 + tests/fixtures/dicom-consumer/parity.ts | 115 ++ tests/fixtures/dicom-consumer/server.mjs | 108 ++ tests/fixtures/dicom-consumer/shared.ts | 66 + tests/fixtures/dicom-consumer/vtk.html | 25 + tests/fixtures/dicom-consumer/vtk.ts | 46 + tests/fixtures/oct/dicom.ts | 5 +- tests/nativePixelDicom.ts | 278 ++++ tests/pageobjects/volview.page.ts | 69 +- tests/specs/annotationTestUtils.ts | 23 +- tests/specs/crosshairs-multi-image.e2e.ts | 77 +- tests/specs/dicom-archive-state.e2e.ts | 107 ++ tests/specs/dicom-dimension-mismatch.e2e.ts | 196 +-- tests/specs/dicom-frame-reconstruction.e2e.ts | 137 ++ tests/specs/dicom-import-regressions.e2e.ts | 198 +++ tests/specs/dicom-japanese-name.e2e.ts | 113 ++ tests/specs/dicom-modality-rescale.e2e.ts | 6 +- tests/specs/dicom-native-parity.e2e.ts | 206 +++ tests/specs/dicom-package.e2e.ts | 59 + tests/specs/dicom-spacing-details.e2e.ts | 179 +++ tests/specs/dicom-volume-composition.e2e.ts | 116 ++ tests/specs/dicom-volume-corpus.e2e.ts | 157 +++ tests/specs/dicomRenderedSlice.ts | 128 ++ .../incremental-positionless-import.e2e.ts | 116 ++ tests/specs/layers-and-rendering.e2e.ts | 3 + tests/specs/multi-acquisition-series.e2e.ts | 78 ++ tests/specs/octTestUtils.ts | 5 +- tests/specs/pet-ct-sample.e2e.ts | 42 +- tests/specs/sample-rendering.e2e.ts | 23 +- tests/specs/segmentationTestUtils.ts | 6 +- .../specs/session-overlapping-imports.e2e.ts | 109 ++ tests/specs/syntheticDicom.ts | 304 ++++- tests/specs/utils.ts | 34 + tests/unit/octFixture.ts | 121 +- tsconfig.json | 21 +- vite.config.ts | 10 +- 268 files changed, 27533 insertions(+), 5372 deletions(-) create mode 100644 packages/dicom/README.md create mode 100644 packages/dicom/__tests__/boundaries.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/dicomTags.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts create mode 100644 packages/dicom/core/collections/__tests__/instanceFacts.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/instanceFactsFixture.ts create mode 100644 packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/sliceFixture.ts create mode 100644 packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts create mode 100644 packages/dicom/core/collections/assignCollectionIds.ts create mode 100644 packages/dicom/core/collections/datasetDetails.ts create mode 100644 packages/dicom/core/collections/groupBy.ts create mode 100644 packages/dicom/core/collections/instanceFacts.ts create mode 100644 packages/dicom/core/collections/instanceKey.ts create mode 100644 packages/dicom/core/collections/instanceRegistry.ts create mode 100644 packages/dicom/core/collections/multiframeGeometry.ts create mode 100644 packages/dicom/core/collections/orientation.ts create mode 100644 packages/dicom/core/collections/planDicomCollections.ts create mode 100644 packages/dicom/core/collections/reconstructVolume.ts create mode 100644 packages/dicom/core/collections/splitOverlappingAcquisitions.ts create mode 100644 packages/dicom/core/instance/__tests__/instanceFixture.ts create mode 100644 packages/dicom/core/instance/__tests__/readInstance.spec.ts create mode 100644 packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts create mode 100644 packages/dicom/core/instance/readInstance.ts create mode 100644 packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts create mode 100644 packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts create mode 100644 packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts create mode 100644 packages/dicom/core/metadata/__tests__/metadataReader.spec.ts create mode 100644 packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts create mode 100644 packages/dicom/core/metadata/datasetAccess.ts create mode 100644 packages/dicom/core/metadata/dcmjs.d.ts create mode 100644 packages/dicom/core/metadata/dcmjsParser.ts create mode 100644 packages/dicom/core/metadata/dicomCharacterSet.ts create mode 100644 packages/dicom/core/metadata/dicomDataset.ts create mode 100644 packages/dicom/core/metadata/dicomLayout.ts rename {src/core => packages/dicom/core/metadata}/dicomTags.ts (86%) create mode 100644 packages/dicom/core/metadata/functionalGroups.ts create mode 100644 packages/dicom/core/metadata/modalityRescale.ts create mode 100644 packages/dicom/core/metadata/nmReconstruction.ts create mode 100644 packages/dicom/core/metadata/readDicomDataset.worker.ts create mode 100644 packages/dicom/core/metadata/spatialMetadata.ts create mode 100644 packages/dicom/core/pixels/__tests__/decoderTable.spec.ts create mode 100644 packages/dicom/core/pixels/__tests__/frameIndex.spec.ts create mode 100644 packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts create mode 100644 packages/dicom/core/pixels/__tests__/pixelFixture.ts create mode 100644 packages/dicom/core/pixels/decoderTable.ts create mode 100644 packages/dicom/core/pixels/frameIndex.ts create mode 100644 packages/dicom/core/pixels/nativeFrame.ts create mode 100644 packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts create mode 100644 packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts create mode 100644 packages/dicom/core/runtime/createDicomRuntime.ts create mode 100644 packages/dicom/core/runtime/decoder.ts create mode 100644 packages/dicom/core/runtime/metadataReader.ts create mode 100644 packages/dicom/core/source/__tests__/byteSource.spec.ts create mode 100644 packages/dicom/core/source/__tests__/sourceFixtures.ts create mode 100644 packages/dicom/core/source/byteSource.ts rename {src => packages/dicom}/core/streaming/__tests__/byteDeque.spec.ts (97%) rename {src => packages/dicom}/core/streaming/__tests__/cachedStreamFetcher.spec.ts (80%) create mode 100644 packages/dicom/core/streaming/__tests__/requestPool.spec.ts rename {src => packages/dicom}/core/streaming/__tests__/streamingByteReader.spec.ts (95%) rename {src => packages/dicom}/core/streaming/byteDeque.ts (100%) rename {src => packages/dicom}/core/streaming/cachedStreamFetcher.ts (80%) create mode 100644 packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts create mode 100644 packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts rename {src => packages/dicom}/core/streaming/dicom/dicomParser.ts (65%) create mode 100644 packages/dicom/core/streaming/dicom/readDicomHeader.ts create mode 100644 packages/dicom/core/streaming/dicom/ultrasoundRegion.ts rename {src => packages/dicom}/core/streaming/httpCodes.ts (100%) create mode 100644 packages/dicom/core/streaming/requestPool.ts rename {src => packages/dicom}/core/streaming/streamingByteReader.ts (96%) create mode 100644 packages/dicom/core/streaming/types.ts create mode 100644 packages/dicom/core/utils.ts rename {src => packages/dicom/core}/utils/__tests__/parseContentRangeHeader.spec.ts (94%) create mode 100644 packages/dicom/core/utils/abort.ts rename {src => packages/dicom/core}/utils/parseContentRangeHeader.ts (100%) create mode 100644 packages/dicom/core/volume/__tests__/allocateVolume.spec.ts create mode 100644 packages/dicom/core/volume/__tests__/functionalGroups.spec.ts create mode 100644 packages/dicom/core/volume/__tests__/loadFrames.spec.ts create mode 100644 packages/dicom/core/volume/__tests__/loadVolume.spec.ts create mode 100644 packages/dicom/core/volume/__tests__/pixelValidation.spec.ts create mode 100644 packages/dicom/core/volume/__tests__/slotOrder.spec.ts create mode 100644 packages/dicom/core/volume/__tests__/volumeFixture.ts rename src/utils/__tests__/allocateImageFromChunks.spec.ts => packages/dicom/core/volume/__tests__/volumeLayout.spec.ts (58%) create mode 100644 packages/dicom/core/volume/allocateVolume.ts create mode 100644 packages/dicom/core/volume/loadVolume.ts create mode 100644 packages/dicom/core/volume/nmGeometry.ts create mode 100644 packages/dicom/core/volume/pixelFormat.ts create mode 100644 packages/dicom/core/volume/pixelValidation.ts create mode 100644 packages/dicom/core/volume/slotOrder.ts create mode 100644 packages/dicom/core/volume/ultrasoundSpacing.ts create mode 100644 packages/dicom/core/volume/volumeLayout.ts create mode 100644 packages/dicom/package.json create mode 100644 packages/dicom/scripts/build.mjs create mode 100644 packages/dicom/scripts/check-consumers.mjs create mode 100644 packages/dicom/tsconfig.build.json create mode 100644 packages/dicom/vtk/__tests__/volumeImage.spec.ts create mode 100644 packages/dicom/vtk/thumbnail.ts create mode 100644 packages/dicom/vtk/volumeImage.ts create mode 100644 src/components/ImageSpacingDetails.vue create mode 100644 src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts delete mode 100644 src/core/stateMachine.ts delete mode 100644 src/core/streaming/__tests__/chunkStateMachine.spec.ts delete mode 100644 src/core/streaming/__tests__/dicomChunkImage.spec.ts create mode 100644 src/core/streaming/__tests__/dicomThumbnail.spec.ts create mode 100644 src/core/streaming/__tests__/dicomVolumeImage.spec.ts delete mode 100644 src/core/streaming/__tests__/requestPool.spec.ts delete mode 100644 src/core/streaming/chunk.ts delete mode 100644 src/core/streaming/chunkImage.ts delete mode 100644 src/core/streaming/chunkStateMachine.ts delete mode 100644 src/core/streaming/concatStreams.ts delete mode 100644 src/core/streaming/dicom/__tests__/dicomMetaLoader.spec.ts create mode 100644 src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts delete mode 100644 src/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts delete mode 100644 src/core/streaming/dicom/dicomDataLoader.ts delete mode 100644 src/core/streaming/dicom/dicomFileDataLoader.ts delete mode 100644 src/core/streaming/dicom/dicomFileMetaLoader.ts delete mode 100644 src/core/streaming/dicom/dicomMetaLoader.ts create mode 100644 src/core/streaming/dicom/octDataset.ts delete mode 100644 src/core/streaming/dicom/ultrasoundRegion.ts delete mode 100644 src/core/streaming/dicomChunkImage.ts create mode 100644 src/core/streaming/dicomVolumeImage.ts delete mode 100644 src/core/streaming/requestPool.ts delete mode 100644 src/core/streaming/types.ts create mode 100644 src/enface/__tests__/dicomMetadataFixture.ts create mode 100644 src/io/__tests__/readDicomTags.differential.spec.ts create mode 100644 src/io/__tests__/readDicomTags.spec.ts create mode 100644 src/io/__tests__/readDicomTagsFixtures.ts create mode 100644 src/io/import/__tests__/dicomImportResults.spec.ts create mode 100644 src/io/import/__tests__/dicomInstanceProvenance.spec.ts create mode 100644 src/io/import/processors/__tests__/handleDicom.spec.ts create mode 100644 src/io/import/processors/handleDicom.ts delete mode 100644 src/io/import/processors/handleDicomFile.ts delete mode 100644 src/io/import/processors/handleDicomStream.ts delete mode 100644 src/io/itk-dicom/.gitignore delete mode 100644 src/io/itk-dicom/CMakeLists.txt delete mode 100644 src/io/itk-dicom/dicom.cpp delete mode 100644 src/io/itk-dicom/emscripten-build/dicom.js delete mode 100755 src/io/itk-dicom/emscripten-build/dicom.wasm delete mode 100755 src/io/itk-dicom/emscripten-build/dicom.wasm.zst create mode 100644 src/io/readDicomTags.ts create mode 100644 src/store/__tests__/datasets-dicom-acquisition-split.spec.ts create mode 100644 src/store/__tests__/datasets-dicom-geometry.spec.ts create mode 100644 src/store/__tests__/datasets-dicom-lifetime.spec.ts create mode 100644 src/store/__tests__/datasets-dicom-transaction.spec.ts create mode 100644 src/store/__tests__/dicom-viewed-slice.spec.ts create mode 100644 src/store/__tests__/dicom-web-store.spec.ts create mode 100644 src/store/__tests__/dicomImportFixtures.ts create mode 100644 src/store/dicom-runtime.ts create mode 100644 src/store/dicom-viewed-slice.ts delete mode 100644 src/utils/allocateImageFromChunks.ts create mode 100644 src/utils/dicom/windowMetadata.ts create mode 100644 tests/dicomCompositionCorpus.json create mode 100644 tests/dicomConsumer.ts create mode 100644 tests/dicomDataset.ts create mode 100644 tests/dicomOrientationFixtures.ts create mode 100644 tests/dicomSourceFixtures.ts create mode 100644 tests/dicomVolumeCorpus.json create mode 100644 tests/fixtures/dicom-consumer/composition.html create mode 100644 tests/fixtures/dicom-consumer/composition.ts create mode 100644 tests/fixtures/dicom-consumer/compositionReference.py create mode 100644 tests/fixtures/dicom-consumer/core.html create mode 100644 tests/fixtures/dicom-consumer/core.ts create mode 100644 tests/fixtures/dicom-consumer/corpus.html create mode 100644 tests/fixtures/dicom-consumer/corpus.ts create mode 100644 tests/fixtures/dicom-consumer/describeVolume.ts create mode 100644 tests/fixtures/dicom-consumer/enhancedFixtures.ts create mode 100644 tests/fixtures/dicom-consumer/fixtureData.ts create mode 100644 tests/fixtures/dicom-consumer/loadVolume.ts create mode 100644 tests/fixtures/dicom-consumer/parity.html create mode 100644 tests/fixtures/dicom-consumer/parity.ts create mode 100644 tests/fixtures/dicom-consumer/server.mjs create mode 100644 tests/fixtures/dicom-consumer/shared.ts create mode 100644 tests/fixtures/dicom-consumer/vtk.html create mode 100644 tests/fixtures/dicom-consumer/vtk.ts create mode 100644 tests/nativePixelDicom.ts create mode 100644 tests/specs/dicom-archive-state.e2e.ts create mode 100644 tests/specs/dicom-frame-reconstruction.e2e.ts create mode 100644 tests/specs/dicom-import-regressions.e2e.ts create mode 100644 tests/specs/dicom-japanese-name.e2e.ts create mode 100644 tests/specs/dicom-native-parity.e2e.ts create mode 100644 tests/specs/dicom-package.e2e.ts create mode 100644 tests/specs/dicom-spacing-details.e2e.ts create mode 100644 tests/specs/dicom-volume-composition.e2e.ts create mode 100644 tests/specs/dicom-volume-corpus.e2e.ts create mode 100644 tests/specs/dicomRenderedSlice.ts create mode 100644 tests/specs/incremental-positionless-import.e2e.ts create mode 100644 tests/specs/multi-acquisition-series.e2e.ts create mode 100644 tests/specs/session-overlapping-imports.e2e.ts diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 07799f786..4ad57ece2 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -18,9 +18,11 @@ jobs: cache: npm - run: npm ci - name: Enforce code style - run: npx prettier --list-different "src/**/*.[jt]s" "tests/**/*.[jt]s" "src/**/*.vue" + run: npx prettier --list-different "src/**/*.[jt]s" "tests/**/*.[jt]s" "src/**/*.vue" "packages/dicom/**/*.{ts,mjs,json,md}" - name: Lint run: npm run lint + - name: Build independent DICOM consumers + run: npm run dicom:check - name: Quality ratchets # A file may not get worse than it is on the pull request's target branch. if: github.event_name == 'pull_request' diff --git a/.github/workflows/e2e-datasets.yml b/.github/workflows/e2e-datasets.yml index 4d6f01351..16a259354 100644 --- a/.github/workflows/e2e-datasets.yml +++ b/.github/workflows/e2e-datasets.yml @@ -22,7 +22,7 @@ jobs: uses: actions/cache@v4 with: path: .tmp/datasets - key: e2e-datasets-${{ hashFiles('tests/datasets.ts') }} + key: e2e-datasets-${{ hashFiles('tests/datasets.ts', 'tests/dicomVolumeCorpus.json', 'tests/dicomCompositionCorpus.json') }} restore-keys: e2e-datasets- - name: Download missing datasets run: node tests/downloadDatasets.ts diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 43312bf9c..18a784071 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -28,7 +28,7 @@ jobs: uses: actions/cache@v4 with: path: .tmp/datasets - key: e2e-datasets-${{ hashFiles('tests/datasets.ts') }} + key: e2e-datasets-${{ hashFiles('tests/datasets.ts', 'tests/dicomVolumeCorpus.json', 'tests/dicomCompositionCorpus.json') }} restore-keys: e2e-datasets- - name: Run E2E on chrome (linux) if: matrix.os == 'ubuntu-latest' diff --git a/.gitignore b/.gitignore index dd9be9f03..f1546634b 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,5 @@ reports .github/copilot CLAUDE.md .claude/ + +/packages/dicom/dist/ diff --git a/.prettierignore b/.prettierignore index 6463485b9..da2a92bc8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,6 +1,5 @@ dist node_modules public -src/io/itk-dicom src/io/resample *.json diff --git a/eslint.config.js b/eslint.config.js index 07cc47b37..f7de6d5fe 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -64,6 +64,11 @@ const ownFeatureExceptPure = (feature) => { const upperLayerMessage = (feature) => `The ${feature.dir} pure layer must not import stores, components, or upper feature modules. Dependencies point downward only.`; +const dicomPublicSurface = { + regex: '^@/packages/dicom/(?!core/.+|vtk/.+)', + message: 'Import the defining DICOM core or vtk module directly.', +}; + const featureBoundaries = (features) => { const publicSurface = ({ dir, publicModules }) => ({ group: [ @@ -76,8 +81,10 @@ const featureBoundaries = (features) => { const publicFeatures = features.filter( (feature) => feature.publicSurface !== false ); - const otherSurfaces = (feature) => - publicFeatures.filter((other) => other !== feature).map(publicSurface); + const otherSurfaces = (feature) => [ + dicomPublicSurface, + ...publicFeatures.filter((other) => other !== feature).map(publicSurface), + ]; return [ { @@ -86,7 +93,12 @@ const featureBoundaries = (features) => { rules: { 'no-restricted-imports': [ 'error', - { patterns: publicFeatures.map(publicSurface) }, + { + patterns: [ + dicomPublicSurface, + ...publicFeatures.map(publicSurface), + ], + }, ], }, }, @@ -148,7 +160,6 @@ const E2E_TIMEOUT_DEBT = [ 'tests/specs/cine-ruler-session.e2e.ts', 'tests/specs/crosshairs-multi-image.e2e.ts', 'tests/specs/delete-selected-annotation.e2e.ts', - 'tests/specs/dicom-dimension-mismatch.e2e.ts', 'tests/specs/different-direction-labelmap.e2e.ts', 'tests/specs/imageCacheUtils.ts', 'tests/specs/layer-source-lifetime.e2e.ts', @@ -171,10 +182,10 @@ const E2E_TIMEOUT_DEBT = [ export default tseslint.config( { ignores: [ - 'src/io/itk-dicom/emscripten-build/**', 'src/io/resample/emscripten-build/**', '**/*.d.ts', 'dist/**', + 'packages/dicom/dist/**', 'node_modules/**', ], }, @@ -246,9 +257,10 @@ export default tseslint.config( 'no-restricted-syntax': [ 'error', { - selector: "Property[key.name='timeout']", + selector: + "Property[key.name='timeout']:not([value.type='Identifier'][value.name='DOWNLOAD_TIMEOUT'])", message: - 'Wait for a state the page publishes rather than passing a timeout.', + 'Wait for a state the page publishes; use DOWNLOAD_TIMEOUT for data-loading readiness.', }, { selector: @@ -292,7 +304,7 @@ export default tseslint.config( }, }, { - files: ['src/vtk/**/*.{js,ts}'], + files: ['src/vtk/**/*.{js,ts}', 'packages/dicom/vtk/**/*.{js,ts}'], rules: { 'no-param-reassign': [ 'error', @@ -378,8 +390,9 @@ export default tseslint.config( // level because the ratchet only fails a file whose debt grows, so existing // files stay over these numbers without failing `npm run lint`. { - files: ['src/**/*.{js,ts,vue}'], + files: ['src/**/*.{js,ts,vue}', 'packages/dicom/**/*.{js,ts}'], ignores: [ + 'packages/dicom/**/__tests__/**', 'src/**/__tests__/**', 'src/**/*.{spec,test}.{js,ts}', 'src/**/*.d.ts', @@ -395,5 +408,26 @@ export default tseslint.config( ], }, }, + ...['core', 'vtk'].map((entry) => ({ + files: [`packages/dicom/${entry}/**/*.{js,ts}`], + ignores: ['**/__tests__/**'], + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: + entry === 'core' + ? '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/|@kitware/vtk\\.js(?:/|$))' + : '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/)', + message: + 'DICOM package internals use relative imports and cannot depend on application state or UI frameworks. Core cannot depend on vtk.js.', + }, + ], + }, + ], + }, + })), eslintConfigPrettier ); diff --git a/package-lock.json b/package-lock.json index ca3c577b5..1a73d11e6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,13 +46,13 @@ "core-js": "3.47.0", "cors": "^2.8.5", "cross-env": "^10.1.0", + "dcmjs": "^0.52.0", "dicom-parser": "^1.8.21", "dicomweb-client-typed": "^0.8.6", "eslint": "^9.39.1", "eslint-config-prettier": "^10.1.8", "eslint-plugin-vue": "^10.6.2", "fast-deep-equal": "^3.1.3", - "fflate": "0.7.5", "file-saver": "^2.0.5", "gl-matrix": "3.4.3", "globals": "^16.2.0", @@ -543,6 +543,19 @@ "node": ">=6.0.0" } }, + "node_modules/@babel/runtime-corejs3": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.29.2.tgz", + "integrity": "sha512-Lc94FOD5+0aXhdb0Tdg3RUtqT6yWbI/BbFWvlaSJ3gAb9Ks+99nHRDKADVqC37er4eCB0fHyWT+y+K3QOvJKbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "core-js-pure": "^3.48.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", @@ -7643,6 +7656,16 @@ "dev": true, "license": "(Apache-2.0 AND MIT)" }, + "node_modules/adm-zip": { + "version": "0.5.17", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.17.tgz", + "integrity": "sha512-+Ut8d9LLqwEvHHJl1+PIHqoyDxFgVN847JTVM3Izi3xHDWPE4UtzzXysMZQs64DMcrJfBeS/uoEP4AD3HQHnQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -9820,6 +9843,21 @@ "url": "https://opencollective.com/core-js" } }, + "node_modules/core-js-pure": { + "version": "3.50.0", + "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.50.0.tgz", + "integrity": "sha512-6GP3Pxz4IKyWjAfa747vIu/jilB5z29JWROLqH/b+pXVcpgh6tM06ZIBwSuglgVqzDYURhOK6oEzTrG0bCHitA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -10283,6 +10321,39 @@ "dev": true, "license": "MIT" }, + "node_modules/dcmjs": { + "version": "0.52.0", + "resolved": "https://registry.npmjs.org/dcmjs/-/dcmjs-0.52.0.tgz", + "integrity": "sha512-0/mT9NACKnwnOnkUx7JAqmWxRcUr7HiCoptw1KhN2StNYE0Hy6+tmpI7CU+lJuBc4rFpcMCalvI8QO6JkJ+7Fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime-corejs3": "7.29.2", + "adm-zip": "0.5.17", + "gl-matrix": "3.4.4", + "lodash.clonedeep": "4.5.0", + "loglevel": "1.9.2", + "ndarray": "1.0.19", + "pako": "2.1.0" + }, + "engines": { + "node": ">=22.13" + } + }, + "node_modules/dcmjs/node_modules/gl-matrix": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz", + "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/dcmjs/node_modules/pako": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/pako/-/pako-2.1.0.tgz", + "integrity": "sha512-w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug==", + "dev": true, + "license": "(MIT AND Zlib)" + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -13296,6 +13367,13 @@ "dev": true, "license": "MIT" }, + "node_modules/iota-array": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz", + "integrity": "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==", + "dev": true, + "license": "MIT" + }, "node_modules/ip-address": { "version": "10.7.2", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.2.tgz", @@ -13399,6 +13477,13 @@ "node": ">=8" } }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true, + "license": "MIT" + }, "node_modules/is-callable": { "version": "1.2.7", "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", @@ -15916,6 +16001,17 @@ "dev": true, "license": "MIT" }, + "node_modules/ndarray": { + "version": "1.0.19", + "resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.0.19.tgz", + "integrity": "sha512-B4JHA4vdyZU30ELBw3g7/p9bZupyew5a7tX1Y/gGeF2hafrPaQZhgrGQfsvgfYbgdFZjYwuEcnaobeM/WMW+HQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "iota-array": "^1.0.0", + "is-buffer": "^1.0.2" + } + }, "node_modules/negotiator": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", diff --git a/package.json b/package.json index a7ef1682f..d143bc6f4 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,11 @@ "files": [ "dist", "src", - "backend-contract" + "backend-contract", + "packages/dicom/core/**/*.ts", + "packages/dicom/vtk/**/*.ts", + "packages/dicom/README.md", + "!packages/dicom/**/__tests__/**" ], "scripts": { "prepare": "node scripts/apply-patches.mjs", @@ -22,17 +26,17 @@ "test:e2e:chrome": "cross-env VITE_SHOW_SAMPLE_DATA=true npm run build && cross-env HEADED=0 wdio run ./wdio.chrome.conf.ts", "test:e2e:chrome:skip-build": "cross-env HEADED=0 wdio run ./wdio.chrome.conf.ts", "test:e2e:dev": "cross-env HEADED=0 VITE_SHOW_SAMPLE_DATA=true concurrently -P \"npm run dev\" \"wdio run ./wdio.dev.conf.ts --watch {@}\"", - "lint": "vue-tsc --noEmit && eslint \"src/**/*.{js,ts,vue}\" \"tests/**/*.{js,ts}\" \"scripts/**/*.mjs\"", - "build:all": "npm run build:dicom && npm run build:resample && npm run build", - "build:dicom": "itk-wasm -s src/io/itk-dicom/ build ", - "build:dicom:debug": "itk-wasm -s src/io/itk-dicom/ build -- -DCMAKE_BUILD_TYPE=Debug", + "lint": "vue-tsc --noEmit && eslint \"src/**/*.{js,ts,vue}\" \"tests/**/*.{js,ts}\" \"scripts/**/*.mjs\" \"packages/dicom/**/*.{js,ts,mjs}\"", + "build:all": "npm run build:resample && npm run build", "build:resample": "itk-wasm -s src/io/resample/ build ", "build:resample:debug": "itk-wasm -s src/io/resample/ build -- -DCMAKE_BUILD_TYPE=Debug", "build:watch": "npm run build -- --watch", - "prettify": "prettier --write src tests", + "prettify": "prettier --write src tests packages/dicom", "docs:dev": "vitepress dev docs", "docs:build": "vitepress build docs", - "docs:preview": "vitepress preview docs" + "docs:preview": "vitepress preview docs", + "dicom:build": "node packages/dicom/scripts/build.mjs", + "dicom:check": "npm run dicom:build && node packages/dicom/scripts/check-consumers.mjs" }, "devDependencies": { "@commitlint/cli": "^21.0.0", @@ -73,13 +77,13 @@ "core-js": "3.47.0", "cors": "^2.8.5", "cross-env": "^10.1.0", + "dcmjs": "^0.52.0", "dicom-parser": "^1.8.21", "dicomweb-client-typed": "^0.8.6", "eslint": "^9.39.1", "eslint-config-prettier": "^10.1.8", "eslint-plugin-vue": "^10.6.2", "fast-deep-equal": "^3.1.3", - "fflate": "0.7.5", "file-saver": "^2.0.5", "gl-matrix": "3.4.3", "globals": "^16.2.0", diff --git a/packages/dicom/README.md b/packages/dicom/README.md new file mode 100644 index 000000000..13b48a597 --- /dev/null +++ b/packages/dicom/README.md @@ -0,0 +1,247 @@ +# Browser DICOM module + +This private directory uses VolView's root install, lockfile and checks. It has +no workspace install or release workflow. VolView imports defining source +modules directly; the root npm distribution includes the core and vtk source +files alongside `dist`, `src` and `backend-contract`. Package tests and +standalone build output are excluded from that distribution. + +- `core/`: byte sources, header reading into structured `DicomDataset` + metadata, collection planning with stable identity, volume allocation and + loading into calibrated typed arrays, and the runtime that owns workers and + requests. It has no Vue, Pinia or vtk.js dependency. +- `vtk/`: a thin adapter that shows a core `Volume` as a `vtkImageData`. + vtk.js is an optional peer, required only by consumers of these modules. + +The package exports concrete module subpaths under `@volview/dicom/core/*` and +`@volview/dicom/vtk/*`; there are no aggregate entry points. + +VolView owns its reactive wrappers, messages, browser state, selections, +annotations, layers, import handling and session provenance. + +## Values and effects + +Instances, plans and volumes are plain values. Only the runtime holds +resources, and only it has `dispose()`. Every asynchronous operation takes an +`AbortSignal`; aborting it is the whole of cancellation. + +```ts +import { createDicomRuntime } from '@volview/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, fromUrl } from '@volview/dicom/core/source/byteSource'; +import { + emptyRegistry, + registerInstances, +} from '@volview/dicom/core/collections/instanceRegistry'; +import { allocateVolume } from '@volview/dicom/core/volume/allocateVolume'; +import { loadVolume } from '@volview/dicom/core/volume/loadVolume'; +import { + applyVolumeUpdate, + toVtkImageData, +} from '@volview/dicom/vtk/volumeImage'; + +const runtime = createDicomRuntime({ + assets: { + pipelineWorkerUrl: new URL( + './assets/itk-wasm-pipeline.min.worker.js', + document.baseURI + ).href, + imageIOUrl: new URL('./assets/image-io', document.baseURI).href, + }, +}); +const { signal } = new AbortController(); + +const sources = [fromBlob(file), fromUrl(url, { fetch: runtime.fetch })]; +const instances = await Promise.all( + sources.map((source) => runtime.readInstance(source, signal)) +); + +const { state, updates } = registerInstances(emptyRegistry, instances); +const allocation = allocateVolume(updates[0]); +if (allocation.kind === 'volume') { + const { volume } = allocation; + const image = toVtkImageData(volume); + for await (const update of loadVolume(volume, { runtime, signal })) { + if ('error' in update) console.error(update.error); + else applyVolumeUpdate(image, volume, update); + } +} +``` + +### Sources + +A `ByteSource` opens a fresh stream for every `read(signal, range?)` and holds +nothing open between reads. `fromBlob` reads slices of a Blob or File. +`fromUrl` issues HTTP Range requests and accepts a server that ignores Range; +pass `runtime.fetch` so requests share the runtime's pool, or any `fetch` for +authentication and other request policies. `readBytes(source, signal, range?)` +reads a source or range into memory. Decoded instances keep no bytes; read the +source again when original bytes are needed. `rangeSupport()` reports whether +a URL source's last ranged response honoured Range. Ranged URL reads bypass +the HTTP cache, since Chrome can answer a Range from an entry an earlier +cancelled read left behind with status 200 and only the range's bytes. + +### Instances + +`runtime.readInstance(source, signal)` reads only the header, stopping at Pixel +Data, and returns a frozen `Instance`: its source, dataset, Part 10 layout, +transfer syntax, ultrasound regions and where the Pixel Data element and its +value sit. The dataset omits private +attributes, including private elements nested in public sequences; use +`readDicomDataset` directly when they are needed. A source without a preamble +or file meta information is read with its transfer syntax assumed and reported +in `layout`. The runtime's `imageImportPolicy: 'skip-radiotherapy'` returns +after the Modality element of RT objects; `'complete-header'` (the default) +reads through the header. + +### Collections + +`registerInstances(state, instances)` is a pure reducer. It returns the next +`state`, the collections whose membership or label changed as `updates`, the +ids a replan dissolved as `removed`, and SOP Instance UIDs re-supplied with +conflicting geometry. Each update carries a stable `id` that starts with the +Series Instance UID, the planned `collection`, `members` in planned order and, +aligned with them, `provenance`: the batch's own instance wherever it +re-supplied one. The first registration of a SOP Instance UID is kept; +instances without one are identified by object. Abandoning an import is not +assigning the returned state. `forgetCollection(state, id)` drops a collection +and its instances so a later import plans them afresh; `isRegistered` checks +whether an object is the registered instance. + +### Volumes + +`allocateVolume(update, options, previous?)` allocates the buffer a planned +collection fills, or reports `{ kind: 'segmentation' }` for SEG, whose labels a +segmentation reader turns into its own image. A `Volume` holds a typed array, +dimensions, components, origin, row-major direction, spacing, spatial metadata, +reconstruction, members, allocation warnings and a per-slice `loaded` mask. +With `previous`, slices it already decoded are copied by instance identity, so +growing a volume never decodes them again. The buffer type comes from the +headers' rescaled value ranges. Ranges beyond 16 bit integers use Float32 +rather than Int32 or Uint32 while every value is within 2^24, and fractional +rescales use Float32 rather than Float64 while Bits Stored is at most 24 and +float32's spacing stays below the slope, since vtk.js converts any other +buffer type to float32 whole on every upload. Decoded values a Float32 volume +would round or merge are rejected. `irregularGeometry: 'preserve-order'` (the +default) keeps approximate spacing for irregular stacks; `'reject'` refuses +them. Neither resamples. Supplied slots must start at zero because the first +member anchors the origin; gaps such as `[0, 2]` are allowed. + +`loadVolume(volume, { runtime, signal, focus?, readAhead? })` is an async +generator of `{ slot, extent, range }` or `{ slot, extent, error }` updates. It +writes decoded pixels into `volume.data` and marks `volume.loaded`. A failure's +extent spans the slices it leaves unloaded, and loading continues. Units load +focus first and then coarse to fine across the stack (`pickNextSlot`); `focus` +is read before every read and decode, so moving it reorders the remaining +work. Reads run ahead of decoding: at most `readAhead` units, defaulting to +the runtime's request concurrency, are being read or waiting to decode. +Aborting `signal`, leaving the loop or disposing the runtime ends the +iteration without throwing. + +The unit is a frame wherever the runtime's decoder table can decode one +without a codec (`planDecode` in `core/pixels/decoderTable.ts`): each frame is +a ranged read from the Pixel Data value (`indexFrames`), decoded on the +calling thread (`decodeNativeFrame`). Every other instance is read and decoded +whole. Once a URL source shows that its server ignores Range, the remaining +frames of that instance come from one read instead of one download each; +until then its frames are read one at a time. + +### Runtime + +`createDicomRuntime(options)` owns the decoder table (`decoders`), the request pool (`requestConcurrency`, +default 24, exposed as `readConcurrency`), the metadata parser workers +(`metadataConcurrency`, or `metadataWorkerFactory` for another asset layout) +and a pool of GDCM decode workers (`decodeConcurrency`, default half the +cores, at most four; each worker carries its own WASM heap). A supplied +`decoder` replaces GDCM and owns its own resources; with one, every instance +goes to it whole unless `decoders` says otherwise. Metadata-only use needs no +decoder or WASM assets. `dispose()` aborts everything pending. + +The default table decodes Implicit and Explicit VR Little Endian and Explicit +VR Big Endian frames natively where the result is identical to GDCM's: +MONOCHROME2 or unsigned 8 bit RGB samples, 8, 16 or 32 bit words with Bits +Stored ending at High Bit (fewer stored bits only in 16 bit words), 16 bit +words only when big endian, one modality rescale for all frames, and no +overlay, curve, Modality LUT, palette or ICC data. Other transfer syntaxes and +declined instances go to GDCM; video and JPEG XL syntaxes fail as known +syntaxes without a decoder. Both paths apply one modality transform to the +entire instance and reject differing per-frame slopes or intercepts. Injected +decoders may support those transforms. Separate single-frame files may have +different transforms. + +### vtk adapter + +`toVtkImageData(volume)` wraps the volume's buffer and geometry without +copying; before any slice decodes its scalar range is a 0 to 255 placeholder. +`applyVolumeUpdate(image, volume, update)` widens the scalar range by a +decoded slice and marks the image modified. `sliceThumbnail(image, slice)` +downsamples one loaded slice to an 8 bit greyscale thumbnail, and +`encodeThumbnailToUri` in `vtk/thumbnail.ts` turns it into a PNG data URI. + +## Geometry and calibration + +Enhanced instances read image geometry and modality transforms from their +shared and per-frame functional groups. Regular spatial frames retain their +stored pixel order, including acquisitions whose frame direction opposes the +row/column cross product. Single-detector reconstructed NM stacks use their +detector patient geometry and signed slice spacing. Gated NM requires temporal +assembly and is rejected. + +OCT shared in-plane spacing is preserved. Calibrated placement between B-scans +requires a matching ophthalmic localizer and remains unsupported. Optical slice +thickness does not define B-scan separation. Vendor-specific ultrasound volume +calibration, RT dose semantics and floating-point parametric maps also require +dedicated import support. VolView skips all RT modalities for both File and HTTP +imports, including RTIMAGE and RTDOSE; these objects do not create a volume. + +`volume.spatialMetadata` reports the applied spacing in image x/y/z order, +including ultrasound region overrides. Each axis records its value, unit (`mm` +or `unknown`), source, and whether it was declared, derived from positions, or +supplied as a display fallback. Reconstruction quality and ultrasound region +limitations are separate from the unit. These are statements about the source +and allocation, not independent calibration. + +Missing physical spacing is permitted for some DICOM objects, including +[secondary captures](https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_A.8.html). +Ordinary patient PixelSpacing and ImagePositionPatient use millimeters without +requiring an additional calibration tag. A fallback value of 1 does not +establish a millimeter scale. A singleton axis does not establish a distance +between slices. + +## Standalone checks + +`npm run dicom:build` emits ES modules and declarations in `packages/dicom/dist`, +including the parser worker, the ITK pipeline worker and the GDCM image reader +assets. Serve the assets from a URL your application controls and pass their +locations explicitly. `npm run dicom:check` builds the package and typechecks +and bundles two small consumers against its emitted JavaScript and +declarations. It rejects VolView application imports and Vue/Pinia +dependencies, and rejects vtk.js in the core consumer. Package boundary tests +also check relative imports and declared dependencies. + +`npm run test:e2e:chrome:skip-build -- --spec tests/specs/dicom-package.e2e.ts` +serves those standalone production bundles, generates its DICOM in memory, and +checks Blob/HTTP metadata, calibrated pixel values, decode worker recovery and +vtk geometry through rendered page output, including a screenshot. + +`tests/specs/dicom-volume-corpus.e2e.ts` exercises pinned public CT, MR and +SPECT files through both File and HTTP sources, plus numeric-padding fixtures. +It checks dimensions, physical geometry, explicit unsupported-topology errors +and the hash of every calibrated voxel through rendered consumer output. Public +URLs, input checksums, independently decoded pixel hashes and provenance are +recorded in `tests/dicomVolumeCorpus.json`; downloads use the ignored dataset +cache. + +`tests/specs/dicom-native-parity.e2e.ts` decodes synthesized instances across +the native format matrix and every cached uncompressed dataset through GDCM +and frame by frame natively, from File and HTTP sources. Wherever the decoder +table plans native frames, both must write identical samples into the volume, +which for a fractional rescale means equal after the same float32 rounding, +and integer GDCM output must equal the native values before any conversion. + +`tests/specs/dicom-volume-composition.e2e.ts` composes downloaded classic CT/PET +series and two MR acquisitions sharing one Series UID. It checks every +collection's ordered SOP membership, complete calibrated voxel hash and +physical geometry after shuffled batch and incremental File/HTTP imports. +`tests/dicomCompositionCorpus.json` records the pinned inputs and independent +expectations. The optional `compositionReference.py` beside the consumer +fixtures reproduces those expectations using pydicom and NumPy from the cache. diff --git a/packages/dicom/__tests__/boundaries.spec.ts b/packages/dicom/__tests__/boundaries.spec.ts new file mode 100644 index 000000000..9acba20c0 --- /dev/null +++ b/packages/dicom/__tests__/boundaries.spec.ts @@ -0,0 +1,95 @@ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { dirname, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; +import { describe, expect, it } from 'vitest'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const manifest = JSON.parse( + readFileSync(resolve(root, 'package.json'), 'utf8') +); +const dependencies = new Set([ + ...Object.keys(manifest.dependencies), + ...Object.keys(manifest.peerDependencies), +]); +const sourceFiles = (directory: string): string[] => + readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const file = resolve(directory, entry.name); + if (entry.isDirectory()) + return entry.name === '__tests__' ? [] : sourceFiles(file); + return entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') + ? [file] + : []; + }); + +const importsOf = (file: string) => { + const source = ts.createSourceFile( + file, + readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest + ); + const imports: string[] = []; + const visit = (node: ts.Node) => { + if ( + (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) + ) + imports.push(node.moduleSpecifier.text); + if ( + ts.isCallExpression(node) && + node.expression.kind === ts.SyntaxKind.ImportKeyword && + node.arguments[0] && + ts.isStringLiteral(node.arguments[0]) + ) + imports.push(node.arguments[0].text); + ts.forEachChild(node, visit); + }; + visit(source); + return imports; +}; + +for (const entry of ['core', 'vtk']) { + describe(`DICOM ${entry} dependency boundary`, () => { + const sources = sourceFiles(resolve(root, entry)); + it.each(sources.map((file) => relative(root, file)))( + '%s stays inside its declared boundary', + (name) => { + for (const specifier of importsOf(resolve(root, name))) { + if (specifier.startsWith('.')) { + const target = relative( + root, + resolve(dirname(resolve(root, name)), specifier) + ); + expect(target.startsWith('..')).toBe(false); + if (entry === 'core') expect(target.startsWith('vtk/')).toBe(false); + } else { + const dependency = specifier.startsWith('@') + ? specifier.split('/').slice(0, 2).join('/') + : specifier.split('/')[0]; + expect(dependencies.has(dependency), specifier).toBe(true); + expect(['vue', 'pinia', '@vueuse/core']).not.toContain(dependency); + if (entry === 'core') + expect(dependency).not.toBe('@kitware/vtk.js'); + } + } + } + ); + }); +} + +it('VolView imports defining core and vtk modules directly', () => { + const repository = resolve(root, '../..'); + for (const file of sourceFiles(resolve(repository, 'src'))) { + for (const specifier of importsOf(file)) { + const target = specifier.startsWith('@/') + ? resolve(repository, specifier.slice(2)) + : resolve(dirname(file), specifier); + if (!target.startsWith(`${root}/`)) continue; + const module = relative(root, target).replace(/\.ts$/, ''); + expect(module, relative(repository, file)).toMatch(/^(core|vtk)\/.+/); + expect(module.endsWith('/index'), relative(repository, file)).toBe(false); + expect(existsSync(`${target.replace(/\.ts$/, '')}.ts`)).toBe(true); + } + } +}); diff --git a/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts b/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts new file mode 100644 index 000000000..6efd79e2f --- /dev/null +++ b/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts @@ -0,0 +1,331 @@ +import { describe, it, expect } from 'vitest'; +import { assignIds, encodeCollectionKey } from '../assignCollectionIds'; +import type { CommittedCollection } from '../assignCollectionIds'; +import { + ORIENTATION_TOLERANCE, + planDicomCollections, +} from '../planDicomCollections'; +import type { CollectionKey, DicomCollection } from '../planDicomCollections'; +import { + IDENTITY_ORIENTATION, + clone, + makeFacts, + tiltedOrientation, +} from './instanceFactsFixture'; + +const SERIES_KEY = 'series-1'; + +// A second orientation row rotation the bucketing tolerance still accepts. +const WITHIN_TOLERANCE = Math.acos(1 - ORIENTATION_TOLERANCE / 2); + +const keyOf = (orientation: string): CollectionKey => ({ + seriesKey: SERIES_KEY, + parts: [ + ['seriesNumber', '1'], + ['sliceThickness', '1'], + ['orientation', orientation], + ], +}); + +const collectionOf = ( + uids: Array, + key = keyOf('1,0,0,0,1,0') +): DicomCollection => ({ + key, + members: uids.map((uid) => makeFacts(uid)), + order: 'spatial', + reconstruction: { + kind: 'regular', + sliceSpacing: null, + slots: uids.map((_, index) => index), + }, + orientation: [1, 0, 0, 0, 1, 0], + label: null, + diagnostics: [], + warnings: [], +}); + +const planOf = (...collections: DicomCollection[]) => ({ collections }); + +const idsOf = (collections: Array<{ id: string }>) => + collections.map((c) => c.id); + +describe('encodeCollectionKey', () => { + it('encodes equal keys identically', () => { + expect(encodeCollectionKey(keyOf('1,0,0,0,1,0'))).toBe( + encodeCollectionKey(keyOf('1,0,0,0,1,0')) + ); + }); + + // The structured key this encodes: the same characters the encoding joins on, + // smuggled inside a series key, a rule name or a value. + const structured: CollectionKey = { + seriesKey: SERIES_KEY, + parts: [ + ['rows', '4'], + ['columns', '8'], + ], + }; + + const smuggled: Array<[string, CollectionKey]> = [ + [ + 'the series key', + { seriesKey: `${SERIES_KEY}|rows=.4`, parts: [['columns', '8']] }, + ], + [ + 'a rule name', + { seriesKey: SERIES_KEY, parts: [['rows=.4|columns', '8']] }, + ], + ['a value', { seriesKey: SERIES_KEY, parts: [['rows', '4|columns=.8']] }], + ]; + + it.each(smuggled)( + 'does not collide when a separator hides in %s', + (_where, key) => { + expect(encodeCollectionKey(key)).not.toBe( + encodeCollectionKey(structured) + ); + } + ); + + it('separates a missing value from the literal strings for it', () => { + const literals = [null, 'null', '', '~'].map( + (value): CollectionKey => ({ + seriesKey: SERIES_KEY, + parts: [['rows', value]], + }) + ); + + const encodings = literals.map(encodeCollectionKey); + + expect(new Set(encodings).size).toBe(literals.length); + }); + + it('separates keys differing only in series key or rule name', () => { + const base: CollectionKey = { + seriesKey: 'series-1', + parts: [['rows', '4']], + }; + const otherSeries: CollectionKey = { + seriesKey: 'series-2', + parts: [['rows', '4']], + }; + const otherRule: CollectionKey = { + seriesKey: 'series-1', + parts: [['columns', '4']], + }; + + const encodings = [base, otherSeries, otherRule].map(encodeCollectionKey); + + expect(new Set(encodings).size).toBe(3); + }); +}); + +describe('assignIds', () => { + it('mints the encoded key when nothing is committed', () => { + const collection = collectionOf(['a', 'b']); + + const { collections } = assignIds(planOf(collection), []); + + expect(collections[0].id).toBe(encodeCollectionKey(collection.key)); + }); + + it('gives distinct collections distinct ids', () => { + const first = collectionOf(['a'], keyOf('1,0,0,0,1,0')); + const second = collectionOf(['b'], keyOf('0,1,0,0,0,1')); + + const { collections } = assignIds(planOf(first, second), []); + + expect(new Set(idsOf(collections)).size).toBe(2); + }); + + it('keeps the committed id when key and members are unchanged', () => { + const collection = collectionOf(['a', 'b']); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['a', 'b'] }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).toBe('visible-1'); + }); + + it('keeps the committed id when a later batch changes the bucket key', () => { + // A lower-sorting SOP UID takes over as the orientation bucket's + // representative, so the second batch keys the same dataset differently. + const firstBatch = [ + makeFacts('uid-m', { + orientation: IDENTITY_ORIENTATION, + projectedPosition: 0, + }), + makeFacts('uid-n', { + orientation: IDENTITY_ORIENTATION, + projectedPosition: 1, + }), + ]; + const newcomer = makeFacts('uid-a', { + orientation: tiltedOrientation(WITHIN_TOLERANCE), + projectedPosition: 2, + }); + + const before = assignIds( + planDicomCollections({ seriesKey: SERIES_KEY, instances: firstBatch }), + [] + ); + const committed = before.collections.map((collection) => ({ + id: collection.id, + sopInstanceUids: collection.members.flatMap((member) => + member.sopInstanceUid === null ? [] : [member.sopInstanceUid] + ), + })); + const after = assignIds( + planDicomCollections({ + seriesKey: SERIES_KEY, + instances: [...firstBatch, newcomer], + }), + committed + ); + + expect(after.collections).toHaveLength(1); + expect(encodeCollectionKey(after.collections[0].key)).not.toBe( + encodeCollectionKey(before.collections[0].key) + ); + expect(after.collections[0].id).toBe(before.collections[0].id); + expect(after.collections[0].id).not.toBe( + encodeCollectionKey(after.collections[0].key) + ); + }); + + it('gives a committed id to the collection holding most of its members', () => { + const majority = collectionOf(['a', 'b', 'c'], keyOf('1,0,0,0,1,0')); + const remainder = collectionOf(['d'], keyOf('0,1,0,0,0,1')); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, + ]; + + const { collections } = assignIds(planOf(majority, remainder), committed); + + expect(collections[0].id).toBe('visible-1'); + expect(collections[1].id).not.toBe('visible-1'); + }); + + it('mints for both halves of an evenly split committed collection', () => { + const left = collectionOf(['a', 'b'], keyOf('1,0,0,0,1,0')); + const right = collectionOf(['c', 'd'], keyOf('0,1,0,0,0,1')); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, + ]; + + const { collections } = assignIds(planOf(left, right), committed); + + expect(idsOf(collections)).not.toContain('visible-1'); + expect(new Set(idsOf(collections)).size).toBe(2); + }); + + it('mints when nothing overlaps, without reusing a committed id', () => { + const collection = collectionOf(['a']); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['x', 'y'] }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).not.toBe('visible-1'); + expect(collections[0].id).toBe(encodeCollectionKey(collection.key)); + }); + + it('never mints an id already taken by a committed collection', () => { + const collection = collectionOf(['a']); + const committed: CommittedCollection[] = [ + { + id: encodeCollectionKey(collection.key), + sopInstanceUids: ['x'], + }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).not.toBe(committed[0].id); + }); + + it('prefers the committed collection it overlaps most', () => { + const collection = collectionOf(['a', 'b', 'c', 'd', 'e']); + const committed: CommittedCollection[] = [ + { id: 'small', sopInstanceUids: ['a', 'b'] }, + { id: 'large', sopInstanceUids: ['c', 'd', 'e'] }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).toBe('large'); + }); + + it('breaks an equal overlap on the smallest committed id', () => { + const collection = collectionOf(['a', 'b', 'c', 'd']); + const committed: CommittedCollection[] = [ + { id: 'zeta', sopInstanceUids: ['a', 'b'] }, + { id: 'alpha', sopInstanceUids: ['c', 'd'] }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).toBe('alpha'); + }); + + it('measures overlap only on members that have a SOP Instance UID', () => { + const collection = collectionOf([null, 'a']); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['a'] }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).toBe('visible-1'); + }); + + it('mints for a collection whose members all lack a SOP Instance UID', () => { + const collection = collectionOf([null, null]); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['a'] }, + ]; + + const { collections } = assignIds(planOf(collection), committed); + + expect(collections[0].id).not.toBe('visible-1'); + }); + + it('carries the planned collections through in order, only adding an id', () => { + const first = collectionOf(['a'], keyOf('1,0,0,0,1,0')); + const second: DicomCollection = { + ...collectionOf(['b'], keyOf('0,1,0,0,0,1')), + order: 'instance-number', + diagnostics: ['b has no position'], + }; + + const { collections } = assignIds(planOf(first, second), []); + + expect(collections).toHaveLength(2); + expect(collections[0].key).toEqual(first.key); + expect(collections[0].members).toEqual(first.members); + expect(collections[1].order).toBe('instance-number'); + expect(collections[1].diagnostics).toEqual(['b has no position']); + expect(collections[1].members[0]).toBe(second.members[0]); + }); + + it('does not mutate the plan or the committed collections', () => { + const plan = planOf( + collectionOf(['a', 'b'], keyOf('1,0,0,0,1,0')), + collectionOf(['c'], keyOf('0,1,0,0,0,1')) + ); + const committed: CommittedCollection[] = [ + { id: 'visible-1', sopInstanceUids: ['a', 'b'] }, + ]; + const planBefore = clone(plan); + const committedBefore = clone(committed); + + assignIds(plan, committed); + + expect(clone(plan)).toEqual(planBefore); + expect(clone(committed)).toEqual(committedBefore); + }); +}); diff --git a/packages/dicom/core/collections/__tests__/dicomTags.spec.ts b/packages/dicom/core/collections/__tests__/dicomTags.spec.ts new file mode 100644 index 000000000..d808e36d0 --- /dev/null +++ b/packages/dicom/core/collections/__tests__/dicomTags.spec.ts @@ -0,0 +1,12 @@ +import { describe, it, expect } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; + +describe('dicomTags', () => { + it.each([ + ['SliceThickness', '0018|0050'], + ['SequenceName', '0018|0024'], + ['SeriesDate', '0008|0021'], + ])('names %s', (name, tag) => { + expect(Tags[name]).toBe(tag); + }); +}); diff --git a/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts b/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts new file mode 100644 index 000000000..4d87b9fd4 --- /dev/null +++ b/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts @@ -0,0 +1,202 @@ +import { Tags } from '../../metadata/dicomTags'; + +/** + * Real Imaging Data Commons (IDC) series behind the acquisition-split rules. + * + * Entries are keyed by SeriesInstanceUID: bucket paths, folder UUIDs, and + * portal URLs all change between IDC releases, the UID does not. Fetch one by + * searching the UID at portal.imaging.datacommons.cancer.gov, or with the + * idc-index package: + * + * from idc_index import IDCClient + * IDCClient().download_from_selection( + * seriesInstanceUID='', downloadDir='.') + * + * `groups` mirrors the real per-group tag values and slice layout, with + * positions projected onto the slice normal, in mm. + */ + +export type SliceGroup = { + /** Tag values stamped on every slice of the group, keyed by 'gggg|eeee'. */ + tags: Record; + /** Slice positions along the normal, in mm. */ + zs: number[]; +}; + +export type IdcSeriesFixture = { + seriesInstanceUID: string; + seriesDescription: string; + vendor: string; + /** What the series is and why it forces the rule it tests. */ + why: string; + groups?: SliceGroup[]; +}; + +const steps = (start: number, count: number, step: number) => + Array.from({ length: count }, (_, i) => start + i * step); + +export const dceEightPhase: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.7695.4164.334885423614895574619945040495', + seriesDescription: 'ISPY2: VOLSER: uni-lateral cropped: original DCE', + vendor: 'GE', + why: + 'DCE breast MR: eight timepoints re-scan one identical 80-slice Z range ' + + 'in a single series. No AcquisitionNumber at all; only ' + + 'TemporalPositionIdentifier separates the timepoints. Loaded merged, ' + + 'every position appears eight times.', + groups: steps(0, 8, 1).map((phase) => ({ + tags: { [Tags.TemporalPositionIdentifier]: String(phase) }, + zs: steps(-81.198, 80, 2.0), + })), +}; + +export const dceSevenPhasePhilips: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.7695.4164.327395145625810010102069976322', + seriesDescription: 'ISPY2: 15ML OMNI T1 FS DYN SENSE 5', + vendor: 'Philips', + why: + 'DCE breast MR: seven timepoints (TemporalPositionIdentifier 1 through ' + + '7), 158 slices each over one Z range. Shows the split holds across ' + + 'vendors and with 1-based numbering.', + groups: steps(1, 7, 1).map((phase) => ({ + tags: { [Tags.TemporalPositionIdentifier]: String(phase) }, + zs: steps(-83.107, 158, 1.0), + })), +}; + +export const dixonDualEcho: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.9203.4004.413147664284321913537786821717', + seriesDescription: 'T1 AX IN_OUT_160 TR MBH', + vendor: 'Siemens', + why: + 'In-phase/opposed-phase Dixon in one series: two echoes (TE 2.4/5.04) ' + + 'over one identical 34-slice range, one AcquisitionNumber, no ' + + 'TemporalPositionIdentifier. Only EchoNumbers separates them; the ' + + 'categorize pipeline cannot (SequenceName is *fl2d2 for both echoes).', + groups: ['1', '2'].map((echo) => ({ + tags: { + [Tags.AcquisitionNumber]: '1', + [Tags.EchoNumbers]: echo, + }, + zs: steps(-107.502, 34, 7.8), + })), +}; + +export const dixonUnevenEchoes: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.1620.1226.196512451812657389463383990773', + seriesDescription: 'AXL_IN_OUT_ABD', + vendor: 'Siemens', + why: + 'Dixon dual-echo where echo 1 has 13 slices and echo 2 has 12 over the ' + + 'same range; unequal group sizes must still split.', + groups: [ + { + tags: { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: '1' }, + zs: steps(0, 13, 7.8), + }, + { + tags: { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: '2' }, + zs: steps(0, 12, 7.8), + }, + ], +}; + +export const dwiMultiBValue: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.7695.4164.198361347871486858845671445367', + seriesDescription: 'ACRIN-6698: DWI_Multi_bValue', + vendor: 'Philips', + why: + 'Diffusion MR: 30 positions repeated at b-values 0, 100, 600, and 800. ' + + 'AcquisitionNumber, TemporalPositionIdentifier, and EchoNumbers are ' + + 'constant, so DiffusionBValue is the only standard discriminator.', + groups: [0, 100, 600, 800].map((bValue) => ({ + tags: { + [Tags.AcquisitionNumber]: '6', + [Tags.TemporalPositionIdentifier]: '1', + [Tags.EchoNumbers]: '1', + [Tags.DiffusionBValue]: String(bValue), + }, + zs: steps(-67.0785, 30, 4.0), + })), +}; + +export const bilateralSagittalSlabs: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.66737955842913643997059729379406867951', + seriesDescription: 'ISPY2: SAG IR', + vendor: 'GE', + why: + 'Bilateral sagittal breast slabs: StackID 1 and 2 cover two 4mm stacks ' + + 'with a 42mm gap, one orientation, one acquisition, all positions ' + + 'distinct. This series is why StackID is NOT a split discriminator: ' + + 'nothing overlaps, so the overlap gate keeps a StackID-like tag from ' + + 'tearing it apart. One collection is not one regular volume, though: no ' + + 'even lattice holds both slabs, so the reconstruction reports an ' + + 'irregular stack and warns, rather than fitting the endpoints to a ' + + 'fabricated 4.59mm spacing.', + groups: [ + { + tags: { [Tags.AcquisitionNumber]: '1', '0020|9056': '1' }, + zs: steps(-156.488, 31, 4.0), + }, + { + tags: { [Tags.AcquisitionNumber]: '1', '0020|9056': '2' }, + zs: steps(5.951, 35, 4.0), + }, + ], +}; + +export const partialTemporalTags: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.7695.4164.232713885104107279235403827078', + seriesDescription: 'ISPY2: Ax Vibrant PRE/POST', + vendor: 'GE', + why: + 'Seven acquisitions re-scanning one range, but ' + + 'TemporalPositionIdentifier is present on only part of the slices. ' + + 'AcquisitionNumber must do the split, and the incomplete temporal tag ' + + 'must not sub-split or block anything.', + groups: [ + { + tags: { + [Tags.AcquisitionNumber]: '1', + [Tags.TemporalPositionIdentifier]: '1', + }, + zs: steps(-60, 36, 2.0), + }, + // The rest of acquisition 1 carries no temporal tag at all. + { tags: { [Tags.AcquisitionNumber]: '1' }, zs: steps(12, 36, 2.0) }, + ...steps(2, 6, 1).map((acq) => ({ + tags: { + [Tags.AcquisitionNumber]: String(acq), + [Tags.TemporalPositionIdentifier]: String(acq), + }, + zs: steps(-60, 72, 2.0), + })), + ], +}; + +export const doubledAcquisition: IdcSeriesFixture = { + seriesInstanceUID: + '1.3.6.1.4.1.14519.5.2.1.7695.1700.103847508594300579711113977161', + seriesDescription: 'IR-SPGR-SAG', + vendor: 'GE', + why: + 'Acquisition 1 holds 74 slices; acquisition 2 holds 148 slices at those ' + + 'same 74 positions. The split is right and the acquisition-2 volume must ' + + 'still carry the duplicate-position warning. Same shape in IDC series ' + + '1.3.6.1.4.1.14519.5.2.1.7695.2311.133871731749882407434486842181 ' + + '(LEFT - Dynamic-3dfgre, acquisition values 0 and 2).', + groups: [ + { tags: { [Tags.AcquisitionNumber]: '1' }, zs: steps(-214.177, 74, 2.5) }, + { + tags: { [Tags.AcquisitionNumber]: '2' }, + zs: [...steps(-214.177, 74, 2.5), ...steps(-214.177, 74, 2.5)], + }, + ], +}; diff --git a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts new file mode 100644 index 000000000..c200bf49f --- /dev/null +++ b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts @@ -0,0 +1,404 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, expect, it } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import { + readInstanceFacts as readStructuredFacts, + seriesKeyOf as structuredSeriesKeyOf, +} from '../instanceFacts'; + +const INSTANCE_NUMBER_TAG = '0020|0013'; + +// readDicomTags hands back DICOM's own padding, so every fixture value here is +// written the way the reader returns it. +const metadata = (overrides: Record = {}) => { + const entries: Array<[string, string]> = [ + [Tags.SOPInstanceUID, '1.2.3.4'], + [Tags.SeriesInstanceUID, '1.2.3'], + [Tags.StudyInstanceUID, '1.2'], + [Tags.PatientID, 'patient-1'], + [Tags.SeriesNumber, '1 '], + [Tags.SliceThickness, '1 '], + [Tags.SeriesDate, '20240101'], + [Tags.Rows, '4'], + [Tags.Columns, '6'], + [Tags.SamplesPerPixel, '1'], + [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0 '], + [Tags.ImagePositionPatient, '10\\20\\30 '], + [Tags.PixelSpacing, '0.5\\0.75'], + [INSTANCE_NUMBER_TAG, '5 '], + ]; + Object.entries(overrides).forEach(([tag, value]) => { + const existing = entries.find((entry) => entry[0] === tag); + if (existing) existing[1] = value; + else entries.push([tag, value]); + }); + return entries; +}; + +const without = (tag: string) => metadata().filter((entry) => entry[0] !== tag); + +describe('readInstanceFacts', () => { + it('names the instance number tag the planner orders on', () => { + expect(Tags.InstanceNumber).toBe(INSTANCE_NUMBER_TAG); + }); + + it('reads every fact the planner compares', () => { + expect(readInstanceFacts(metadata())).toEqual({ + sopInstanceUid: '1.2.3.4', + seriesInstanceUid: '1.2.3', + seriesNumber: '1', + sequenceName: null, + sliceThickness: '1', + seriesDate: '20240101', + rows: '4', + columns: '6', + samplesPerPixel: '1', + numberOfFrames: '1', + orientation: [1, 0, 0, 0, 1, 0], + position: [10, 20, 30], + projectedPosition: 30, + pixelSpacing: [0.5, 0.75], + instanceNumber: 5, + acquisitionNumber: null, + temporalPositionIdentifier: null, + echoNumbers: null, + diffusionBValue: null, + }); + }); + + it('reads an instance with no tags at all as entirely unknown', () => { + expect(readInstanceFacts([])).toEqual({ + sopInstanceUid: null, + seriesInstanceUid: null, + seriesNumber: null, + sequenceName: null, + sliceThickness: null, + seriesDate: null, + rows: null, + columns: null, + samplesPerPixel: null, + numberOfFrames: '1', + orientation: null, + position: null, + projectedPosition: null, + pixelSpacing: null, + instanceNumber: null, + acquisitionNumber: null, + temporalPositionIdentifier: null, + echoNumbers: null, + diffusionBValue: null, + }); + }); + + it.each([ + ['SeriesNumber', Tags.SeriesNumber, 'seriesNumber'], + ['SequenceName', Tags.SequenceName, 'sequenceName'], + ['SliceThickness', Tags.SliceThickness, 'sliceThickness'], + ['SeriesDate', Tags.SeriesDate, 'seriesDate'], + ['Rows', Tags.Rows, 'rows'], + ['Columns', Tags.Columns, 'columns'], + ['SamplesPerPixel', Tags.SamplesPerPixel, 'samplesPerPixel'], + ] as const)( + 'reads a zero length %s as absent, not as an empty string', + (_name, tag, fact) => { + expect(readInstanceFacts(metadata({ [tag]: '' }))[fact]).toBeNull(); + expect(readInstanceFacts(metadata({ [tag]: ' ' }))[fact]).toBeNull(); + } + ); + + it.each([ + ['SeriesNumber', Tags.SeriesNumber, 'seriesNumber'], + ['SliceThickness', Tags.SliceThickness, 'sliceThickness'], + ['Rows', Tags.Rows, 'rows'], + ['Columns', Tags.Columns, 'columns'], + ['SamplesPerPixel', Tags.SamplesPerPixel, 'samplesPerPixel'], + ['NumberOfFrames', Tags.NumberOfFrames, 'numberOfFrames'], + ] as const)( + 'normalizes the numeric spelling of %s so 04 and 4.0 are one value', + (_name, tag, fact) => { + const readFact = (value: string) => + readInstanceFacts(metadata({ [tag]: value }))[fact]; + expect(readFact('4')).toBe('4'); + expect(readFact('04')).toBe('4'); + expect(readFact('4.0')).toBe('4'); + expect(readFact(' 4 ')).toBe('4'); + expect(readFact('1.50')).toBe('1.5'); + } + ); + + // A study date's leading zeros are part of the value, so it stays text. + it('keeps a series date as text rather than as a number', () => { + expect( + readInstanceFacts(metadata({ [Tags.SeriesDate]: '00240101 ' })).seriesDate + ).toBe('00240101'); + }); + + it('keeps a sequence name as text', () => { + expect( + readInstanceFacts(metadata({ [Tags.SequenceName]: '007 ' })).sequenceName + ).toBe('007'); + }); + + it('trims the padding DICOM adds to odd length identifiers', () => { + const facts = readInstanceFacts( + metadata({ + [Tags.SOPInstanceUID]: '1.2.3.4 ', + [Tags.SeriesInstanceUID]: '1.2.3 ', + }) + ); + expect(facts.sopInstanceUid).toBe('1.2.3.4'); + expect(facts.seriesInstanceUid).toBe('1.2.3'); + }); + + it.each([ + ['a missing tag', without(Tags.ImageOrientationPatient)], + [ + 'too few cosines', + metadata({ [Tags.ImageOrientationPatient]: '1\\0\\0' }), + ], + [ + 'a non numeric cosine', + metadata({ [Tags.ImageOrientationPatient]: '1\\0\\0\\0\\x\\0' }), + ], + ])('reads an orientation with %s as unknown', (_case, entries) => { + const facts = readInstanceFacts(entries); + expect(facts.orientation).toBeNull(); + expect(facts.projectedPosition).toBeNull(); + }); + + it.each([ + ['a missing tag', without(Tags.ImagePositionPatient)], + ['too few coordinates', metadata({ [Tags.ImagePositionPatient]: '1\\2' })], + [ + 'a non numeric coordinate', + metadata({ [Tags.ImagePositionPatient]: '1\\2\\z' }), + ], + ])('reads a position with %s as unknown', (_case, entries) => { + const facts = readInstanceFacts(entries); + expect(facts.position).toBeNull(); + expect(facts.projectedPosition).toBeNull(); + }); + + it.each([ + ['a blank component', '1\\\\3'], + ['a trailing blank component', '1\\2\\'], + ['a whitespace component', '1\\ \\3'], + ])('reads a position with %s as unknown, not as a zero', (_case, value) => { + const facts = readInstanceFacts( + metadata({ [Tags.ImagePositionPatient]: value }) + ); + expect(facts.position).toBeNull(); + expect(facts.projectedPosition).toBeNull(); + }); + + it.each([ + ['an all zero basis', '0\\0\\0\\0\\0\\0'], + ['a zero length row', '0\\0\\0\\0\\1\\0'], + ['a row and column that are the same axis', '1\\0\\0\\1\\0\\0'], + ['a row and column 45 degrees apart', '1\\0\\0\\0.7071\\0.7071\\0'], + ['a blank cosine', '1\\0\\0\\0\\\\0'], + ])('reads %s as no orientation at all', (_case, value) => { + const facts = readInstanceFacts( + metadata({ [Tags.ImageOrientationPatient]: value }) + ); + expect(facts.orientation).toBeNull(); + expect(facts.projectedPosition).toBeNull(); + }); + + // A DS value carries a printed decimal, so exact unit length is not on offer. + it('normalizes cosines that are within the tolerance of unit length', () => { + const facts = readInstanceFacts( + metadata({ + [Tags.ImageOrientationPatient]: '0.99998\\0\\0\\0\\1.00002\\0', + }) + ); + + expect(facts.orientation).not.toBeNull(); + expect(facts.orientation![0]).toBeCloseTo(1, 12); + expect(facts.orientation![4]).toBeCloseTo(1, 12); + expect(facts.projectedPosition).toBeCloseTo(30, 12); + }); + + // GDCM rescales whatever cosines it is given, so a basis printed to three + // decimals or written at the wrong length loads as the scanner meant it + // rather than landing in the unreadable bucket. + it.each([ + [ + 'an oblique printed to three decimals', + '0.707\\0.707\\0\\-0.707\\0.707\\0', + [0.7071, 0.7071, 0, -0.7071, 0.7071, 0], + ], + [ + 'a row written at twice unit length', + '2\\0\\0\\0\\1\\0', + [1, 0, 0, 0, 1, 0], + ], + ])('rescales %s to unit axes', (_case, value, expected) => { + const facts = readInstanceFacts( + metadata({ [Tags.ImageOrientationPatient]: value }) + ); + + expect(facts.orientation).not.toBeNull(); + facts.orientation!.forEach((cosine, index) => + expect(cosine).toBeCloseTo(expected[index], 3) + ); + expect(facts.projectedPosition).toBeCloseTo(30, 10); + }); + + it('accepts cosines a printed digit away from square', () => { + const facts = readInstanceFacts( + metadata({ + [Tags.ImageOrientationPatient]: '0.7071\\0.7071\\0\\-0.7072\\0.7070\\0', + }) + ); + + expect(facts.orientation).not.toBeNull(); + expect(facts.projectedPosition).toBeCloseTo(30, 3); + }); + + it.each([ + ['zero', '0\\0.5'], + ['negative', '-1\\0.5'], + ['blank', '\\0.5'], + ])('reads a %s pixel spacing as unknown', (_case, value) => { + expect( + readInstanceFacts(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing + ).toBeNull(); + }); + + it('projects the position onto the slice normal, not onto z', () => { + // Rows run along +y and columns along +z, so the normal is +x. + const facts = readInstanceFacts( + metadata({ [Tags.ImageOrientationPatient]: '0\\1\\0\\0\\0\\1' }) + ); + expect(facts.projectedPosition).toBeCloseTo(10, 10); + }); + + it('projects onto the normal with the cosines in row then column order', () => { + // Swapping the two rows of the case above flips the normal to -x. + const facts = readInstanceFacts( + metadata({ [Tags.ImageOrientationPatient]: '0\\0\\1\\0\\1\\0' }) + ); + expect(facts.projectedPosition).toBeCloseTo(-10, 10); + }); + + it.each([ + ['a missing tag', without(Tags.PixelSpacing), null], + ['a single value', metadata({ [Tags.PixelSpacing]: '0.5' }), null], + [ + 'a non numeric value', + metadata({ [Tags.PixelSpacing]: '0.5\\bad' }), + null, + ], + ])('reads a pixel spacing with %s as unknown', (_case, entries) => { + expect(readInstanceFacts(entries).pixelSpacing).toBeNull(); + }); + + it.each([ + ['5 ', 5], + ['+5', 5], + ['-3', -3], + ])('reads the instance number %s as a number', (value, expected) => { + expect( + readInstanceFacts(metadata({ [INSTANCE_NUMBER_TAG]: value })) + .instanceNumber + ).toBe(expected); + }); + + it.each([ + ['a missing tag', without(INSTANCE_NUMBER_TAG)], + ['an empty value', metadata({ [INSTANCE_NUMBER_TAG]: ' ' })], + ['a non numeric value', metadata({ [INSTANCE_NUMBER_TAG]: 'first' })], + ])('reads an instance number with %s as unknown', (_case, entries) => { + expect(readInstanceFacts(entries).instanceNumber).toBeNull(); + }); + + it('does not mutate the metadata it reads', () => { + const entries = metadata(); + const before = JSON.parse(JSON.stringify(entries)); + readInstanceFacts(entries); + expect(entries).toEqual(before); + }); +}); + +describe('seriesKeyOf', () => { + it('is the series instance uid so a collection id carries it as a prefix', () => { + expect(seriesKeyOf(metadata())).toBe('1.2.3'); + expect(seriesKeyOf(metadata({ [Tags.SeriesInstanceUID]: '1.2.3 ' }))).toBe( + '1.2.3' + ); + }); + + it('separates two series that differ only in series instance uid', () => { + expect( + seriesKeyOf(metadata({ [Tags.SeriesInstanceUID]: '1.2.4' })) + ).not.toBe(seriesKeyOf(metadata())); + }); + + it('never reuses a series key for an instance that has no series uid', () => { + const anonymous = seriesKeyOf(metadata({ [Tags.SeriesInstanceUID]: '' })); + expect(anonymous).not.toBe(''); + expect(anonymous).not.toBe(seriesKeyOf(metadata())); + }); + + it('falls back to the study and patient when the series uid is absent', () => { + const key = (overrides: Record) => + seriesKeyOf(metadata({ [Tags.SeriesInstanceUID]: '', ...overrides })); + + expect(key({})).toBe(key({})); + expect(key({ [Tags.StudyInstanceUID]: '9.9' })).not.toBe(key({})); + expect(key({ [Tags.PatientID]: 'patient-2' })).not.toBe(key({})); + }); + + // Concatenation alone would tie these two, since only the split moves. + it('escapes the fallback parts so a moved separator changes the key', () => { + const key = (study: string, patient: string) => + seriesKeyOf( + metadata({ + [Tags.SeriesInstanceUID]: '', + [Tags.StudyInstanceUID]: study, + [Tags.PatientID]: patient, + }) + ); + expect(key('a|b', 'c')).not.toBe(key('a', 'b|c')); + expect(key('a:b', 'c')).not.toBe(key('a', 'b:c')); + }); + + it('does not mutate the metadata it reads', () => { + const entries = metadata(); + const before = JSON.parse(JSON.stringify(entries)); + seriesKeyOf(entries); + expect(entries).toEqual(before); + }); +}); + +function readInstanceFacts(tags: Iterable) { + return readStructuredFacts(datasetFromTags(tags)); +} +function seriesKeyOf(tags: Iterable) { + return structuredSeriesKeyOf(datasetFromTags(tags)); +} + +describe('single-frame and spacing normalization', () => { + it.each([undefined, '', ' ', '1', '01'])( + 'defaults NumberOfFrames %s to one', + (frames) => { + expect( + readStructuredFacts( + datasetFromTags( + frames === undefined ? [] : [[Tags.NumberOfFrames, frames]] + ) + ).numberOfFrames + ).toBe('1'); + } + ); + + it.each(['0.5\\0.75\\2.5', '0.5\\0.75\\'])( + 'retains the first two PixelSpacing values in %s', + (value) => { + expect( + readInstanceFacts(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing + ).toEqual([0.5, 0.75]); + } + ); +}); diff --git a/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts b/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts new file mode 100644 index 000000000..7e22ea469 --- /dev/null +++ b/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts @@ -0,0 +1,60 @@ +import type { InstanceFacts } from '../planDicomCollections'; + +export const IDENTITY_ORIENTATION = [1, 0, 0, 0, 1, 0]; + +// Rotates the second orientation row by theta, leaving both rows unit length. +export const tiltedOrientation = (theta: number) => [ + 1, + 0, + 0, + 0, + Math.cos(theta), + Math.sin(theta), +]; + +export const orientationKeyValue = (orientation: number[]) => + orientation.map(String).join(','); + +// The position and its projection are one fact, so a fixture naming only the +// projection gets the axial position that produces it. +const positionFor = (overrides: Partial) => { + if ('position' in overrides) return overrides.position ?? null; + const projected = + 'projectedPosition' in overrides ? overrides.projectedPosition : 0; + return projected === null || projected === undefined + ? null + : [0, 0, projected]; +}; + +const defaults = (sopInstanceUid: string | null): InstanceFacts => ({ + sopInstanceUid, + seriesInstanceUid: 'series-1', + seriesNumber: '1', + sequenceName: null, + sliceThickness: '1', + seriesDate: '20240101', + rows: '4', + columns: '4', + samplesPerPixel: '1', + numberOfFrames: null, + orientation: IDENTITY_ORIENTATION, + position: [0, 0, 0], + projectedPosition: 0, + pixelSpacing: [1, 1], + instanceNumber: 1, + acquisitionNumber: null, + temporalPositionIdentifier: null, + echoNumbers: null, + diffusionBValue: null, +}); + +export const makeFacts = ( + sopInstanceUid: string | null, + overrides: Partial = {} +): InstanceFacts => ({ + ...defaults(sopInstanceUid), + ...overrides, + position: positionFor(overrides), +}); + +export const clone = (value: unknown) => JSON.parse(JSON.stringify(value)); diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts new file mode 100644 index 000000000..caf38871a --- /dev/null +++ b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -0,0 +1,204 @@ +import { describe, expect, it } from 'vitest'; +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { Tags } from '../../metadata/dicomTags'; +import type { Instance } from '../../instance/readInstance'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { + emptyRegistry, + forgetCollection, + isRegistered, + registerInstances, + type RegistryState, +} from '../instanceRegistry'; +import { mergingChunks } from '@/tests/dicomOrientationFixtures'; +import { + OTHER_SERIES_UID, + SERIES_UID, + sliceDataset, + type SliceOptions, +} from './sliceFixture'; + +const slice = (options: SliceOptions = {}) => + instanceFor(sliceDataset(options)); + +const sopsOf = (instances: readonly Instance[]) => + instances.map((instance) => + getDatasetTag(instance.dataset, Tags.SOPInstanceUID) + ); + +/** Registers batches in order, keeping each returned state as a store would. */ +const registerAll = (batches: Instance[][], initial = emptyRegistry) => + batches.reduce( + (results, batch) => [ + ...results, + registerInstances(results.at(-1)?.state ?? initial, batch), + ], + [] as ReturnType[] + ); + +const lastUpdates = (batches: Instance[][]) => + registerAll(batches).at(-1)!.updates; + +describe('pure instance registry', () => { + it('orders a series into one collection whose members align with the plan', () => { + const [a, b, c] = [0, 1, 2].map((z) => slice({ sop: `s${z}`, z })); + + const [update] = lastUpdates([[c, a, b]]); + + expect(update.members).toEqual([a, b, c]); + expect(update.provenance).toEqual([a, b, c]); + expect(update.collection.members.map((m) => m.sopInstanceUid)).toEqual( + sopsOf(update.members) + ); + expect(update.id.startsWith(SERIES_UID)).toBe(true); + }); + + it.each([ + ['one batch', [[0, 1, 2]]], + ['a late earlier slice', [[1, 2], [0]]], + ['one at a time', [[2], [0], [1]]], + ])('keeps one id and one ordering when loaded as %s', (_name, zs) => { + const slices = [0, 1, 2].map((z) => slice({ sop: `b${z}`, z })); + const once = lastUpdates([slices]); + + const batched = lastUpdates(zs.map((batch) => batch.map((z) => slices[z]))); + + expect(batched).toHaveLength(1); + expect(batched[0].id).toBe(once[0].id); + expect(batched[0].members).toEqual(slices); + }); + + it('keeps the first registration of a SOP Instance UID and reports the re-supply', () => { + const original = slice({ sop: 'same', z: 0 }); + const resupplied = slice({ sop: 'same', z: 0 }); + + const [first, second] = registerAll([[original], [resupplied]]); + + expect(second.updates[0].id).toBe(first.updates[0].id); + expect(second.updates[0].members).toEqual([original]); + expect(second.updates[0].provenance).toEqual([resupplied]); + expect(isRegistered(second.state, original)).toBe(true); + expect(isRegistered(second.state, resupplied)).toBe(false); + }); + + it('reports a conflicting copy under a registered UID and keeps the first', () => { + const original = slice({ sop: 'same', z: 0 }); + const conflicting = slice({ sop: 'same', z: 1 }); + + const second = registerAll([[original], [conflicting]])[1]; + + expect(second.conflictingInstanceUids).toEqual(['same']); + expect(second.updates[0].members).toEqual([original]); + expect(second.updates[0].provenance).toEqual([original]); + }); + + it('identifies instances without a UID by object', () => { + const first = slice({ sop: null, z: 0 }); + const second = slice({ sop: null, z: 1 }); + + const results = registerAll([[first, second, first], [first]]); + + expect(results[0].updates[0].members).toEqual([first, second]); + expect(results[1].updates[0].members).toEqual([first, second]); + }); + + it('recognizes a NUL padded UID as the registered instance', () => { + const padded = slice({ sop: '1.2.3\0\0' }); + const { state } = registerInstances(emptyRegistry, [padded]); + expect(isRegistered(state, padded)).toBe(true); + }); + + it('reports the id a replan dissolves when two collections merge', () => { + const { between, straight, tilted } = mergingChunks(slice); + + const [first, second] = registerAll([[straight, tilted], [between]]); + + expect(first.updates).toHaveLength(2); + expect(second.updates).toHaveLength(1); + expect(second.updates[0].members).toEqual([straight, tilted, between]); + expect(second.removed).toEqual( + first.updates + .map((update) => update.id) + .filter((id) => id !== second.updates[0].id) + ); + }); + + it('leaves an untouched collection out and reports a relabelled one', () => { + const scout = slice({ sop: 'scout', rows: '8' }); + const acquisition = (number: string, zs: number[]) => + zs.map((z) => + slice({ + sop: `${number}-${z}`, + z, + tags: { [Tags.AcquisitionNumber]: number }, + }) + ); + + const [first, second, third] = registerAll([ + acquisition('1', [0, 2]), + [scout], + acquisition('2', [1, 3]), + ]); + + expect(second.updates.map((update) => sopsOf(update.members))).toEqual([ + ['scout'], + ]); + const relabelled = third.updates.find( + (update) => update.id === first.updates[0].id + )!; + expect(sopsOf(relabelled.members)).toEqual(['1-0', '1-2']); + expect(relabelled.collection.label).toBe('rows 4, acquisition 1'); + expect(third.removed).toEqual([]); + }); + + it('plans series independently', () => { + const first = slice({ sop: 'a', series: SERIES_UID }); + const second = slice({ sop: 'b', series: OTHER_SERIES_UID }); + + const updates = lastUpdates([[first, second]]); + + expect(updates.map((update) => update.members)).toEqual([ + [first], + [second], + ]); + }); + + it('leaves the input state untouched, so discarding a result undoes it', () => { + const kept = slice({ sop: 'a', z: 0 }); + const { state } = registerInstances(emptyRegistry, [kept]); + const discarded = slice({ sop: 'b', z: 1 }); + + registerInstances(state, [discarded]); + const retried = slice({ sop: 'b', z: 1 }); + const { updates } = registerInstances(state, [retried]); + + expect(isRegistered(state, discarded)).toBe(false); + expect(updates[0].members).toEqual([kept, retried]); + }); + + it('forgets a collection so a re-import plans it afresh under the same id', () => { + const scout = slice({ sop: 'scout', rows: '8' }); + const kept = slice({ sop: 'kept' }); + const { state, updates } = registerInstances(emptyRegistry, [scout, kept]); + const scoutId = updates.find((update) => update.members[0] === scout)!.id; + + const forgotten = forgetCollection(state, scoutId); + const resupplied = slice({ sop: 'scout', rows: '8' }); + const again = registerInstances(forgotten, [resupplied]); + + expect(isRegistered(forgotten, scout)).toBe(false); + expect(isRegistered(forgotten, kept)).toBe(true); + expect(again.updates.map((update) => [update.id, update.members])).toEqual([ + [scoutId, [resupplied]], + ]); + expect(again.removed).toEqual([]); + expect(forgetCollection(forgotten, 'unknown')).toBe(forgotten); + }); + + it('drops an emptied series from the state', () => { + const only = slice(); + const { state, updates } = registerInstances(emptyRegistry, [only]); + const forgotten: RegistryState = forgetCollection(state, updates[0].id); + expect(forgotten.size).toBe(0); + }); +}); diff --git a/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts b/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts new file mode 100644 index 000000000..abc58e4d9 --- /dev/null +++ b/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts @@ -0,0 +1,1040 @@ +import { describe, it, expect } from 'vitest'; +import { + HARD_FACT_RULES, + ORIENTATION_RULE, + ORIENTATION_TOLERANCE, + IN_PLANE_SHIFT_WARNING, + NONPARALLEL_SLICES_WARNING, + IRREGULAR_VOLUME_WARNING, + REPEATED_POSITIONS_WARNING, + UNREADABLE_POSITION_WARNING, + planDicomCollections, + validateCollections, +} from '../planDicomCollections'; +import { + SEMANTIC_AXES, + DESCRIPTOR_AXES, +} from '../splitOverlappingAcquisitions'; +import type { DicomCollection, InstanceFacts } from '../planDicomCollections'; +import { + IDENTITY_ORIENTATION, + clone, + makeFacts, + orientationKeyValue, + tiltedOrientation, +} from './instanceFactsFixture'; + +const SERIES_KEY = 'series-1'; + +const plan = (instances: InstanceFacts[], seriesKey = SERIES_KEY) => + planDicomCollections({ seriesKey, instances }); + +const uidsOf = (collection: DicomCollection) => + collection.members.map((m) => m.sopInstanceUid); + +function collectionWith(collections: DicomCollection[], uid: string) { + const found = collections.find((c) => + c.members.some((m) => m.sopInstanceUid === uid) + ); + if (!found) throw new Error(`no collection holds ${uid}`); + return found; +} + +const partValue = (collection: DicomCollection, rule: string) => { + const part = collection.key.parts.find(([name]) => name === rule); + if (!part) throw new Error(`no key part named ${rule}`); + return part[1]; +}; + +const mentions = (diagnostics: string[], needle: string) => + diagnostics.some((d) => d.includes(needle)); + +// Second orientation row rotations, measured against the dot-product tolerance. +const WITHIN = Math.acos(1 - ORIENTATION_TOLERANCE / 2); +const BEYOND = Math.acos(1 - ORIENTATION_TOLERANCE * 2); +// cos(CHAIN) is inside the tolerance while cos(2 * CHAIN) is outside it. +const CHAIN = Math.sqrt(ORIENTATION_TOLERANCE); + +describe('planDicomCollections', () => { + it('plans nothing for an empty instance list', () => { + expect(plan([])).toEqual({ collections: [] }); + }); + + it('keeps one consistent series in a single collection', () => { + const a = makeFacts('uid-a', { projectedPosition: 0, instanceNumber: 1 }); + const b = makeFacts('uid-b', { projectedPosition: 1, instanceNumber: 2 }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(1); + expect(collections[0].key.seriesKey).toBe(SERIES_KEY); + expect(collections[0].members[0]).toBe(a); + expect(collections[0].members[1]).toBe(b); + expect(collections[0].order).toBe('spatial'); + expect(collections[0].diagnostics).toEqual([]); + }); + + it('names the hard facts then orientation, in a fixed key order', () => { + const { collections } = plan([makeFacts('uid-a')]); + + expect(collections[0].key.parts.map(([rule]) => rule)).toEqual([ + ...HARD_FACT_RULES, + ORIENTATION_RULE, + ...SEMANTIC_AXES.map((axis) => axis.rule), + ]); + expect(collections[0].key.parts).toEqual([ + ['rows', '4'], + ['columns', '4'], + ['samplesPerPixel', '1'], + ['numberOfFrames', null], + ['orientation', orientationKeyValue(IDENTITY_ORIENTATION)], + ['acquisition', null], + ['phase', null], + ['echo', null], + ['b-value', null], + ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), + ]); + }); + + const differingFacts: Array<[string, Partial, string]> = [ + ['rows', { rows: '8' }, '8'], + ['columns', { columns: '8' }, '8'], + ['samplesPerPixel', { samplesPerPixel: '3' }, '3'], + ['numberOfFrames', { numberOfFrames: '2' }, '2'], + ]; + + it.each(differingFacts)( + 'partitions on a differing %s', + (rule, overrides, expected) => { + const a = makeFacts('uid-a'); + const b = makeFacts('uid-b', overrides); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(2); + expect(uidsOf(collectionWith(collections, 'uid-a'))).toEqual(['uid-a']); + expect(uidsOf(collectionWith(collections, 'uid-b'))).toEqual(['uid-b']); + expect(partValue(collectionWith(collections, 'uid-b'), rule)).toBe( + expected + ); + } + ); + + const missingFacts: Array< + [string, Partial, Partial] + > = [ + ['rows', { rows: '4' }, { rows: null }], + ['columns', { columns: '4' }, { columns: null }], + ['samplesPerPixel', { samplesPerPixel: '1' }, { samplesPerPixel: null }], + ['numberOfFrames', { numberOfFrames: '2' }, { numberOfFrames: null }], + ]; + + it.each(missingFacts)( + 'buckets a missing %s on its own', + (rule, present, absent) => { + const a = makeFacts('uid-a', present); + const b = makeFacts('uid-b', absent); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(2); + expect(partValue(collectionWith(collections, 'uid-b'), rule)).toBeNull(); + expect( + partValue(collectionWith(collections, 'uid-a'), rule) + ).not.toBeNull(); + } + ); + + it('does not partition on pixel spacing, position or instance number', () => { + const a = makeFacts('uid-a', { + pixelSpacing: [1, 1], + position: [0, 0, 0], + projectedPosition: 0, + instanceNumber: 1, + }); + const b = makeFacts('uid-b', { + pixelSpacing: [0.5, 0.75], + position: [0, 0, 3], + projectedPosition: 3, + instanceNumber: 9, + }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(1); + expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); + }); + + it('keys on the given series key, not the instances own series UID', () => { + const a = makeFacts('uid-a', { seriesInstanceUid: 'somewhere-else' }); + + const { collections } = plan([a], 'series-9'); + + expect(collections[0].key.seriesKey).toBe('series-9'); + }); + + it('buckets orientations whose rows agree within the tolerance', () => { + const a = makeFacts('uid-a', { orientation: IDENTITY_ORIENTATION }); + const b = makeFacts('uid-b', { orientation: tiltedOrientation(WITHIN) }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(1); + expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); + }); + + it('splits orientations whose rows disagree beyond the tolerance', () => { + const a = makeFacts('uid-a', { orientation: IDENTITY_ORIENTATION }); + const b = makeFacts('uid-b', { orientation: tiltedOrientation(BEYOND) }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(2); + expect( + partValue(collectionWith(collections, 'uid-b'), ORIENTATION_RULE) + ).toBe(orientationKeyValue(tiltedOrientation(BEYOND))); + }); + + it('buckets identical cosines that are slightly over normalized', () => { + const overNormalized = [1.0001, 0, 0, 0, 1, 0]; + const a = makeFacts('uid-a', { orientation: overNormalized }); + const b = makeFacts('uid-b', { orientation: overNormalized }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(1); + expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); + expect(partValue(collections[0], ORIENTATION_RULE)).toBe( + orientationKeyValue(overNormalized) + ); + }); + + it('buckets a chain of near orientations the same way under permutation', () => { + const a = makeFacts('uid-a', { orientation: IDENTITY_ORIENTATION }); + const b = makeFacts('uid-b', { orientation: tiltedOrientation(CHAIN) }); + const c = makeFacts('uid-c', { orientation: tiltedOrientation(2 * CHAIN) }); + + const forward = plan([a, b, c]); + const backward = plan([c, b, a]); + const shuffled = plan([b, c, a]); + + expect(forward.collections).toHaveLength(2); + expect(uidsOf(collectionWith(forward.collections, 'uid-a'))).toEqual([ + 'uid-a', + 'uid-b', + ]); + expect(uidsOf(collectionWith(forward.collections, 'uid-c'))).toEqual([ + 'uid-c', + ]); + expect(backward).toEqual(forward); + expect(shuffled).toEqual(forward); + }); + + it('buckets a chain of anonymous near orientations the same under permutation', () => { + const anonymousChain = () => [ + makeFacts(null, { + orientation: IDENTITY_ORIENTATION, + projectedPosition: 0, + }), + makeFacts(null, { + orientation: tiltedOrientation(CHAIN), + projectedPosition: 1, + }), + makeFacts(null, { + orientation: tiltedOrientation(2 * CHAIN), + projectedPosition: 2, + }), + ]; + + const [x, y, z] = anonymousChain(); + const forward = plan([x, y, z]); + + expect(forward.collections.map((c) => c.members.length)).toEqual([2, 1]); + expect(plan([z, y, x])).toEqual(forward); + expect(plan([y, x, z])).toEqual(forward); + }); + + it('takes the orientation key from the smallest SOP UID, not the first input', () => { + const late = makeFacts('uid-z', { orientation: IDENTITY_ORIENTATION }); + const early = makeFacts('uid-a', { + orientation: tiltedOrientation(WITHIN), + }); + + const { collections } = plan([late, early]); + + expect(collections).toHaveLength(1); + expect(partValue(collections[0], ORIENTATION_RULE)).toBe( + orientationKeyValue(tiltedOrientation(WITHIN)) + ); + }); + + it('never represents a bucket with an instance that has no SOP UID', () => { + const anonymous = makeFacts(null, { orientation: IDENTITY_ORIENTATION }); + const identified = makeFacts('uid-z', { + orientation: tiltedOrientation(WITHIN), + }); + + const { collections } = plan([anonymous, identified]); + + expect(collections).toHaveLength(1); + expect(partValue(collections[0], ORIENTATION_RULE)).toBe( + orientationKeyValue(tiltedOrientation(WITHIN)) + ); + }); + + it('buckets an unreadable orientation on its own and diagnoses it', () => { + const a = makeFacts('uid-a'); + const b = makeFacts('uid-b', { orientation: null }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(2); + const orphan = collectionWith(collections, 'uid-b'); + expect(partValue(orphan, ORIENTATION_RULE)).toBeNull(); + expect(mentions(orphan.diagnostics, 'uid-b')).toBe(true); + }); + + it('deduplicates by SOP Instance UID, keeping the last occurrence', () => { + const stale = makeFacts('uid-a', { instanceNumber: 1 }); + const fresh = makeFacts('uid-a', { instanceNumber: 7 }); + + const { collections } = plan([stale, fresh]); + + expect(collections).toHaveLength(1); + expect(collections[0].members).toHaveLength(1); + expect(collections[0].members[0]).toBe(fresh); + expect(mentions(collections[0].diagnostics, 'uid-a')).toBe(true); + }); + + it('never merges instances that have no SOP Instance UID', () => { + const a = makeFacts(null, { projectedPosition: 0, instanceNumber: 1 }); + const b = makeFacts(null, { projectedPosition: 1, instanceNumber: 2 }); + + const { collections } = plan([a, b]); + + expect(collections).toHaveLength(1); + expect(collections[0].members).toHaveLength(2); + }); + + it('keeps both entries when one anonymous instance is listed twice', () => { + const shared = makeFacts(null); + + const { collections } = plan([shared, shared]); + + expect(collections).toHaveLength(1); + expect(collections[0].members).toEqual([shared, shared]); + }); + + it('orders members by projected position ascending', () => { + const high = makeFacts('uid-a', { projectedPosition: 10 }); + const low = makeFacts('uid-b', { projectedPosition: -5 }); + const mid = makeFacts('uid-c', { projectedPosition: 0 }); + + const { collections } = plan([high, low, mid]); + + expect(uidsOf(collections[0])).toEqual(['uid-b', 'uid-c', 'uid-a']); + expect(collections[0].order).toBe('spatial'); + expect(collections[0].diagnostics).toEqual([]); + }); + + // The tied members keep the scanner's own sequence, but position stays the + // primary key: slot i lands at origin + i * spacing along the normal, so an + // order that ran against position would mirror the volume. + it('breaks a repeated projected position on instance number, keeping spatial order', () => { + const later = makeFacts('uid-a', { + projectedPosition: 3, + instanceNumber: 2, + }); + const earlier = makeFacts('uid-b', { + projectedPosition: 3, + instanceNumber: 1, + }); + // Numbered before the tied pair yet positioned after it. + const far = makeFacts('uid-c', { projectedPosition: 5, instanceNumber: 0 }); + const near = makeFacts('uid-d', { + projectedPosition: 0, + instanceNumber: 9, + }); + + const { collections } = plan([later, far, earlier, near]); + + expect(uidsOf(collections[0])).toEqual([ + 'uid-d', + 'uid-b', + 'uid-a', + 'uid-c', + ]); + expect(collections[0].order).toBe('spatial'); + expect(collections[0].warnings).toEqual([REPEATED_POSITIONS_WARNING]); + }); + + it('breaks a repeated position on SOP Instance UID when instance numbers tie', () => { + const second = makeFacts('uid-b', { projectedPosition: 3 }); + const first = makeFacts('uid-a', { projectedPosition: 3 }); + + const { collections } = plan([second, first]); + + expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); + expect(collections[0].order).toBe('spatial'); + }); + + it('orders an unnumbered member after a numbered one at the same position', () => { + const numbered = makeFacts('uid-b', { projectedPosition: 3 }); + const unnumbered = makeFacts('uid-a', { + projectedPosition: 3, + instanceNumber: null, + }); + const low = makeFacts('uid-c', { projectedPosition: 0 }); + + const { collections } = plan([unnumbered, numbered, low]); + + expect(uidsOf(collections[0])).toEqual(['uid-c', 'uid-b', 'uid-a']); + expect(collections[0].order).toBe('spatial'); + }); + + it('breaks a shared position between anonymous members on content', () => { + const anonymousPair = () => [ + makeFacts(null, { projectedPosition: 0, instanceNumber: 1 }), + makeFacts(null, { projectedPosition: 0, instanceNumber: 2 }), + ]; + + const [a, b] = anonymousPair(); + const forward = plan([a, b]); + + expect(forward.collections[0].members.map((m) => m.instanceNumber)).toEqual( + [1, 2] + ); + expect(plan([b, a])).toEqual(forward); + }); + + it('breaks an anonymous tie on facts outside the ordering keys', () => { + const anonymousPair = () => [ + makeFacts(null, { position: [0, 0, 0] }), + makeFacts(null, { position: [9, 9, 9] }), + ]; + + const [a, b] = anonymousPair(); + const forward = plan([a, b]); + + expect(forward.collections[0].members.map((m) => m.position)).toEqual([ + [0, 0, 0], + [9, 9, 9], + ]); + expect(plan([b, a])).toEqual(forward); + }); + + it('keeps an unreadable position out of the collection it cannot be placed in', () => { + const blind = makeFacts('uid-a', { + projectedPosition: null, + instanceNumber: 3, + }); + const alsoBlind = makeFacts('uid-c', { + projectedPosition: null, + instanceNumber: 1, + }); + const seen = makeFacts('uid-b', { + projectedPosition: 2, + instanceNumber: 1, + }); + + const { collections } = plan([blind, seen, alsoBlind]); + + expect(collections).toHaveLength(2); + expect(uidsOf(collectionWith(collections, 'uid-b'))).toEqual(['uid-b']); + + const unknown = collectionWith(collections, 'uid-a'); + expect(uidsOf(unknown)).toEqual(['uid-c', 'uid-a']); + expect(unknown.order).toBe('instance-number'); + expect(mentions(unknown.diagnostics, 'uid-a')).toBe(true); + expect(unknown.warnings).toEqual([UNREADABLE_POSITION_WARNING]); + }); + + it('says nothing about a series that is one positionless instance', () => { + const alone = makeFacts('uid-a', { + projectedPosition: null, + instanceNumber: 1, + }); + + const { collections } = plan([alone]); + + expect(collections).toHaveLength(1); + expect(collections[0].warnings).toEqual([]); + }); + + it('warns about a lone positionless instance beside a volume it missed', () => { + const alone = makeFacts('uid-a', { + projectedPosition: null, + instanceNumber: 1, + }); + const seen = makeFacts('uid-b', { + projectedPosition: 2, + instanceNumber: 2, + }); + + const { collections } = plan([alone, seen]); + + expect(collectionWith(collections, 'uid-a').warnings).toEqual([ + UNREADABLE_POSITION_WARNING, + ]); + }); + + it('breaks a shared instance number on SOP Instance UID', () => { + const second = makeFacts('uid-b', { + projectedPosition: null, + instanceNumber: 4, + }); + const first = makeFacts('uid-a', { + projectedPosition: null, + instanceNumber: 4, + }); + + const { collections } = plan([second, first]); + + expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); + expect(collections[0].order).toBe('instance-number'); + }); + + it('records input order when neither position nor instance number reads', () => { + const second = makeFacts('uid-b', { + projectedPosition: null, + instanceNumber: null, + }); + const first = makeFacts('uid-a', { + projectedPosition: null, + instanceNumber: null, + }); + + const { collections } = plan([second, first]); + + expect(uidsOf(collections[0])).toEqual(['uid-b', 'uid-a']); + expect(collections[0].order).toBe('input'); + expect(mentions(collections[0].diagnostics, 'uid-a')).toBe(true); + expect(mentions(collections[0].diagnostics, 'uid-b')).toBe(true); + }); + + const permutable = () => [ + makeFacts('uid-1', { projectedPosition: 2, instanceNumber: 2 }), + makeFacts('uid-2', { projectedPosition: 1, instanceNumber: 1 }), + makeFacts('uid-3', { + projectedPosition: 0, + instanceNumber: 3, + sliceThickness: '5', + }), + makeFacts('uid-4', { + projectedPosition: 4, + instanceNumber: 4, + sliceThickness: '5', + }), + makeFacts('uid-5', { + projectedPosition: 3, + instanceNumber: 5, + orientation: tiltedOrientation(BEYOND), + }), + makeFacts('uid-6', { + projectedPosition: 5, + instanceNumber: 6, + orientation: tiltedOrientation(BEYOND), + }), + ]; + + it('is invariant to input permutation in membership and order', () => { + const base = plan(permutable()); + const reversed = plan(permutable().reverse()); + const rotated = (() => { + const items = permutable(); + return plan([...items.slice(2), ...items.slice(0, 2)]); + })(); + const interleaved = (() => { + const items = permutable(); + return plan([items[5], items[0], items[3], items[1], items[4], items[2]]); + })(); + + expect(base.collections).toHaveLength(3); + expect(reversed).toEqual(base); + expect(rotated).toEqual(base); + expect(interleaved).toEqual(base); + }); + + it('does not mutate the instances it is given', () => { + const instances = permutable(); + const before = clone(instances); + + plan(instances); + + expect(clone(instances)).toEqual(before); + }); + + it('holds every instance exactly once across the collections', () => { + const instances = permutable(); + + const { collections } = plan(instances); + const members = collections.flatMap((c) => c.members); + + expect(members).toHaveLength(instances.length); + expect(new Set(members).size).toBe(instances.length); + instances.forEach((instance) => expect(members).toContain(instance)); + expect(() => validateCollections(instances, collections)).not.toThrow(); + }); +}); + +describe('planDicomCollections semantic partition', () => { + const pass = (acquisition: string, zs: number[]) => + zs.map((z, i) => + makeFacts(`acq${acquisition}-${i}`, { + projectedPosition: z, + instanceNumber: i + 1, + acquisitionNumber: acquisition, + }) + ); + + it('separates overlapping passes and labels each collection', () => { + const first = pass('1', [0, 2, 4]); + const second = pass('2', [1, 3, 5]); + + const { collections } = plan([...first, ...second]); + + expect(collections).toHaveLength(2); + const [one, two] = collections; + expect(one.label).toBe('acquisition 1'); + expect(partValue(one, 'acquisition')).toBe('1'); + expect(uidsOf(one)).toEqual(['acq1-0', 'acq1-1', 'acq1-2']); + expect(one.order).toBe('spatial'); + expect(two.label).toBe('acquisition 2'); + expect(partValue(two, 'acquisition')).toBe('2'); + expect(collections.every((c) => c.warnings.length === 0)).toBe(true); + }); + + // Two members whose cosines agree within the tolerance are one plane. Each + // member's own normal would place them at two positions a fraction of a + // micron apart, and the repeated slice would go unreported. + it('projects a bucket on one normal rather than on each member of it', () => { + const straight = makeFacts('uid-a', { + position: [0, 0, 10], + projectedPosition: 10, + }); + const tilted = makeFacts('uid-b', { + orientation: tiltedOrientation(WITHIN), + position: [0, 0, 10], + projectedPosition: 10 * Math.cos(WITHIN), + }); + + const { collections } = plan([straight, tilted]); + + expect(collections).toHaveLength(1); + expect(collections[0].warnings).toEqual([REPEATED_POSITIONS_WARNING]); + }); + + it('partitions each orientation bucket on its own', () => { + const stack = [...pass('1', [0, 2]), ...pass('2', [1, 3])]; + const scout = makeFacts('scout', { + orientation: tiltedOrientation(BEYOND), + acquisitionNumber: '1', + }); + + const { collections } = plan([...stack, scout]); + + expect(collections).toHaveLength(3); + expect(collectionWith(collections, 'scout').label).toBeNull(); + expect(collectionWith(collections, 'acq1-0').label).toBe('acquisition 1'); + }); + + it('leaves an unlabelled collection when nothing overlaps', () => { + const { collections } = plan(pass('1', [0, 2, 4])); + + expect(collections[0].label).toBeNull(); + expect(partValue(collections[0], 'acquisition')).toBeNull(); + expect(collections[0].warnings).toEqual([]); + }); + + it('warns that an unevenly spaced collection is not one regular volume', () => { + // Two 4mm runs with a gap between them, as the bilateral sagittal slabs + // of idcSeriesFixtures.ts are. One collection, but no single lattice. + const { collections } = plan(pass('1', [0, 4, 8, 50, 54, 58])); + + expect(collections).toHaveLength(1); + expect(collections[0].warnings).toEqual([IRREGULAR_VOLUME_WARNING]); + }); + + it('leaves an evenly spaced collection unwarned', () => { + const { collections } = plan(pass('1', [0, 4, 8, 12])); + + expect(collections[0].warnings).toEqual([]); + }); + + it('warns that a tilted gantry stack was stacked without correcting its shear', () => { + const theta = Math.PI / 9; + const orientation = tiltedOrientation(theta); + // The table advances along z while the columns lean into it, so each + // slice plane sits sideways of the last on the stack's own normal. + const stack = [0, 3, 6, 9].map((z, i) => + makeFacts(`tilt-${i}`, { + orientation, + position: [0, 0, z], + projectedPosition: z * Math.cos(theta), + instanceNumber: i + 1, + }) + ); + + const { collections } = plan(stack); + + expect(collections).toHaveLength(1); + expect(collections[0].order).toBe('spatial'); + expect(uidsOf(collections[0])).toEqual(stack.map((m) => m.sopInstanceUid)); + expect(collections[0].warnings).toEqual([IN_PLANE_SHIFT_WARNING]); + }); + + // A 358mm field of view, so a lean shows at the far corner of a slice. + const wideStack = (strayUid: string, lean: number) => + [0, 5, 10, 15].map((z, i) => + makeFacts(i === 2 ? strayUid : `wide-${i}`, { + rows: '512', + columns: '512', + pixelSpacing: [0.7, 0.7], + orientation: i === 2 ? tiltedOrientation(lean) : IDENTITY_ORIENTATION, + projectedPosition: z, + instanceNumber: i + 1, + }) + ); + + it.each(['a-walked-first', 'z-walked-last'])( + 'takes the axes most slices declare when the stray one is %s', + (strayUid) => { + const { collections } = plan(wideStack(strayUid, 0.0002)); + + expect(collections).toHaveLength(1); + expect(collections[0].orientation).toEqual(IDENTITY_ORIENTATION); + expect(collections[0].warnings).toEqual([]); + } + ); + + it('warns when a slice leans off the volume axes by more than a tenth of a millimetre', () => { + const { collections } = plan(wideStack('wide-stray', 0.001)); + + expect(collections).toHaveLength(1); + expect(collections[0].orientation).toEqual(IDENTITY_ORIENTATION); + expect(collections[0].warnings).toEqual([NONPARALLEL_SLICES_WARNING]); + }); + + it('does not assume a physical scale when judging an unknown pixel spacing', () => { + const members = wideStack('wide-stray', 0.001).map((member) => ({ + ...member, + pixelSpacing: null, + })); + + expect(plan(members).collections[0].warnings).not.toContain( + NONPARALLEL_SLICES_WARNING + ); + }); + + it('warns about a repeated position no axis separates', () => { + const { collections } = plan(pass('1', [0, 2, 2, 4])); + + expect(collections).toHaveLength(1); + expect(collections[0].warnings).toEqual([REPEATED_POSITIONS_WARNING]); + }); + + // A later import can bring a slice whose geometry cannot be read. Merging it + // back in would undo a separation the positions of the other members + // already earned. + it('keeps two separated acquisitions apart when a positionless member arrives', () => { + const first = pass('1', [0, 2, 4]); + const second = pass('2', [1, 3, 5]); + const before = plan([...first, ...second]); + + const blind = makeFacts('blind', { + projectedPosition: null, + position: null, + instanceNumber: 7, + }); + const after = plan([...first, ...second, blind]); + + expect(before.collections).toHaveLength(2); + expect(after.collections).toHaveLength(3); + + // The two evidence-backed collections survive unchanged, keys included. + before.collections.forEach((collection) => { + const kept = collectionWith( + after.collections, + collection.members[0].sopInstanceUid! + ); + expect(kept.key).toEqual(collection.key); + expect(uidsOf(kept)).toEqual(uidsOf(collection)); + expect(kept.warnings).toEqual([]); + }); + + const unknown = collectionWith(after.collections, 'blind'); + expect(uidsOf(unknown)).toEqual(['blind']); + expect(unknown.warnings).toEqual([UNREADABLE_POSITION_WARNING]); + expect(unknown.key).not.toEqual(before.collections[0].key); + }); + + it('gives the two passes distinct, collision-free keys', () => { + const { collections } = plan([...pass('1', [0, 2]), ...pass('2', [1, 3])]); + + expect(() => + validateCollections( + collections.flatMap((c) => c.members), + collections + ) + ).not.toThrow(); + }); +}); + +describe('validateCollections', () => { + const a = makeFacts('uid-a'); + const b = makeFacts('uid-b'); + + const collectionOf = ( + members: InstanceFacts[], + parts: Array<[string, string | null]> + ): DicomCollection => ({ + key: { seriesKey: SERIES_KEY, parts }, + members, + order: 'input', + reconstruction: { + kind: 'regular', + sliceSpacing: null, + slots: members.map((_, index) => index), + }, + orientation: null, + label: null, + diagnostics: [], + warnings: [], + }); + + const partsOne: Array<[string, string | null]> = [['orientation', 'one']]; + const partsTwo: Array<[string, string | null]> = [['orientation', 'two']]; + + it('accepts a conserving, collision-free plan', () => { + expect(() => + validateCollections( + [a, b], + [collectionOf([a], partsOne), collectionOf([b], partsTwo)] + ) + ).not.toThrow(); + }); + + it('rejects an instance that landed in no collection', () => { + expect(() => + validateCollections([a, b], [collectionOf([a], partsOne)]) + ).toThrow('uid-b'); + }); + + it('rejects an instance that landed in two collections', () => { + expect(() => + validateCollections( + [a], + [collectionOf([a], partsOne), collectionOf([a], partsTwo)] + ) + ).toThrow('uid-a'); + }); + + it('accepts an instance listed twice when it is placed twice', () => { + expect(() => + validateCollections([a, a], [collectionOf([a, a], partsOne)]) + ).not.toThrow(); + }); + + it('rejects an instance listed twice but placed once', () => { + expect(() => + validateCollections([a, a], [collectionOf([a], partsOne)]) + ).toThrow('uid-a'); + }); + + it('rejects a member that was never one of the instances', () => { + expect(() => + validateCollections([a], [collectionOf([a, b], partsOne)]) + ).toThrow('uid-b'); + }); + + it('rejects two collections sharing a key', () => { + expect(() => + validateCollections( + [a, b], + [collectionOf([a], partsOne), collectionOf([b], partsOne)] + ) + ).toThrow(/key/i); + }); +}); + +describe('independent multi-frame instances', () => { + it('keeps anonymous clip keys stable when an earlier clip is removed', () => { + const clips = [0, 1, 2].map(() => makeFacts(null, { numberOfFrames: '3' })); + const before = plan(clips.slice(0, 2)).collections; + const after = plan(clips.slice(1)).collections; + const keyOf = (collections: DicomCollection[], member: InstanceFacts) => + collections.find((collection) => collection.members.includes(member))! + .key; + + expect(keyOf(after, clips[1])).toEqual(keyOf(before, clips[1])); + expect(keyOf(after, clips[2])).not.toEqual(keyOf(before, clips[0])); + }); + + it.each([null, 0])( + 'keeps equal-shaped clips separate at position %s', + (position) => { + const instances = ['clip-a', 'clip-b'].map((uid) => + makeFacts(uid, { + numberOfFrames: '3', + position: position === null ? null : [0, 0, position], + projectedPosition: position, + }) + ); + const collections = plan(instances).collections; + expect(collections.map((c) => uidsOf(c))).toEqual([ + ['clip-a'], + ['clip-b'], + ]); + expect(new Set(collections.map((c) => JSON.stringify(c.key))).size).toBe( + 2 + ); + expect(plan([...instances].reverse())).toEqual(plan(instances)); + } + ); +}); + +describe('acquisition descriptors', () => { + const descriptors: Array<[keyof InstanceFacts, string]> = [ + ['seriesNumber', '2'], + ['sequenceName', '*ep_b1000t'], + ['sliceThickness', '2'], + ['seriesDate', '20240202'], + ]; + + const run = (uid: string, zs: number[], facts: Partial) => + zs.map((z) => makeFacts(`${uid}-${z}`, { projectedPosition: z, ...facts })); + + it.each(descriptors)( + 'keeps independent single-plane images apart when %s differs', + (fact, value) => { + const { collections } = plan([ + makeFacts('first', { [fact]: '1' }), + makeFacts('second', { [fact]: value }), + ]); + + expect(collections).toHaveLength(2); + expect( + collections.map((collection) => collection.members.length) + ).toEqual([1, 1]); + expect( + collections.every( + (collection) => collection.reconstruction.kind === 'regular' + ) + ).toBe(true); + expect( + new Set(collections.map((collection) => collection.label)).size + ).toBe(2); + } + ); + + it('keeps an unknown sequence separate from a named sequence on one plane', () => { + const { collections } = plan([ + makeFacts('unknown', { sequenceName: null }), + makeFacts('known', { sequenceName: '*ep_b0' }), + ]); + + expect(collections.map((collection) => collection.label).sort()).toEqual([ + 'sequence *ep_b0', + 'sequence unknown', + ]); + }); + + it.each(descriptors)( + 'keeps a stack whole across one differing %s', + (fact, value) => { + const slices = run('slice', [0, 1, 2, 3, 4], {}); + slices[2] = { ...slices[2], [fact]: value }; + const { collections } = plan(slices); + + expect(collections).toHaveLength(1); + expect(collections[0].reconstruction).toEqual({ + kind: 'regular', + sliceSpacing: 1, + slots: [0, 1, 2, 3, 4], + }); + } + ); + + it.each(descriptors)( + 'keeps adjoining stacks together across %s', + (fact, value) => { + const { collections } = plan([ + ...run('first', [0, 1, 2], { [fact]: '1' }), + ...run('second', [3, 4, 5], { [fact]: value }), + ]); + + expect(collections).toHaveLength(1); + expect(collections[0].reconstruction.kind).toBe('regular'); + } + ); + + it.each(descriptors)( + 'separates and labels overlapping stacks by %s', + (fact, value) => { + const { collections } = plan([ + ...run('first', [0, 2, 4], { [fact]: '1' }), + ...run('second', [1, 3, 5], { [fact]: value }), + ]); + + expect(collections).toHaveLength(2); + expect(collections.every((collection) => collection.label !== null)).toBe( + true + ); + expect( + new Set(collections.map((collection) => collection.label)).size + ).toBe(2); + } + ); + + it('labels DWI stacks by b-value when sequence names also differ', () => { + const { collections } = plan([ + ...run('b0', [0, 1, 2], { sequenceName: '*ep_b0', diffusionBValue: '0' }), + ...run('b1000', [0, 1, 2], { + sequenceName: '*ep_b1000t', + diffusionBValue: '1000', + }), + ]); + + expect(collections.map((collection) => collection.label)).toEqual([ + 'b-value 0', + 'b-value 1000', + ]); + }); + + it('keeps anonymous single-plane ordering stable across descriptor differences', () => { + const members = ['second', 'first'].map((sequenceName) => + makeFacts(null, { sequenceName }) + ); + + expect(plan(members)).toEqual(plan([...members].reverse())); + }); + + it('labels incompatible pixel shapes', () => { + const { collections } = plan([ + makeFacts('small', { rows: '4' }), + makeFacts('large', { rows: '8' }), + ]); + + expect(collections.map((collection) => collection.label)).toEqual([ + 'rows 4', + 'rows 8', + ]); + }); + + it('keeps incompatible acquisition descriptors apart when geometry is unreadable', () => { + const { collections } = plan( + ['first', 'second'].map((sequenceName) => + makeFacts(sequenceName, { + sequenceName, + orientation: null, + position: null, + }) + ) + ); + + expect(collections).toHaveLength(2); + expect( + new Set(collections.map((collection) => collection.label)).size + ).toBe(2); + }); +}); diff --git a/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts b/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts new file mode 100644 index 000000000..6142deebb --- /dev/null +++ b/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts @@ -0,0 +1,252 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, expect, it } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import { readInstanceFacts as readStructuredFacts } from '../instanceFacts'; +import { reconstructVolume } from '../reconstructVolume'; +import { + bilateralSagittalSlabs, + type IdcSeriesFixture, +} from './idcSeriesFixtures'; + +// An axial slice at z, read through the fact reader so the fixtures stay in +// the tag vocabulary the real data uses. +const slice = (z: number, tags: Record = {}) => + readInstanceFacts([ + ...Object.entries({ + [Tags.ImageOrientationPatient]: '1\\0\\0\\0\\1\\0', + [Tags.ImagePositionPatient]: `0\\0\\${z}`, + [Tags.PixelSpacing]: '0.5\\0.5', + ...tags, + }), + ]); + +const stack = (zs: number[]) => zs.map((z) => slice(z)); + +// A gantry tilted by theta leans the columns into z, so each slice plane sits +// sideways of the last as the table advances along z. +const tiltedSlice = (z: number, theta: number) => + slice(z, { + [Tags.ImageOrientationPatient]: [ + 1, + 0, + 0, + 0, + Math.cos(theta), + Math.sin(theta), + ].join('\\'), + }); + +const fixtureSlices = (fixture: IdcSeriesFixture) => + fixture + .groups!.flatMap((group) => group.zs.map((z) => slice(z))) + .sort( + (left, right) => + (left.projectedPosition as number) - (right.projectedPosition as number) + ); + +describe('reconstructVolume', () => { + it('measures an evenly spaced stack and maps every member to its slot', () => { + const result = reconstructVolume(stack([-10, -6, -2, 2, 6])); + + expect(result.kind).toBe('regular'); + expect(result.sliceSpacing).toBeCloseTo(4, 12); + expect(result.slots).toEqual([0, 1, 2, 3, 4]); + }); + + it('derives the spacing from the endpoints once every gap matches', () => { + const result = reconstructVolume(stack([0, 9, 18])); + + expect(result.kind).toBe('regular'); + expect(result.sliceSpacing).toBe(9); + }); + + it('has no spacing to derive from a single member', () => { + const result = reconstructVolume(stack([7])); + + expect(result.kind).toBe('regular'); + expect(result.sliceSpacing).toBeNull(); + expect(result.slots).toEqual([0]); + }); + + it('accepts a single plane without patient position or orientation', () => { + expect( + reconstructVolume([ + { + orientation: null, + position: null, + pixelSpacing: null, + }, + ]) + ).toEqual({ kind: 'regular', sliceSpacing: null, slots: [0] }); + }); + + it('does not treat a positionless multi-frame instance as a single plane', () => { + expect( + reconstructVolume([ + { + orientation: null, + position: null, + pixelSpacing: null, + numberOfFrames: '3', + }, + ]) + ).toMatchObject({ kind: 'irregular', reason: 'unreadable-geometry' }); + }); + + // IDC series 1.3.6.1.4.1.14519.5.2.1.7009.2403.337074050757748643824459343650 + // ("WB_3D_NON-AC"): whole-body PET stepping by 3.27mm with the occasional + // 3.35mm step from printing precision. One lattice, printed unevenly. + it('accepts the printing jitter of quantized whole-body PET positions', () => { + const result = reconstructVolume(stack([0, 3.27, 6.54, 9.89, 13.16])); + + expect(result.kind).toBe('regular'); + expect(result.sliceSpacing).toBeCloseTo(3.29, 2); + }); + + // The two slabs are 4mm stacks 42.439mm apart. Endpoint distance over slice + // count would call that a 4.59mm lattice, which describes neither slab. + it('calls the bilateral sagittal slabs an irregular stack', () => { + const members = fixtureSlices(bilateralSagittalSlabs); + + const result = reconstructVolume(members); + + expect(members).toHaveLength(66); + expect(result.kind).toBe('irregular'); + expect(result).toMatchObject({ reason: 'uneven-slice-spacing' }); + // The fallback places the slices at a gap the series actually holds. + expect(result.sliceSpacing).toBeCloseTo(4, 12); + expect(result.sliceSpacing).not.toBeCloseTo(4.59137, 4); + }); + + it('reports a hole in an otherwise even stack as irregular', () => { + const result = reconstructVolume(stack([0, 4, 8, 20, 24])); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'uneven-slice-spacing', + }); + }); + + it('reports a repeated slice position as irregular', () => { + const result = reconstructVolume(stack([0, 4, 4, 8])); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'repeated-position', + }); + }); + + it('reports a member whose position cannot be read as irregular', () => { + const blind = readInstanceFacts([ + [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], + [Tags.PixelSpacing, '0.5\\0.5'], + ]); + + const result = reconstructVolume([...stack([0, 4]), blind]); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'unreadable-geometry', + }); + expect(result.sliceSpacing).toBeNull(); + }); + + it('reports a slice shifted within its own plane as irregular', () => { + const shifted = readInstanceFacts([ + [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], + [Tags.ImagePositionPatient, '0\\30\\8'], + [Tags.PixelSpacing, '0.5\\0.5'], + ]); + + const result = reconstructVolume([...stack([0, 4]), shifted]); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'in-plane-shift', + }); + // The fallback is a step the members do take, not the one to the outlier. + expect(result.sliceSpacing).toBeCloseTo(4, 12); + }); + + it('steps a tilted gantry stack by the distance its slices advance', () => { + const theta = Math.PI / 9; + + const result = reconstructVolume( + [0, 3, 6, 9].map((z) => tiltedSlice(z, theta)) + ); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'in-plane-shift', + }); + // The table stepped 3mm a slice, which is the extent ITK's series reader + // keeps too; the shear is warned about, not folded into the spacing. + expect(result.sliceSpacing).toBeCloseTo(3, 12); + expect(result.slots).toEqual([0, 1, 2, 3]); + }); + + it('reports two in-plane sample spacings as irregular', () => { + const coarse = slice(8, { [Tags.PixelSpacing]: '0.6\\0.6' }); + + const result = reconstructVolume([...stack([0, 4]), coarse]); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'mixed-pixel-spacing', + }); + expect(result.sliceSpacing).toBeCloseTo(4, 12); + }); + + it('steps a stack whose orientation cannot be read by its positions', () => { + const blind = (z: number) => + readInstanceFacts([ + [Tags.ImagePositionPatient, `0\\0\\${z}`], + [Tags.PixelSpacing, '0.5\\0.5'], + ]); + + const result = reconstructVolume([0, 4, 8].map(blind)); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'unreadable-geometry', + }); + expect(result.sliceSpacing).toBeCloseTo(4, 12); + }); + + it('has no step for members that never move', () => { + const result = reconstructVolume(stack([5, 5, 5])); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'repeated-position', + }); + expect(result.sliceSpacing).toBeNull(); + }); + + it('projects on the normal it is given rather than on the first member', () => { + const members = stack([0, 4, 8]); + + // On the members' own normal the stack is even; on +x it steps sideways. + expect(reconstructVolume(members).kind).toBe('regular'); + expect(reconstructVolume(members, [1, 0, 0])).toMatchObject({ + kind: 'irregular', + reason: 'in-plane-shift', + }); + }); +}); + +function readInstanceFacts(tags: Iterable) { + return readStructuredFacts(datasetFromTags(tags)); +} + +it.each([0.01, 0.05, 0.1])( + 'detects a missing slice in a %s mm stack', + (step) => { + expect( + reconstructVolume(stack([0, 1, 2, 4, 5, 6].map((i) => i * step))) + ).toMatchObject({ + kind: 'irregular', + reason: 'uneven-slice-spacing', + }); + } +); diff --git a/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts b/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts new file mode 100644 index 000000000..c1fd05c81 --- /dev/null +++ b/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts @@ -0,0 +1,456 @@ +import { describe, expect, it } from 'vitest'; +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { Tags } from '../../metadata/dicomTags'; +import type { Instance } from '../../instance/readInstance'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { + emptyRegistry, + forgetCollection, + isRegistered, + registerInstances, + type InstanceCollectionUpdate, +} from '../instanceRegistry'; +import { UNREADABLE_POSITION_WARNING } from '../planDicomCollections'; +import { mergingChunks, tilt } from '@/tests/dicomOrientationFixtures'; +import { SERIES_UID, sliceDataset, type SliceOptions } from './sliceFixture'; + +const sliceInstance = (options: SliceOptions = {}) => + instanceFor(sliceDataset(options)); + +const sops = (instances: readonly Instance[]) => + instances.map((instance) => + getDatasetTag(instance.dataset, Tags.SOPInstanceUID) + ); + +const byId = (updates: InstanceCollectionUpdate[]) => + [...updates].sort((left, right) => (left.id < right.id ? -1 : 1)); + +/** Keeps each returned state, as the store that owns the registry does. */ +function createRegistry() { + let state = emptyRegistry; + return { + register: (batch: Instance[]) => { + const result = registerInstances(state, batch); + state = result.state; + return result; + }, + forget: (id: string) => { + state = forgetCollection(state, id); + }, + has: (instance: Instance) => isRegistered(state, instance), + }; +} + +const collidingMultiframes = (series = SERIES_UID) => + ['1', null].map((sop) => + sliceInstance({ sop, series, tags: { [Tags.NumberOfFrames]: '2' } }) + ); + +describe('instance registry across imports', () => { + it('keeps anonymous clip ownership stable after deletion and another import', () => { + const registry = createRegistry(); + const clips = [0, 1, 2].map(() => + sliceInstance({ + sop: null, + tags: { [Tags.NumberOfFrames]: '3' }, + }) + ); + const before = registry.register(clips.slice(0, 2)).updates; + const first = before.find((update) => update.members.includes(clips[0]))!; + const second = before.find((update) => update.members.includes(clips[1]))!; + expect(first.members).toEqual([clips[0]]); + registry.forget(first.id); + + const after = registry.register([clips[2]]); + + expect(after.removed).not.toContain(second.id); + const updated = after.updates.find((update) => update.id === second.id); + if (updated) expect(updated.members[0]).toBe(clips[1]); + expect(registry.has(clips[1])).toBe(true); + expect(registry.has(clips[0])).toBe(false); + }); + + it('does not confuse a numeric UID with an anonymous clip identity', () => { + const registry = createRegistry(); + const clips = collidingMultiframes(); + const { updates } = registry.register(clips); + + expect(updates).toHaveLength(2); + expect(new Set(updates.map((update) => update.id)).size).toBe(2); + expect(new Set(updates.flatMap((update) => update.members))).toEqual( + new Set(clips) + ); + clips.forEach((clip) => expect(registry.has(clip)).toBe(true)); + }); + + it('plans one consistent series into one ordered collection', () => { + const registry = createRegistry(); + const first = sliceInstance({ sop: 'a', z: 0 }); + const second = sliceInstance({ sop: 'b', z: 1 }); + const third = sliceInstance({ sop: 'c', z: 2 }); + + // Arrival order deliberately differs from slice order. + const { updates } = registry.register([third, first, second]); + + expect(updates).toHaveLength(1); + const [update] = updates; + expect(sops(update.members)).toEqual(['a', 'b', 'c']); + expect(update.provenance).toEqual(update.members); + expect(update.collection.order).toBe('spatial'); + expect(update.collection.diagnostics).toEqual([]); + }); + + it('aligns the chunk members with the planned facts', () => { + const registry = createRegistry(); + const chunks = [ + sliceInstance({ sop: 'a', z: 2 }), + sliceInstance({ sop: 'b', z: 0 }), + ]; + + const { updates } = registry.register(chunks); + const [update] = updates; + + expect(update.collection.members.map((m) => m.sopInstanceUid)).toEqual( + sops(update.members) + ); + }); + + // The DICOMweb store reconciles its own series keyed progress against the + // loaded volume id by prefix. + it('mints an id that starts with the series instance uid', () => { + const registry = createRegistry(); + + const { updates } = registry.register([sliceInstance({ sop: 'a' })]); + + expect(updates[0].id.startsWith(SERIES_UID)).toBe(true); + }); + + it('keeps the collection id and grows its members across two batches', () => { + const registry = createRegistry(); + const first = sliceInstance({ sop: 'a', z: 0 }); + const second = sliceInstance({ sop: 'b', z: 1 }); + + const [firstUpdate] = registry.register([first]).updates; + const [secondUpdate] = registry.register([second]).updates; + + expect(secondUpdate.id).toBe(firstUpdate.id); + expect(sops(secondUpdate.members)).toEqual(['a', 'b']); + // Every member reports its provenance, not just the one the batch brought. + expect(secondUpdate.provenance).toEqual([first, second]); + }); + + it('orders a late arriving earlier slice into its planned position', () => { + const registry = createRegistry(); + const first = sliceInstance({ sop: 'a', z: 0 }); + const second = sliceInstance({ sop: 'b', z: 1 }); + + registry.register([second]); + const [update] = registry.register([first]).updates; + + expect(sops(update.members)).toEqual(['a', 'b']); + expect(update.provenance).toEqual([first, second]); + }); + + const POSITIONS: Record = { a: 0, b: 1, c: 2 }; + + const loadBatches = (batches: ReadonlyArray>) => { + const registry = createRegistry(); + return batches.reduce( + (_, batch) => + registry.register( + batch.map((sop) => sliceInstance({ sop, z: POSITIONS[sop] })) + ).updates, + [] as InstanceCollectionUpdate[] + ); + }; + + it.each([ + ['one batch', [['a', 'b', 'c']]], + ['two batches', [['a'], ['b', 'c']]], + ['two batches in reverse', [['b', 'c'], ['a']]], + ['one slice at a time', [['c'], ['a'], ['b']]], + [ + 'a repeated batch', + [ + ['a', 'b', 'c'], + ['a', 'b', 'c'], + ], + ], + ] as const)( + 'plans the whole series into one collection when loaded as %s', + (_case, batches) => { + const updates = loadBatches(batches); + + expect(updates).toHaveLength(1); + expect(sops(updates[0].members)).toEqual(['a', 'b', 'c']); + } + ); + + it('gives one series the same id however the slices are batched', () => { + const idOf = (batches: ReadonlyArray>) => + loadBatches(batches)[0].id; + + const oneBatch = idOf([['a', 'b', 'c']]); + expect(idOf([['a'], ['b', 'c']])).toBe(oneBatch); + expect(idOf([['b', 'c'], ['a']])).toBe(oneBatch); + expect( + idOf([ + ['a', 'b', 'c'], + ['a', 'b', 'c'], + ]) + ).toBe(oneBatch); + }); + + it.each([ + { sop: ' a ', series: ` ${SERIES_UID} ` }, + { sop: null, series: SERIES_UID }, + { sop: null, series: null }, + { sop: '', series: SERIES_UID }, + { sop: ' ', series: '' }, + { sop: 'a', series: ' ' }, + ])('recognizes only the canonical member for identity %j', (identity) => { + const registry = createRegistry(); + const original = sliceInstance(identity); + const duplicate = sliceInstance(identity); + + const { updates } = registry.register([original]); + + expect(registry.has(original)).toBe(true); + expect(registry.has(duplicate)).toBe(false); + registry.forget(updates[0].id); + expect(registry.has(original)).toBe(false); + }); + + it('counts one chunk once however often a batch repeats it', () => { + const registry = createRegistry(); + const chunk = sliceInstance({ sop: 'a', z: 0 }); + + const [update] = registry.register([chunk, chunk]).updates; + + expect(update.members).toEqual([chunk]); + }); + + it('re-registers an anonymous chunk without duplicating it', () => { + const registry = createRegistry(); + const chunk = sliceInstance({ sop: null, z: 0 }); + + registry.register([chunk]); + const [update] = registry.register([chunk]).updates; + + expect(update.members).toEqual([chunk]); + }); + + it('splits one batch of incompatible instances into two collections', () => { + const registry = createRegistry(); + const scout = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); + const slices = [ + sliceInstance({ sop: 'a', z: 0 }), + sliceInstance({ sop: 'b', z: 1 }), + ]; + + const { updates } = registry.register([scout, ...slices]); + + expect(updates).toHaveLength(2); + const membership = updates.map((update) => sops(update.members)); + expect(membership).toContainEqual(['scout']); + expect(membership).toContainEqual(['a', 'b']); + expect(updates[0].id).not.toBe(updates[1].id); + updates.forEach((update) => + expect(update.id.startsWith(SERIES_UID)).toBe(true) + ); + }); + + it('leaves an untouched collection out of a later batch', () => { + const registry = createRegistry(); + const scout = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); + const slice = sliceInstance({ sop: 'a', z: 0 }); + + const [sliceUpdate] = registry.register([slice]).updates; + const { updates } = registry.register([scout]); + + expect(updates).toHaveLength(1); + expect(sops(updates[0].members)).toEqual(['scout']); + expect(updates[0].id).not.toBe(sliceUpdate.id); + }); + + // The positions of the two passes already earned their separation; a later + // slice nothing spatial can be said about must not dissolve it. + it('keeps two separated acquisitions when a positionless chunk arrives later', () => { + const registry = createRegistry(); + const first = [0, 2, 4].map((z) => + sliceInstance({ + sop: `one-${z}`, + z, + tags: { [Tags.AcquisitionNumber]: '1' }, + }) + ); + const second = [1, 3, 5].map((z) => + sliceInstance({ + sop: `two-${z}`, + z, + tags: { [Tags.AcquisitionNumber]: '2' }, + }) + ); + + const separated = byId(registry.register([...first, ...second]).updates); + expect(separated).toHaveLength(2); + + const blind = sliceInstance({ sop: 'blind', z: null, instanceNumber: 9 }); + const { updates, removed } = registry.register([blind]); + + // Neither committed collection dissolved, and neither was re-planned. + expect(removed).toEqual([]); + expect(updates).toHaveLength(1); + expect(updates[0].id).not.toBe(separated[0].id); + expect(updates[0].id).not.toBe(separated[1].id); + expect(sops(updates[0].members)).toEqual(['blind']); + expect(updates[0].collection.warnings).toEqual([ + UNREADABLE_POSITION_WARNING, + ]); + + // The two volumes still hold exactly the slices of their own pass. + const again = byId(registry.register([...first, ...second]).updates); + expect(again.map((update) => update.id)).toEqual( + separated.map((update) => update.id) + ); + expect(again.map((update) => sops(update.members))).toEqual([ + sops(separated[0].members), + sops(separated[1].members), + ]); + expect(again.flatMap((update) => update.collection.warnings)).toEqual([]); + }); + + it('reports a collection a later batch re-registers unchanged', () => { + const registry = createRegistry(); + const slice = sliceInstance({ sop: 'a', z: 0 }); + + registry.register([slice]); + const { updates } = registry.register([slice]); + + expect(updates).toHaveLength(1); + expect(updates[0].provenance).toEqual([slice]); + }); + + const merging = () => mergingChunks(sliceInstance); + + it('reports a collection that lost members without gaining a chunk', () => { + const registry = createRegistry(); + const straight = sliceInstance({ + sop: 'sop-2', + z: 0, + orientation: tilt(0), + }); + const near = sliceInstance({ sop: 'sop-3', z: 1, orientation: tilt(0.01) }); + // Agrees with the straight instance but not with the near one, so the + // bucket it seeds as the new reference leaves the near one behind. + const splitter = sliceInstance({ + sop: 'sop-1', + z: 2, + orientation: tilt(-0.005), + }); + + const first = registry.register([straight, near]); + expect(first.updates).toHaveLength(1); + + const second = registry.register([splitter]); + + const orphaned = second.updates.find( + (update) => !update.members.includes(splitter) + ); + expect(orphaned).toBeDefined(); + expect(sops(orphaned!.members)).toEqual(['sop-3']); + expect(second.removed).toEqual([first.updates[0].id]); + }); + + it('replans without the instances a forgotten collection held', () => { + const registry = createRegistry(); + const original = sliceInstance({ sop: 'a', z: 0 }); + const { updates } = registry.register([original]); + + registry.forget(updates[0].id); + const resupplied = sliceInstance({ sop: 'a', z: 0 }); + const second = registry.register([resupplied]); + + // Identity, not shape: the released chunk is an equal but stale object. + expect(second.updates[0].members).toHaveLength(1); + expect(second.updates[0].members[0]).toBe(resupplied); + expect(second.updates[0].id).toBe(updates[0].id); + }); + + it('keeps the members a replan moved when the dissolved id is forgotten', () => { + const registry = createRegistry(); + const { between, straight, tilted } = merging(); + + registry.register([straight, tilted]); + const merged = registry.register([between]); + merged.removed.forEach((id) => registry.forget(id)); + + const third = registry.register([between]); + + expect(third.updates[0].members).toHaveLength(3); + }); + + it('forgets one collection of a series without touching the others', () => { + const registry = createRegistry(); + const scout = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); + const slice = sliceInstance({ sop: 'a', z: 0 }); + + const { updates } = registry.register([scout, slice]); + const scoutUpdate = updates.find((update) => update.members[0] === scout)!; + registry.forget(scoutUpdate.id); + + const resupplied = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); + const second = registry.register([resupplied]); + + expect(second.updates).toHaveLength(1); + expect(second.updates[0].members).toHaveLength(1); + expect(second.updates[0].members[0]).toBe(resupplied); + expect(second.removed).toEqual([]); + }); + + it('surfaces the planner order and diagnostics for a positionless series', () => { + const registry = createRegistry(); + const chunks = [ + sliceInstance({ sop: 'alpha', z: null, instanceNumber: 2 }), + sliceInstance({ sop: 'beta', z: null, instanceNumber: 1 }), + ]; + + const [update] = registry.register(chunks).updates; + + expect(sops(update.members)).toEqual(['beta', 'alpha']); + expect(update.collection.order).toBe('instance-number'); + const diagnostics = update.collection.diagnostics.join(' '); + expect(diagnostics).toContain('alpha'); + expect(diagnostics).toContain('beta'); + }); + + it('does not mutate the batch it registers', () => { + const registry = createRegistry(); + const chunks = [ + sliceInstance({ sop: 'a', z: 2 }), + sliceInstance({ sop: 'b', z: 0 }), + ]; + const order = [...chunks]; + + registry.register(chunks); + + expect(chunks).toEqual(order); + }); +}); + +describe('registry normalization and conflicting identities', () => { + it('keeps slices with absent and explicit single-frame counts in one volume', () => { + const registry = createRegistry(); + const result = registry.register([ + sliceInstance({ sop: 'first', z: 0 }), + sliceInstance({ + sop: 'second', + z: 1, + tags: { [Tags.NumberOfFrames]: '1' }, + }), + ]); + expect(result.updates).toHaveLength(1); + expect(result.updates[0].members).toHaveLength(2); + expect(result.updates[0].collection.reconstruction.sliceSpacing).toBe(1); + }); +}); diff --git a/packages/dicom/core/collections/__tests__/sliceFixture.ts b/packages/dicom/core/collections/__tests__/sliceFixture.ts new file mode 100644 index 000000000..d2c8bdcbd --- /dev/null +++ b/packages/dicom/core/collections/__tests__/sliceFixture.ts @@ -0,0 +1,52 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { Tags } from '../../metadata/dicomTags'; + +export const SERIES_UID = '1.2.826.0.1.3680043.9.7'; +export const OTHER_SERIES_UID = '1.2.826.0.1.3680043.9.8'; + +export type SliceOptions = { + sop?: string | null; + series?: string | null; + z?: number | null; + rows?: string; + orientation?: string; + instanceNumber?: number | null; + modality?: string; + // Extra tags, keyed 'gggg|eeee'. + tags?: Record; +}; + +let sopCounter = 0; + +/** A planner-ready MR slice header; every call mints a fresh SOP UID by default. */ +export function sliceDataset(options: SliceOptions = {}) { + const { + sop = `sop-${(sopCounter += 1)}`, + series = SERIES_UID, + z = 0, + rows = '4', + orientation = '1\\0\\0\\0\\1\\0', + instanceNumber = 1, + modality = 'MR', + tags = {}, + } = options; + + const entries: Array<[string, string]> = [ + [Tags.StudyInstanceUID, '1.2.826.0.1.3680043.9.1'], + [Tags.PatientID, 'patient-1'], + [Tags.SeriesNumber, '1'], + [Tags.Modality, modality], + [Tags.Rows, rows], + [Tags.Columns, '4'], + [Tags.SamplesPerPixel, '1'], + [Tags.ImageOrientationPatient, orientation], + ]; + if (series !== null) entries.push([Tags.SeriesInstanceUID, series]); + if (sop !== null) entries.push([Tags.SOPInstanceUID, sop]); + if (z !== null) entries.push([Tags.ImagePositionPatient, `0\\0\\${z}`]); + if (instanceNumber !== null) + entries.push(['0020|0013', String(instanceNumber)]); + entries.push(...Object.entries(tags)); + + return datasetFromTags(entries); +} diff --git a/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts b/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts new file mode 100644 index 000000000..440e2c8fb --- /dev/null +++ b/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts @@ -0,0 +1,635 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, it, expect } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import { readInstanceFacts as readStructuredFacts } from '../instanceFacts'; +import type { InstanceFacts } from '../planDicomCollections'; +import { + GEOMETRY_RULE, + DESCRIPTOR_AXES, + SEMANTIC_AXES, + UNREADABLE_GEOMETRY, + UNREADABLE_GEOMETRY_LABEL, + splitOverlappingAcquisitions, + type SemanticPart, +} from '../splitOverlappingAcquisitions'; +import { makeFacts } from './instanceFactsFixture'; +import { + bilateralSagittalSlabs, + dceEightPhase, + dceSevenPhasePhilips, + dixonDualEcho, + dixonUnevenEchoes, + doubledAcquisition, + dwiMultiBValue, + partialTemporalTags, + type IdcSeriesFixture, +} from './idcSeriesFixtures'; + +let nextUid = 0; + +// An axial slice at z carrying the given tags, read through the fact reader so +// the fixtures stay in the tag vocabulary the real data uses. +function slice(z: number, tags: Record = {}) { + nextUid += 1; + return readInstanceFacts([ + [Tags.SOPInstanceUID, `1.2.3.${nextUid}`], + [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], + [Tags.ImagePositionPatient, `0\\0\\${z}`], + ...Object.entries(tags), + ]); +} + +// A stack of `count` slices starting at `start`, tagged with an acquisition. +const stack = (acquisition: string, start: number, count: number, step = 2.5) => + Array.from({ length: count }, (_, i) => + slice(start + i * step, { [Tags.AcquisitionNumber]: acquisition }) + ); + +const zOf = (facts: InstanceFacts) => facts.projectedPosition as number; +const byPosition = (a: InstanceFacts, b: InstanceFacts) => zOf(a) - zOf(b); + +// Slices mirroring a real IDC series recorded in idcSeriesFixtures.ts. +const fixtureSlices = (fixture: IdcSeriesFixture) => + fixture + .groups!.flatMap((group) => group.zs.map((z) => slice(z, group.tags))) + .sort(byPosition); + +const labels = (parts: SemanticPart[]) => + parts.map((part) => part.label).sort(); + +const partLabelled = (parts: SemanticPart[], label: string | null) => { + const found = parts.find((part) => part.label === label); + if (!found) throw new Error(`no part labelled ${label}`); + return found; +}; + +const partValue = (part: SemanticPart, rule: string) => { + const entry = part.parts.find(([name]) => name === rule); + if (!entry) throw new Error(`no part named ${rule}`); + return entry[1]; +}; + +const unsplitParts = SEMANTIC_AXES.map((axis) => [axis.rule, null]); + +describe('splitOverlappingAcquisitions', () => { + it('passes a single acquisition through as one unlabelled part', () => { + const members = stack('1', 0, 5); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toEqual([ + { + parts: unsplitParts, + members, + label: null, + repeatedPositions: false, + unreadablePositions: false, + }, + ]); + }); + + it('names one key part per axis, in axis order, split or not', () => { + const parts = splitOverlappingAcquisitions(stack('1', 0, 3)); + + expect(parts[0].parts.map(([rule]) => rule)).toEqual([ + 'acquisition', + 'phase', + 'echo', + 'b-value', + ...DESCRIPTOR_AXES.map((axis) => axis.rule), + ]); + }); + + it('separates overlapping acquisitions merged into one series', () => { + // The reference bug, IDC series + // 1.3.6.1.4.1.14519.5.2.1.3098.5025.295130953269492004748715270821 + // ("ST+ N15/12/17 A30/20/40"): three overlapping 2.5mm passes that merged + // into one 447-slice volume at a fabricated 1.478mm spacing. + const acq1 = stack('1', -20, 5); + const acq2 = stack('2', -19.25, 6); + const acq3 = stack('3', -18.5, 4); + + const parts = splitOverlappingAcquisitions( + [...acq1, ...acq2, ...acq3].sort(byPosition) + ); + + expect(labels(parts)).toEqual([ + 'acquisition 1', + 'acquisition 2', + 'acquisition 3', + ]); + expect(partLabelled(parts, 'acquisition 1').members).toEqual(acq1); + expect(partLabelled(parts, 'acquisition 2').members).toEqual(acq2); + expect(partLabelled(parts, 'acquisition 3').members).toEqual(acq3); + expect(partLabelled(parts, 'acquisition 2').parts).toEqual([ + ['acquisition', '2'], + ['phase', null], + ['echo', null], + ['b-value', null], + ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), + ]); + expect(parts.every((part) => !part.repeatedPositions)).toBe(true); + }); + + it('keeps acquisitions that follow one another together', () => { + // IDC series + // 1.3.6.1.4.1.14519.5.2.1.7009.2403.262533307142705262678914598920 + // ("Recon 2: CHEST"): one continuous 5mm stack whose slices carry three + // acquisition numbers, with a 30mm hole where slices are missing. Uneven + // spacing is not a reason to tear the scans apart. + const merged = [ + ...stack('3', -320.25, 4, 5), + ...stack('2', -300.25, 6, 5), + ...stack('1', -245.25, 56, 5), + ].sort(byPosition); + + const parts = splitOverlappingAcquisitions(merged); + + expect(parts).toHaveLength(1); + expect(parts[0].members).toEqual(merged); + expect(parts[0].label).toBeNull(); + expect(parts[0].repeatedPositions).toBe(false); + }); + + it('leaves a long run of sequential acquisitions merged', () => { + // IDC series + // 1.3.6.1.4.1.14519.5.2.1.3320.3273.243812674588352758771557518364: + // acquisitions numbered 20 through 36 across one evenly spaced stack. + const groups = Array.from({ length: 17 }, (_, i) => + stack(String(20 + i), i * 25, 10) + ); + + const parts = splitOverlappingAcquisitions(groups.flat().sort(byPosition)); + + expect(parts).toHaveLength(1); + }); + + it('tolerates quantized whole-body PET positions', () => { + // IDC series + // 1.3.6.1.4.1.14519.5.2.1.7009.2403.337074050757748643824459343650 + // ("WB_3D_NON-AC"): whole-body PET stepping by 3.27mm with the occasional + // 3.35mm step from printing precision. One acquisition, nothing to + // separate. + const members = [0, 3.27, 6.54, 9.89, 13.16, 16.43].map((z) => + slice(z, { [Tags.AcquisitionNumber]: '1' }) + ); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toHaveLength(1); + expect(parts[0].repeatedPositions).toBe(false); + }); + + it('leaves repeat scans of one plane whole and flags the repetition', () => { + // IDC series + // 1.3.6.1.4.1.14519.5.2.1.7009.2403.668914995861790731496154478744 + // ("Smart Prep Series"), bolus tracking: seven scans of the same slice, + // one acquisition each. That is a time series of one plane, and fanning it + // out would make seven one-slice datasets. + const members = Array.from({ length: 7 }, (_, i) => + slice(-82.89, { [Tags.AcquisitionNumber]: String(i + 1) }) + ); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toEqual([ + { + parts: unsplitParts, + members, + label: null, + repeatedPositions: true, + unreadablePositions: false, + }, + ]); + }); + + it('does not fan out a counter stamped per slice over one repeated position', () => { + // Some scanners set AcquisitionNumber from InstanceNumber. One duplicate + // slice must not turn such a stack into one dataset per slice. + const members = [0, 2.5, 5, 5, 7.5, 10].map((z, i) => + slice(z, { [Tags.AcquisitionNumber]: String(i + 1) }) + ); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toHaveLength(1); + expect(parts[0].label).toBeNull(); + expect(parts[0].repeatedPositions).toBe(true); + }); + + it('leaves a single overlapping slice of another pass merged', () => { + const members = [...stack('1', 0, 3), ...stack('2', 2.5, 1)].sort( + byPosition + ); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toHaveLength(1); + expect(parts[0].repeatedPositions).toBe(true); + }); + + it.each([ + ['acquisition', Tags.AcquisitionNumber], + ['phase', Tags.TemporalPositionIdentifier], + ])( + 'keeps singleton %s values with the remainder of overlapping scans', + (rule, tag) => { + const scans = ['1', '2'].flatMap((value) => + [0, 2, 4, 6, 8].map((z) => slice(z, { [tag]: value })) + ); + const remainder = [ + slice(1, { [tag]: '3' }), + slice(3), + slice(5, { [tag]: '4' }), + ]; + + const parts = splitOverlappingAcquisitions( + [...scans, ...remainder].sort(byPosition) + ); + + expect(labels(parts)).toEqual([ + `${rule} 1`, + `${rule} 2`, + `${rule} mixed`, + ]); + expect(partLabelled(parts, `${rule} mixed`).members).toEqual(remainder); + expect(partValue(partLabelled(parts, `${rule} mixed`), rule)).toBeNull(); + } + ); + + it('still separates contrasts within singleton counter values', () => { + const scans = [...stack('1', 0, 3), ...stack('2', 0, 3)]; + const contrasts = ['1', '2'].map((echo, index) => + slice(2.5, { + [Tags.AcquisitionNumber]: String(index + 3), + [Tags.EchoNumbers]: echo, + }) + ); + + const parts = splitOverlappingAcquisitions([...scans, ...contrasts]); + + expect(labels(parts)).toEqual([ + 'acquisition 1', + 'acquisition 2', + 'acquisition 3, echo 1', + 'acquisition 4, echo 2', + ]); + contrasts.forEach((member, index) => + expect( + partLabelled(parts, `acquisition ${index + 3}, echo ${index + 1}`) + .members + ).toEqual([member]) + ); + }); + + it('leaves a repeated plane inside a split whole', () => { + // A full stack plus a bolus-tracking pass of one plane, each frame with + // its own phase: the pass is a time series, not twenty datasets. + const volume = stack('1', 0, 10); + const monitoring = Array.from({ length: 20 }, (_, i) => + slice(5, { + [Tags.AcquisitionNumber]: '2', + [Tags.TemporalPositionIdentifier]: String(i + 1), + }) + ); + + const parts = splitOverlappingAcquisitions( + [...volume, ...monitoring].sort(byPosition) + ); + + expect(labels(parts)).toEqual(['acquisition 1', 'acquisition 2']); + expect(partLabelled(parts, 'acquisition 2').members).toHaveLength(20); + expect(partLabelled(parts, 'acquisition 2').repeatedPositions).toBe(true); + }); + + it('separates scans that share a boundary slice', () => { + const merged = [...stack('1', 0, 4), ...stack('2', 7.5, 4)].sort( + byPosition + ); + + expect(labels(splitOverlappingAcquisitions(merged))).toEqual([ + 'acquisition 1', + 'acquisition 2', + ]); + }); + + it('does not separate scans that abut without overlapping', () => { + const merged = [...stack('1', 0, 4), ...stack('2', 10, 4)].sort(byPosition); + + expect(splitOverlappingAcquisitions(merged)).toHaveLength(1); + }); + + it('reports repeated positions no axis separates', () => { + const members = [0, 2.5, 2.5, 5].map((z) => + slice(z, { [Tags.AcquisitionNumber]: '1' }) + ); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toHaveLength(1); + expect(parts[0].repeatedPositions).toBe(true); + }); + + it('ignores slices with no acquisition number', () => { + const members = [0, 2.5, 5, 6.25, 8.75].map((z) => slice(z)); + + const parts = splitOverlappingAcquisitions(members); + + expect(parts).toHaveLength(1); + expect(parts[0].repeatedPositions).toBe(false); + }); + + it('holds members whose position cannot be read in a part of their own', () => { + const blind = makeFacts('uid-a', { + projectedPosition: null, + acquisitionNumber: '1', + }); + const first = stack('2', 0, 3); + const second = stack('3', 1, 3); + + const parts = splitOverlappingAcquisitions([blind, ...first, ...second]); + + // The two overlapping acquisitions stay separated, and the member nothing + // spatial can be said about is diagnosed rather than merged into them. + expect(labels(parts)).toEqual([ + 'acquisition 2', + 'acquisition 3', + UNREADABLE_GEOMETRY_LABEL, + ]); + const unknown = partLabelled(parts, UNREADABLE_GEOMETRY_LABEL); + expect(unknown.members).toEqual([blind]); + expect(partLabelled(parts, 'acquisition 2').members).toEqual(first); + expect(partLabelled(parts, 'acquisition 3').members).toEqual(second); + expect(unknown.unreadablePositions).toBe(true); + expect(partValue(unknown, GEOMETRY_RULE)).toBe(UNREADABLE_GEOMETRY); + parts + .filter((part) => part !== unknown) + .forEach((part) => { + expect(part.unreadablePositions).toBe(false); + expect(part.parts.some(([rule]) => rule === GEOMETRY_RULE)).toBe(false); + }); + }); + + it('keeps members whose positions are all unreadable in one diagnosed part', () => { + const blind = [ + makeFacts('uid-a', { projectedPosition: null }), + makeFacts('uid-b', { projectedPosition: null }), + ]; + + const parts = splitOverlappingAcquisitions(blind); + + expect(parts).toHaveLength(1); + expect(parts[0].members).toEqual(blind); + expect(parts[0].unreadablePositions).toBe(true); + }); + + it('keeps each part in the member order it was given', () => { + const acq1 = stack('1', -20, 5); + const acq2 = stack('2', -19.25, 6); + const merged = [...acq1, ...acq2].sort(byPosition); + + const parts = splitOverlappingAcquisitions(merged); + + parts.forEach((part) => { + expect(part.members).toEqual([...part.members].sort(byPosition)); + }); + }); + + it('is invariant to member permutation in membership', () => { + const acq1 = stack('1', -20, 5); + const acq2 = stack('2', -19.25, 6); + const forward = splitOverlappingAcquisitions([...acq1, ...acq2]); + const backward = splitOverlappingAcquisitions([...acq2, ...acq1].reverse()); + + const membership = (parts: SemanticPart[]) => + parts + .map((part) => ({ + label: part.label, + uids: part.members.map((m) => m.sopInstanceUid).sort(), + })) + .sort((a, b) => (a.label! < b.label! ? -1 : 1)); + + expect(membership(backward)).toEqual(membership(forward)); + }); + + it('keeps the value spelling the fact reader normalized', () => { + const merged = [...stack('01', 0, 5), ...stack('+2', 0.75, 5)].sort( + byPosition + ); + + const parts = splitOverlappingAcquisitions(merged); + + expect(labels(parts)).toEqual(['acquisition 1', 'acquisition 2']); + }); +}); + +describe('splitOverlappingAcquisitions temporal and echo axes', () => { + it('separates DCE timepoints that re-scan one range', () => { + const parts = splitOverlappingAcquisitions(fixtureSlices(dceEightPhase)); + + expect(labels(parts)).toEqual( + ['0', '1', '2', '3', '4', '5', '6', '7'].map((p) => `phase ${p}`) + ); + expect(partLabelled(parts, 'phase 3').members).toHaveLength(80); + expect(partValue(partLabelled(parts, 'phase 3'), 'phase')).toBe('3'); + expect(parts.every((part) => !part.repeatedPositions)).toBe(true); + }); + + it('separates timepoints across vendors and 1-based numbering', () => { + const parts = splitOverlappingAcquisitions( + fixtureSlices(dceSevenPhasePhilips) + ); + + expect(parts).toHaveLength(7); + parts.forEach((part) => { + expect(part.members).toHaveLength(158); + expect(part.repeatedPositions).toBe(false); + }); + }); + + it('separates Dixon echoes that nothing else distinguishes', () => { + const parts = splitOverlappingAcquisitions(fixtureSlices(dixonDualEcho)); + + expect(labels(parts)).toEqual(['echo 1', 'echo 2']); + expect(partLabelled(parts, 'echo 1').parts).toEqual([ + ['acquisition', null], + ['phase', null], + ['echo', '1'], + ['b-value', null], + ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), + ]); + }); + + it('separates echoes with unequal slice counts', () => { + const parts = splitOverlappingAcquisitions( + fixtureSlices(dixonUnevenEchoes) + ); + + expect(partLabelled(parts, 'echo 1').members).toHaveLength(13); + expect(partLabelled(parts, 'echo 2').members).toHaveLength(12); + }); + + it('separates repeated diffusion positions by b-value', () => { + const parts = splitOverlappingAcquisitions(fixtureSlices(dwiMultiBValue)); + + expect(labels(parts)).toEqual([ + 'b-value 0', + 'b-value 100', + 'b-value 600', + 'b-value 800', + ]); + parts.forEach((part) => { + expect(part.members).toHaveLength(30); + expect(part.repeatedPositions).toBe(false); + }); + }); + + it('isolates a slice missing the discriminator instead of blocking the split', () => { + const b0 = [0, 2, 4].map((z) => slice(z, { [Tags.DiffusionBValue]: '0' })); + const b800 = [0, 2, 4].map((z) => + slice(z, { [Tags.DiffusionBValue]: '800' }) + ); + const untagged = slice(2); + + const parts = splitOverlappingAcquisitions( + [...b0, untagged, ...b800].sort(byPosition) + ); + + expect(labels(parts)).toEqual([ + 'b-value 0', + 'b-value 800', + 'b-value unknown', + ]); + expect(partLabelled(parts, 'b-value unknown').members).toEqual([untagged]); + expect( + partValue(partLabelled(parts, 'b-value unknown'), 'b-value') + ).toBeNull(); + }); + + it('still separates contrasts of a single plane', () => { + // A one-slice in/out-phase pair differs in echo, not in time, so each + // echo is its own dataset even at one position. + const members = ['1', '2'].map((echo) => + slice(0, { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: echo }) + ); + + const parts = splitOverlappingAcquisitions(members); + + expect(labels(parts)).toEqual(['echo 1', 'echo 2']); + expect(parts.every((part) => !part.repeatedPositions)).toBe(true); + }); + + it('treats equivalent integer spellings as one tag value', () => { + const merged = [...stack('+1', 0, 5), ...stack('01', 0, 5)].sort( + byPosition + ); + + const parts = splitOverlappingAcquisitions(merged); + + expect(parts).toHaveLength(1); + expect(parts[0].repeatedPositions).toBe(true); + }); + + it('does not split bilateral slabs whose stacks do not overlap', () => { + // StackID (0020|9056) differs per slab, but the slabs form one sound + // volume with a gap; this series is why StackID is not an axis. + const parts = splitOverlappingAcquisitions( + fixtureSlices(bilateralSagittalSlabs) + ); + + expect(parts).toHaveLength(1); + expect(parts[0].repeatedPositions).toBe(false); + }); + + it('splits on acquisition when the temporal tag is partially present', () => { + const parts = splitOverlappingAcquisitions( + fixtureSlices(partialTemporalTags) + ); + + expect(labels(parts)).toEqual( + ['1', '2', '3', '4', '5', '6', '7'].map((a) => `acquisition ${a}`) + ); + expect(partLabelled(parts, 'acquisition 1').members).toHaveLength(72); + expect(parts.every((part) => !part.repeatedPositions)).toBe(true); + }); + + it('keeps sequential timepoints merged', () => { + const phase = (value: string, start: number, count: number) => + Array.from({ length: count }, (_, i) => + slice(start + i * 5, { [Tags.TemporalPositionIdentifier]: value }) + ); + + const parts = splitOverlappingAcquisitions( + [...phase('1', 0, 5), ...phase('2', 30, 5)].sort(byPosition) + ); + + expect(parts).toHaveLength(1); + }); + + it('splits a doubled acquisition and still flags the repetition', () => { + const parts = splitOverlappingAcquisitions( + fixtureSlices(doubledAcquisition) + ); + + expect(labels(parts)).toEqual(['acquisition 1', 'acquisition 2']); + expect(partLabelled(parts, 'acquisition 1').members).toHaveLength(74); + expect(partLabelled(parts, 'acquisition 1').repeatedPositions).toBe(false); + expect(partLabelled(parts, 'acquisition 2').members).toHaveLength(148); + expect(partLabelled(parts, 'acquisition 2').repeatedPositions).toBe(true); + }); + + it('recurses into each timepoint of a 4D multi-echo series', () => { + // Synthetic: no IDC case observed with two active levels. Pins the + // hierarchical key shape and label rendering. + const merged = ['1', '2'] + .flatMap((phase) => + ['1', '2'].flatMap((echo) => + Array.from({ length: 10 }, (_, i) => + slice(i * 2, { + [Tags.AcquisitionNumber]: '1', + [Tags.TemporalPositionIdentifier]: phase, + [Tags.EchoNumbers]: echo, + }) + ) + ) + ) + .sort(byPosition); + + const parts = splitOverlappingAcquisitions(merged); + + expect(labels(parts)).toEqual([ + 'phase 1, echo 1', + 'phase 1, echo 2', + 'phase 2, echo 1', + 'phase 2, echo 2', + ]); + expect(partLabelled(parts, 'phase 2, echo 1').parts).toEqual([ + ['acquisition', null], + ['phase', '2'], + ['echo', '1'], + ['b-value', null], + ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), + ]); + parts.forEach((part) => { + expect(part.members).toHaveLength(10); + }); + }); + + it('gives distinct values distinct key parts however they are spelled', () => { + // Normalized values remain distinct even when their punctuation differs. + const merged = [...stack('1.5', 0, 5), ...stack('1-5', 0, 5)].sort( + byPosition + ); + + const parts = splitOverlappingAcquisitions(merged); + + expect(labels(parts)).toEqual(['acquisition 1-5', 'acquisition 1.5']); + expect( + partValue(partLabelled(parts, 'acquisition 1-5'), 'acquisition') + ).toBe('1-5'); + }); +}); + +function readInstanceFacts(tags: Iterable) { + return readStructuredFacts(datasetFromTags(tags)); +} diff --git a/packages/dicom/core/collections/assignCollectionIds.ts b/packages/dicom/core/collections/assignCollectionIds.ts new file mode 100644 index 000000000..0233b9430 --- /dev/null +++ b/packages/dicom/core/collections/assignCollectionIds.ts @@ -0,0 +1,104 @@ +import type { + CollectionKey, + DicomCollection, + DicomCollectionPlan, +} from './planDicomCollections'; + +export type CommittedCollection = { + id: string; + sopInstanceUids: string[]; +}; + +export type AssignedCollection = DicomCollection & { id: string }; + +export type AssignedPlan = { + collections: AssignedCollection[]; +}; + +// encodeURIComponent escapes every separator the key values can carry, so the +// join characters below cannot appear inside an encoded component. +const escape = (value: string) => encodeURIComponent(value); + +// A present value is prefixed, so it can never collide with the missing marker. +const encodeValue = (value: string | null) => + value === null ? '~' : `.${escape(value)}`; + +/** Escaped encoding of a structured key, safe to use as a store ID. */ +export function encodeCollectionKey(key: CollectionKey) { + return [ + escape(key.seriesKey), + ...key.parts.map( + ([rule, value]) => `${escape(rule)}=${encodeValue(value)}` + ), + ].join('|'); +} + +const uidsOf = (collection: DicomCollection) => + new Set( + collection.members + .map((member) => member.sopInstanceUid) + .filter((uid): uid is string => uid !== null) + ); + +const overlapSize = (planned: Set, committed: Set) => + [...planned].filter((uid) => committed.has(uid)).length; + +const mint = (key: CollectionKey, taken: Set) => { + const base = encodeCollectionKey(key); + if (!taken.has(base)) return base; + const next = (suffix: number): string => { + const candidate = `${base}~${suffix}`; + return taken.has(candidate) ? next(suffix + 1) : candidate; + }; + return next(2); +}; + +/** + * Carries a committed ID over to the collection holding the plurality of its + * members; mints a fresh ID from the key otherwise. + */ +export function assignIds( + plan: DicomCollectionPlan, + committedIds: CommittedCollection[] +) { + const plannedUids = plan.collections.map(uidsOf); + const committedUids = committedIds.map( + (committed) => new Set(committed.sopInstanceUids) + ); + + // A committed ID moves only where its members are not split more evenly + // elsewhere: the plurality holder must be strictly ahead of every rival. + const claimable = committedIds.map((committed, committedIndex) => { + const overlaps = plannedUids.map((planned) => + overlapSize(planned, committedUids[committedIndex]) + ); + const best = Math.max(0, ...overlaps); + const holders = overlaps.filter((size) => size === best).length; + return best > 0 && holders === 1 + ? { plannedIndex: overlaps.indexOf(best), overlap: best, committed } + : null; + }); + + const claimFor = (plannedIndex: number) => + claimable + .filter( + (claim): claim is NonNullable => + claim !== null && claim.plannedIndex === plannedIndex + ) + .sort( + (left, right) => + right.overlap - left.overlap || + (left.committed.id < right.committed.id ? -1 : 1) + )[0]; + + const taken = new Set(committedIds.map((committed) => committed.id)); + + const collections = plan.collections.map((collection, index) => { + const claim = claimFor(index); + const id = claim ? claim.committed.id : mint(collection.key, taken); + taken.add(id); + return { ...collection, id }; + }); + + return { collections }; +} diff --git a/packages/dicom/core/collections/datasetDetails.ts b/packages/dicom/core/collections/datasetDetails.ts new file mode 100644 index 000000000..186726715 --- /dev/null +++ b/packages/dicom/core/collections/datasetDetails.ts @@ -0,0 +1,16 @@ +import type { DicomDataset } from '../metadata/dicomDataset'; +import { readInstanceDetails } from './instanceFacts'; + +// Parsed datasets are immutable, so derived facts live as long as the dataset. +const detailsByDataset = new WeakMap< + DicomDataset, + ReturnType +>(); + +export function readDatasetDetails(dataset: DicomDataset) { + const cached = detailsByDataset.get(dataset); + if (cached) return cached; + const details = readInstanceDetails(dataset); + detailsByDataset.set(dataset, details); + return details; +} diff --git a/packages/dicom/core/collections/groupBy.ts b/packages/dicom/core/collections/groupBy.ts new file mode 100644 index 000000000..fec13bb4b --- /dev/null +++ b/packages/dicom/core/collections/groupBy.ts @@ -0,0 +1,11 @@ +/** Groups preserve input order, both of the keys and of their members. */ +export const groupBy = (items: T[], keyOf: (item: T) => string) => { + const groups = new Map(); + items.forEach((item) => { + const key = keyOf(item); + const group = groups.get(key); + if (group) group.push(item); + else groups.set(key, [item]); + }); + return groups; +}; diff --git a/packages/dicom/core/collections/instanceFacts.ts b/packages/dicom/core/collections/instanceFacts.ts new file mode 100644 index 000000000..6c4e2774d --- /dev/null +++ b/packages/dicom/core/collections/instanceFacts.ts @@ -0,0 +1,205 @@ +import { dot } from './orientation'; +import { multiframeGeometry } from './multiframeGeometry'; +import type { InstanceFacts } from './planDicomCollections'; +import { Tags } from '../metadata/dicomTags'; +import type { DicomDataset } from '../metadata/dicomDataset'; +import { getFrameTag } from '../metadata/functionalGroups'; +import { trimDicomPadding } from '../utils'; + +// readDicomTags hands back DICOM's own byte padding, so a value that is only +// padding is absent rather than an empty string. +const textOf = (metadata: DicomDataset, tag: string) => { + const value = trimDicomPadding(getFrameTag(metadata, tag) ?? ''); + return value.length > 0 ? value : null; +}; + +// Hard facts are compared for equality, so '04', '4' and '4.0' must be one +// value. A value that is not a number keeps its own spelling. +const numericTextOf = (metadata: DicomDataset, tag: string) => { + const text = textOf(metadata, tag); + if (text === null) return null; + const value = Number(text); + return Number.isFinite(value) ? String(value) : text; +}; + +const numberOf = (metadata: DicomDataset, tag: string) => { + const text = textOf(metadata, tag); + if (text === null) return null; + const value = Number(text); + return Number.isFinite(value) ? value : null; +}; + +// A blank component is absent, not zero: Number('') is 0, which would turn +// '1\\3' into the readable position [1, 0, 3]. +const vectorOf = ( + metadata: DicomDataset, + tag: string, + length: number, + frameIndex = 0 +) => { + const raw = getFrameTag(metadata, tag, frameIndex); + const text = raw === undefined ? null : trimDicomPadding(raw); + if (text === null) return null; + const parts = text.split('\\').map(trimDicomPadding); + const values = parts.map(Number); + return parts.length === length && + parts.every((part) => part.length > 0) && + values.every((value) => Number.isFinite(value)) + ? values + : null; +}; + +const cross = (left: number[], right: number[]) => [ + left[1] * right[2] - left[2] * right[1], + left[2] * right[0] - left[0] * right[2], + left[0] * right[1] - left[1] * right[0], +]; + +/** + * How far the row and column cosines may be from square, once each is scaled + * to unit length, before they span no plane. GDCM allows a thousandth and + * rescales any axis it is given, so a value printed to three decimals loads + * as the scanner meant it while a skewed basis still does not. + */ +export const ORTHOGONALITY_TOLERANCE = 1e-3; + +const magnitude = (axis: number[]) => Math.sqrt(dot(axis, axis)); + +/** + * The axis scaled to unit length, or null when it has no length to scale. A + * printed cosine is never exactly unit, so the length it was written with is + * corrected rather than judged. + */ +const unitize = (axis: number[]) => { + const size = magnitude(axis); + return size > 0 ? axis.map((component) => component / size) : null; +}; + +/** + * Row and column cosines, normalized, or null when they are not two axes + * spanning a plane. A degenerate or skewed basis has no slice normal, so + * nothing can be projected on it. + */ +const orientationOf = (metadata: DicomDataset, frameIndex: number) => { + const cosines = vectorOf( + metadata, + Tags.ImageOrientationPatient, + 6, + frameIndex + ); + if (cosines === null) return null; + + const row = unitize(cosines.slice(0, 3)); + const column = unitize(cosines.slice(3, 6)); + if (row === null || column === null) return null; + if (Math.abs(dot(row, column)) > ORTHOGONALITY_TOLERANCE) return null; + + return [...row, ...column]; +}; + +/** + * The slice normal of a validated orientation: the row cosines crossed with + * the column cosines, which is only the z axis for an axial acquisition. + * Unit length to within the orthogonality tolerance, since the two axes are + * unit and square to it. + */ +export const sliceNormalOf = (orientation: number[] | null) => + orientation === null + ? null + : cross(orientation.slice(0, 3), orientation.slice(3, 6)); + +/** Where a position sits along a slice normal, in mm. */ +export const projectOnNormal = ( + normal: number[] | null, + position: number[] | null +) => (normal === null || position === null ? null : dot(normal, position)); + +// A pixel spacing of zero or less places no sample anywhere. +const pixelSpacingOf = (metadata: DicomDataset, frameIndex: number) => { + const raw = getFrameTag(metadata, Tags.PixelSpacing, frameIndex); + const parts = raw?.split('\\').slice(0, 2).map(trimDicomPadding); + const spacing = + parts?.length === 2 && parts.every(Boolean) ? parts.map(Number) : null; + return spacing !== null && + spacing.every((value) => Number.isFinite(value) && value > 0) + ? spacing + : null; +}; + +/** + * Where an instance places its samples, for callers that need nothing else. + * Reading it costs three tag lookups rather than the twenty a full fact read + * takes, which a volume of two thousand slices notices. + */ +export function readGeometryFacts(metadata: DicomDataset, frameIndex = 0) { + return { + orientation: orientationOf(metadata, frameIndex), + position: vectorOf(metadata, Tags.ImagePositionPatient, 3, frameIndex), + pixelSpacing: pixelSpacingOf(metadata, frameIndex), + }; +} + +/** Reads planning facts and the full frame geometry from the same header. */ +export function readInstanceDetails(metadata: DicomDataset) { + const frames = + textOf(metadata, Tags.Modality) === 'SEG' + ? null + : multiframeGeometry( + metadata, + numberOf(metadata, Tags.NumberOfFrames) ?? 1 + ); + const { orientation, position, pixelSpacing } = + frames ?? readGeometryFacts(metadata); + + const facts: InstanceFacts = { + ...(frames ? { frameReconstruction: frames.reconstruction } : {}), + sopInstanceUid: textOf(metadata, Tags.SOPInstanceUID), + seriesInstanceUid: textOf(metadata, Tags.SeriesInstanceUID), + seriesNumber: numericTextOf(metadata, Tags.SeriesNumber), + sequenceName: textOf(metadata, Tags.SequenceName), + sliceThickness: numericTextOf(metadata, Tags.SliceThickness), + seriesDate: textOf(metadata, Tags.SeriesDate), + rows: numericTextOf(metadata, Tags.Rows), + columns: numericTextOf(metadata, Tags.Columns), + samplesPerPixel: numericTextOf(metadata, Tags.SamplesPerPixel), + numberOfFrames: numericTextOf(metadata, Tags.NumberOfFrames) ?? '1', + orientation, + position, + projectedPosition: projectOnNormal(sliceNormalOf(orientation), position), + pixelSpacing, + instanceNumber: numberOf(metadata, Tags.InstanceNumber), + acquisitionNumber: numericTextOf(metadata, Tags.AcquisitionNumber), + temporalPositionIdentifier: numericTextOf( + metadata, + Tags.TemporalPositionIdentifier + ), + echoNumbers: numericTextOf(metadata, Tags.EchoNumbers), + diffusionBValue: numericTextOf(metadata, Tags.DiffusionBValue), + }; + return { facts, frameGeometry: frames }; +} + +/** Reads the planner's plain facts out of one instance's tag values. */ +export function readInstanceFacts(metadata: DicomDataset) { + return readInstanceDetails(metadata).facts; +} + +// Carries a separator no UID can hold, so a fallback key never equals a real +// series key. +const NO_SERIES_UID = 'no-series'; + +/** + * The grouping key for one instance's series. Instances of different series + * are planned independently. + */ +export function seriesKeyOf(metadata: DicomDataset) { + const seriesUid = textOf(metadata, Tags.SeriesInstanceUID); + if (seriesUid !== null) return seriesUid; + + // Escaped, so moving a separator from one part to the other changes the key. + return [ + NO_SERIES_UID, + encodeURIComponent(textOf(metadata, Tags.StudyInstanceUID) ?? ''), + encodeURIComponent(textOf(metadata, Tags.PatientID) ?? ''), + ].join('|'); +} diff --git a/packages/dicom/core/collections/instanceKey.ts b/packages/dicom/core/collections/instanceKey.ts new file mode 100644 index 000000000..7d91d372d --- /dev/null +++ b/packages/dicom/core/collections/instanceKey.ts @@ -0,0 +1,16 @@ +import type { InstanceFacts } from './planDicomCollections'; + +const anonymousKeys = new WeakMap(); +let nextAnonymousKey = 0; + +// Chunk facts are cached for the lifetime of their metadata. Object identity +// survives replanning without retaining discarded facts, and the prefix cannot +// be a DICOM UID, whose alphabet contains only digits and dots. +export const instanceKey = (instance: InstanceFacts) => { + if (instance.sopInstanceUid !== null) return instance.sopInstanceUid; + const existing = anonymousKeys.get(instance); + if (existing) return existing; + const created = `anonymous:${nextAnonymousKey++}`; + anonymousKeys.set(instance, created); + return created; +}; diff --git a/packages/dicom/core/collections/instanceRegistry.ts b/packages/dicom/core/collections/instanceRegistry.ts new file mode 100644 index 000000000..97e859fe2 --- /dev/null +++ b/packages/dicom/core/collections/instanceRegistry.ts @@ -0,0 +1,241 @@ +import type { Instance } from '../instance/readInstance'; +import { trimDicomPadding } from '../utils'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; +import { + planDicomCollections, + type DicomCollection, + type InstanceFacts, +} from './planDicomCollections'; +import { + assignIds, + encodeCollectionKey, + type CommittedCollection, +} from './assignCollectionIds'; +import { seriesKeyOf } from './instanceFacts'; +import { readDatasetDetails } from './datasetDetails'; +import { groupBy } from './groupBy'; + +export type InstanceCollectionUpdate = { + id: string; + seriesKey: string; + collection: DicomCollection; + /** Registered instances in the collection's order, aligned with collection.members. */ + members: Instance[]; + /** Aligned with members: the batch's own instance wherever it re-supplied one. */ + provenance: Instance[]; +}; + +// An instance with no SOP Instance UID is identified by its object, so two of +// them never merge while re-registering one does not duplicate it. +type InstanceKey = string | Instance; + +type Registered = { + key: InstanceKey; + instance: Instance; + facts: InstanceFacts; +}; + +type Committed = { + members: readonly InstanceKey[]; + // Reported when relabelled even if its members did not move. + key: string; +}; + +type SeriesState = { + instances: ReadonlyMap; + committed: ReadonlyMap; +}; + +/** Every instance seen so far and the collections last planned, per series. */ +export type RegistryState = ReadonlyMap; + +export const emptyRegistry: RegistryState = new Map(); + +const emptySeries: SeriesState = { instances: new Map(), committed: new Map() }; + +// One facts object per instance: the planner's members are matched back by identity. +const factsByInstance = new WeakMap(); + +const factsOf = (instance: Instance) => { + const cached = factsByInstance.get(instance); + if (cached) return cached; + const facts = { ...readDatasetDetails(instance.dataset).facts }; + factsByInstance.set(instance, facts); + return facts; +}; + +const keyOf = (instance: Instance): InstanceKey => + trimDicomPadding( + getDatasetTag(instance.dataset, Tags.SOPInstanceUID) ?? '' + ) || instance; + +const registeredOf = (instance: Instance): Registered => ({ + key: keyOf(instance), + instance, + facts: factsOf(instance), +}); + +// A collection holding no SOP Instance UID cannot be claimed back by overlap, +// so its ID is re-minted from its key instead of counting as taken. +const claimable = (committed: SeriesState['committed']) => + [...committed] + .map( + ([id, { members }]): CommittedCollection => ({ + id, + sopInstanceUids: members.filter( + (key): key is string => typeof key === 'string' + ), + }) + ) + .filter((collection) => collection.sopInstanceUids.length > 0); + +const unchanged = (before: Committed | undefined, after: Committed) => + before !== undefined && + before.key === after.key && + before.members.length === after.members.length && + before.members.every((key, index) => key === after.members[index]); + +// The first registration of an instance wins; a re-supply only reports back. +function mergeBatch(series: SeriesState, batch: Registered[]) { + const instances = new Map(series.instances); + const conflicting = new Set(); + batch.forEach((entry) => { + const existing = instances.get(entry.key); + if (!existing) instances.set(entry.key, entry); + else if ( + typeof entry.key === 'string' && + JSON.stringify(existing.facts) !== JSON.stringify(entry.facts) + ) + conflicting.add(entry.key); + }); + return { instances, conflicting }; +} + +const firstByKey = (batch: Registered[]) => + batch.reduce( + (byKey, entry) => + byKey.has(entry.key) ? byKey : byKey.set(entry.key, entry.instance), + new Map() + ); + +function planSeries( + series: SeriesState, + seriesKey: string, + batch: Registered[] +) { + const { instances, conflicting } = mergeBatch(series, batch); + const registered = [...instances.values()]; + const plan = planDicomCollections({ + seriesKey, + instances: registered.map((entry) => entry.facts), + }); + const assigned = assignIds(plan, claimable(series.committed)); + const entryOf = new Map(registered.map((entry) => [entry.facts, entry])); + const supplied = firstByKey(batch); + const provenanceOf = ({ key, instance }: Registered) => + typeof key === 'string' && conflicting.has(key) + ? instance + : (supplied.get(key) ?? instance); + + const planned = assigned.collections.map(({ id, ...collection }) => { + const entries = collection.members.map((facts) => entryOf.get(facts)!); + const committed: Committed = { + members: entries.map((entry) => entry.key), + key: encodeCollectionKey(collection.key), + }; + const update: InstanceCollectionUpdate = { + id, + seriesKey, + collection, + members: entries.map((entry) => entry.instance), + provenance: entries.map(provenanceOf), + }; + // A replan can move members or relabel a collection the batch brought nothing. + const changed = + committed.members.some((key) => supplied.has(key)) || + !unchanged(series.committed.get(id), committed); + return { committed, update, changed }; + }); + + return { + series: { + instances, + committed: new Map( + planned.map(({ update, committed }) => [update.id, committed]) + ), + }, + updates: planned + .filter(({ changed }) => changed) + .map(({ update }) => update), + removed: [...series.committed.keys()].filter( + (id) => !planned.some(({ update }) => update.id === id) + ), + conflictingInstanceUids: [...conflicting], + }; +} + +/** + * Registers a batch and replans every series it touches. Pure: the caller + * keeps the returned state, so abandoning an import is not assigning it. + */ +export function registerInstances( + state: RegistryState, + batch: readonly Instance[] +) { + const bySeries = groupBy([...batch], (instance) => + seriesKeyOf(instance.dataset) + ); + const results = [...bySeries].map(([seriesKey, instances]) => ({ + seriesKey, + ...planSeries( + state.get(seriesKey) ?? emptySeries, + seriesKey, + instances.map(registeredOf) + ), + })); + const next = new Map(state); + results.forEach(({ seriesKey, series }) => next.set(seriesKey, series)); + return { + state: next as RegistryState, + updates: results.flatMap((result) => result.updates), + /** Committed IDs the replan dissolved, whose members moved elsewhere. */ + removed: results.flatMap((result) => result.removed), + /** Different geometry under a registered SOP Instance UID; the first copy is kept. */ + conflictingInstanceUids: results.flatMap( + (result) => result.conflictingInstanceUids + ), + }; +} + +function forgetFromSeries(series: SeriesState, collectionId: string) { + const forgotten = series.committed.get(collectionId); + if (!forgotten) return series; + const instances = new Map(series.instances); + forgotten.members.forEach((key) => instances.delete(key)); + const committed = new Map(series.committed); + committed.delete(collectionId); + return { instances, committed }; +} + +/** Drops a collection and the instances it held, so a re-import plans them afresh. */ +export function forgetCollection( + state: RegistryState, + collectionId: string +): RegistryState { + const owner = [...state].find(([, series]) => + series.committed.has(collectionId) + ); + if (!owner) return state; + const [seriesKey, series] = owner; + const next = new Map(state); + const remaining = forgetFromSeries(series, collectionId); + if (remaining.instances.size === 0) next.delete(seriesKey); + else next.set(seriesKey, remaining); + return next; +} + +/** Whether this object, not merely an equal copy, is the registered instance. */ +export const isRegistered = (state: RegistryState, instance: Instance) => + state.get(seriesKeyOf(instance.dataset))?.instances.get(keyOf(instance)) + ?.instance === instance; diff --git a/packages/dicom/core/collections/multiframeGeometry.ts b/packages/dicom/core/collections/multiframeGeometry.ts new file mode 100644 index 000000000..30adbf375 --- /dev/null +++ b/packages/dicom/core/collections/multiframeGeometry.ts @@ -0,0 +1,72 @@ +import type { DicomDataset } from '../metadata/dicomDataset'; +import { readGeometryFacts, sliceNormalOf } from './instanceFacts'; +import { reconstructVolume, type Reconstruction } from './reconstructVolume'; +import { dot, orientationsAgree } from './orientation'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { trimDicomPadding } from '../utils'; +import { perFrameGroups, sequenceItems } from '../metadata/functionalGroups'; + +function storageDirection(frames: ReturnType[]) { + const first = frames[0]; + const normal = sliceNormalOf(first.orientation); + const last = frames.at(-1)!.position; + const delta = first.position?.map((value, index) => + last ? last[index] - value : 0 + ); + const sign = normal && delta && dot(normal, delta) < 0 ? -1 : 1; + return normal?.map((value) => value * sign) ?? null; +} + +const singleSpatialStack = (groups: DicomDataset[]) => + ['00209056', '00209128'].every((tag) => { + const values = groups + .map((group) => + trimDicomPadding( + getDatasetTag(sequenceItems(group, '00209111')[0], tag) ?? '' + ) + ) + .filter(Boolean); + return new Set(values).size <= 1; + }); + +/** + * Patient-space frames keep their stored pixel order. The third direction + * follows the positions, which can run opposite the row/column cross product. + * Ophthalmic scan-line coordinates require a separate calibrated localizer; + * optical SliceThickness cannot substitute for their separation. + */ +export function multiframeGeometry(metadata: DicomDataset, count: number) { + const groups = perFrameGroups(metadata); + const shared = sequenceItems(metadata, '52009229'); + if (count < 2 || (shared.length === 0 && groups.length === 0)) return null; + const frames = Array.from({ length: count }, (_, index) => + readGeometryFacts(metadata, index) + ); + const first = frames[0]; + const direction = storageDirection(frames); + const reconstruction = reconstructVolume(frames, direction); + const readable = + groups.length === count && + singleSpatialStack(groups) && + frames.every( + (frame) => + frame.pixelSpacing !== null && + first.orientation !== null && + frame.orientation !== null && + orientationsAgree(first.orientation, frame.orientation) + ); + const validated: Reconstruction = readable + ? reconstruction + : { + kind: 'irregular', + reason: 'unreadable-geometry', + sliceSpacing: reconstruction.sliceSpacing, + slots: [0], + }; + return { + ...first, + direction, + sliceSpacingSource: 'ImagePositionPatient', + reconstruction: { ...validated, slots: [0] }, + }; +} diff --git a/packages/dicom/core/collections/orientation.ts b/packages/dicom/core/collections/orientation.ts new file mode 100644 index 000000000..1529fe569 --- /dev/null +++ b/packages/dicom/core/collections/orientation.ts @@ -0,0 +1,11 @@ +/** Minimum agreement of normalized row and column direction cosines. */ +export const ORIENTATION_TOLERANCE = 1e-4; + +export const dot = (left: number[], right: number[], offset = 0) => + left[offset] * right[offset] + + left[offset + 1] * right[offset + 1] + + left[offset + 2] * right[offset + 2]; + +export const orientationsAgree = (left: number[], right: number[]) => + dot(left, right) >= 1 - ORIENTATION_TOLERANCE && + dot(left, right, 3) >= 1 - ORIENTATION_TOLERANCE; diff --git a/packages/dicom/core/collections/planDicomCollections.ts b/packages/dicom/core/collections/planDicomCollections.ts new file mode 100644 index 000000000..b2aa745ff --- /dev/null +++ b/packages/dicom/core/collections/planDicomCollections.ts @@ -0,0 +1,595 @@ +import { orientationsAgree } from './orientation'; +import { groupBy } from './groupBy'; +import { instanceKey } from './instanceKey'; +import { + SEMANTIC_AXES, + splitOverlappingAcquisitions, + type PositionOf, +} from './splitOverlappingAcquisitions'; +import { projectOnNormal, sliceNormalOf } from './instanceFacts'; +import { + IN_PLANE_TOLERANCE_MM, + reconstructInstances, + type IrregularReason, + type Reconstruction, +} from './reconstructVolume'; + +/** + * Facts read once per instance from a chunk's metadata. Plain data: the planner + * never sees a Chunk, a store, or an itk-wasm task. + */ +export type InstanceFacts = { + // Identity. Instances without a SOP Instance UID are never deduplicated. + sopInstanceUid: string | null; + seriesInstanceUid: string | null; + + // Acquisition descriptors split spatial stacks only where their ranges overlap. + seriesNumber: string | null; + sequenceName: string | null; + sliceThickness: string | null; + seriesDate: string | null; + // Pixel shape must agree before slices can share an allocation. + rows: string | null; + columns: string | null; + samplesPerPixel: string | null; + numberOfFrames: string | null; + + // Geometry. Any of these may be unreadable. + orientation: number[] | null; + position: number[] | null; + projectedPosition: number | null; + pixelSpacing: number[] | null; + /** Intra-instance frame geometry; slots still index source chunks. */ + frameReconstruction?: Reconstruction; + + // Ordering fallback. + instanceNumber: number | null; + + // Semantic partition facts: what distinguishes one scan of a range from + // another within a series. Normalized for equality. + acquisitionNumber: string | null; + temporalPositionIdentifier: string | null; + echoNumbers: string | null; + diffusionBValue: string | null; +}; + +export type CollectionKey = { + seriesKey: string; + parts: Array<[string, string | null]>; +}; + +export type MemberOrder = 'spatial' | 'instance-number' | 'input'; + +export type DicomCollection = { + key: CollectionKey; + members: InstanceFacts[]; + order: MemberOrder; + // The axes the members were ordered and judged on. Allocation must build + // on these too, or the warnings describe a volume other than the one shown. + orientation: number[] | null; + reconstruction: Reconstruction; + // Names the scan the collection was separated out as ('acquisition 2', + // 'phase 3, echo 1'); null when nothing separated it from its series. + label: string | null; + // Per-member notes about how the plan was reached. + diagnostics: string[]; + // Conditions the user should hear about: the collection loads, but not as + // the sound volume its series promised. + warnings: string[]; +}; + +export type DicomCollectionPlan = { + collections: DicomCollection[]; +}; + +export type PlanInput = { + seriesKey: string; + instances: InstanceFacts[]; +}; + +export { ORIENTATION_TOLERANCE } from './orientation'; + +// The hard facts, in the order they appear in a collection key. +export const HARD_FACT_RULES = [ + 'rows', + 'columns', + 'samplesPerPixel', + 'numberOfFrames', +] as const; + +export const ORIENTATION_RULE = 'orientation'; + +export const REPEATED_POSITIONS_WARNING = + 'holds repeated slice positions that no tag separates. Its slice spacing ' + + 'and measurements along the slice axis may be wrong.'; + +export const IRREGULAR_VOLUME_WARNING = + 'does not sample one regular volume: its slices are not evenly spaced on ' + + 'one grid. They were placed one slot apart in the order shown, so ' + + 'positions and measurements along the slice axis may be wrong.'; + +export const UNREADABLE_POSITION_WARNING = + 'holds slices whose position could not be read. They were kept out of the ' + + 'volumes of their series, and their order and spacing may be wrong.'; + +export const NONPARALLEL_SLICES_WARNING = + 'holds slices that are not parallel to one another. They were stacked on ' + + 'the axes most of them declare, so positions and measurements may be wrong.'; + +export const IN_PLANE_SHIFT_WARNING = + 'holds slices that are offset within their own plane from one to the next, ' + + 'as a tilted gantry produces. They were stacked without correcting for the ' + + 'offset, so positions and measurements across slices may be wrong.'; + +// A repeated or unreadable position makes a stack irregular too, and already +// carries a warning of its own. +const RECONSTRUCTION_WARNINGS: Record = { + 'unreadable-geometry': [], + 'repeated-position': [], + 'uneven-slice-spacing': [IRREGULAR_VOLUME_WARNING], + 'in-plane-shift': [IN_PLANE_SHIFT_WARNING], + 'mixed-pixel-spacing': [IRREGULAR_VOLUME_WARNING], +}; + +export const UNREADABLE_FRAME_GEOMETRY_WARNING = + 'holds frames whose spatial geometry could not be established. They were ' + + 'placed one slot apart in stored order, so positions and measurements ' + + 'along the slice axis may be wrong.'; + +const reconstructionWarnings = ( + reconstruction: Reconstruction, + intraInstance: boolean +) => { + if (reconstruction.kind === 'regular') return []; + if (intraInstance && reconstruction.reason === 'unreadable-geometry') + return [UNREADABLE_FRAME_GEOMETRY_WARNING]; + if (intraInstance && reconstruction.reason === 'repeated-position') + return [REPEATED_POSITIONS_WARNING]; + return RECONSTRUCTION_WARNINGS[reconstruction.reason]; +}; + +const ANONYMOUS = 'an instance with no SOP Instance UID'; + +const label = (instance: InstanceFacts) => + instance.sopInstanceUid === null + ? ANONYMOUS + : `instance ${instance.sopInstanceUid}`; + +// Nulls sort last so a missing identity never becomes a bucket representative. +const compareUid = (left: string | null, right: string | null) => { + if (left === right) return 0; + if (left === null) return 1; + if (right === null) return -1; + return left < right ? -1 : 1; +}; + +const compareBySopUid = (left: InstanceFacts, right: InstanceFacts) => + compareUid(left.sopInstanceUid, right.sopInstanceUid); + +const readableNumber = (value: number | null): value is number => + value !== null && Number.isFinite(value); + +const compareText = (left: string, right: string) => { + if (left === right) return 0; + return left < right ? -1 : 1; +}; + +// Unreadable numbers sort last so they never win a tie-break. +const compareNumber = (left: number | null, right: number | null) => { + if (!readableNumber(left)) return readableNumber(right) ? 1 : 0; + if (!readableNumber(right)) return -1; + return left === right ? 0 : left - right; +}; + +// JSON collapses NaN and Infinity onto null; keep them apart so the signature +// below separates every pair of unequal instances. +const encodeFact = (_key: string, value: unknown) => + typeof value === 'number' && !Number.isFinite(value) ? String(value) : value; + +const contentSignature = (instance: InstanceFacts) => + JSON.stringify( + [ + instance.sopInstanceUid, + instance.seriesInstanceUid, + ...HARD_FACT_RULES.map((rule) => instance[rule]), + ...SEMANTIC_AXES.map((axis) => instance[axis.fact]), + instance.orientation, + instance.position, + instance.projectedPosition, + instance.pixelSpacing, + instance.frameReconstruction, + instance.instanceNumber, + ], + encodeFact + ); + +/** + * Total order over instances that share a SOP Instance UID comparison, which + * happens whenever two instances both lack one. + */ +const compareByContent = (left: InstanceFacts, right: InstanceFacts) => + compareText( + JSON.stringify(left.orientation), + JSON.stringify(right.orientation) + ) || + compareNumber(left.projectedPosition, right.projectedPosition) || + compareNumber(left.instanceNumber, right.instanceNumber) || + compareText(contentSignature(left), contentSignature(right)); + +// Sorting on the UID alone ties every anonymous instance, leaving the greedy +// orientation walk at the mercy of input order. +const compareWalkOrder = (left: InstanceFacts, right: InstanceFacts) => + compareBySopUid(left, right) || compareByContent(left, right); + +const readableOrientation = (value: number[] | null): value is number[] => + value !== null && + value.length === 6 && + value.every((v) => Number.isFinite(v)); + +const orientationValue = (orientation: number[]) => + orientation.map(String).join(','); + +// Ties go to the first given, so a walk ordered input decides them the same +// way whatever order the files arrived in. +const mostDeclared = (orientations: number[][]) => { + const counts = new Map(); + orientations.forEach((orientation) => { + const value = orientationValue(orientation); + counts.set(value, (counts.get(value) ?? 0) + 1); + }); + const countOf = (orientation: number[]) => + counts.get(orientationValue(orientation)) as number; + return orientations.reduce((best, orientation) => + countOf(orientation) > countOf(best) ? orientation : best + ); +}; + +/** + * How far a member's far corner sits from where the volume axes put it, in + * mm. A volume has one direction, so a slice leaning off it is resampled + * nowhere: its samples are simply shown as if it did not lean. + */ +const leanOffAxes = (axes: number[], member: InstanceFacts) => { + const { orientation } = member; + if (!readableOrientation(orientation) || member.pixelSpacing === null) + return 0; + const [rowSpacing, columnSpacing] = member.pixelSpacing; + const width = Number(member.columns) * columnSpacing; + const height = Number(member.rows) * rowSpacing; + return Math.hypot( + ...[0, 1, 2].map( + (i) => + width * (orientation[i] - axes[i]) + + height * (orientation[i + 3] - axes[i + 3]) + ) + ); +}; + +const nonparallel = (axes: number[] | null, members: InstanceFacts[]) => + axes !== null && + members.some((member) => leanOffAxes(axes, member) > IN_PLANE_TOLERANCE_MM); + +const canonicalKey = (key: CollectionKey) => + JSON.stringify([key.seriesKey, key.parts]); + +/** Last occurrence of a SOP Instance UID wins, so the newest batch survives. */ +const dedupe = (instances: InstanceFacts[]) => { + const lastIndex = new Map(); + instances.forEach((instance, index) => { + if (instance.sopInstanceUid !== null) + lastIndex.set(instance.sopInstanceUid, index); + }); + + const kept = instances.filter( + (instance, index) => + instance.sopInstanceUid === null || + lastIndex.get(instance.sopInstanceUid) === index + ); + + const droppedCounts = new Map(); + instances.forEach((instance, index) => { + const uid = instance.sopInstanceUid; + if (uid === null || lastIndex.get(uid) === index) return; + droppedCounts.set(uid, (droppedCounts.get(uid) ?? 0) + 1); + }); + + const diagnostics = new Map(); + kept.forEach((instance) => { + const uid = instance.sopInstanceUid; + const dropped = uid === null ? 0 : (droppedCounts.get(uid) ?? 0); + if (dropped > 0) + diagnostics.set( + instance, + `dropped ${dropped} earlier copy of instance ${uid}` + ); + }); + + return { kept, diagnostics }; +}; + +const hardFactSignature = (instance: InstanceFacts) => + JSON.stringify(HARD_FACT_RULES.map((rule) => instance[rule])); + +const hardFactParts = (instance: InstanceFacts) => + HARD_FACT_RULES.map( + (rule) => [rule, instance[rule]] as [string, string | null] + ); + +const hardFactLabeler = (all: InstanceFacts[]) => { + const rules = HARD_FACT_RULES.filter((rule) => + all.some((member) => member[rule] !== all[0][rule]) + ); + const names = { + rows: 'rows', + columns: 'columns', + samplesPerPixel: 'components', + numberOfFrames: 'frames', + }; + return (instance: InstanceFacts) => + rules + .map((rule) => `${names[rule]} ${instance[rule] ?? 'unknown'}`) + .join(', '); +}; + +/** + * Greedy bucketing walked in SOP Instance UID then content order, so the + * representative whose cosines become the key, and the membership the greedy + * walk produces, do not depend on input order. + */ +const bucketByOrientation = (instances: InstanceFacts[]) => { + const references: number[][] = []; + const bucketOf = new Map(); + + const walked = [...instances].sort(compareWalkOrder); + walked.forEach((instance) => { + const { orientation } = instance; + if (!readableOrientation(orientation)) { + bucketOf.set(instance, -1); + return; + } + const found = references.findIndex((reference) => + orientationsAgree(reference, orientation) + ); + bucketOf.set( + instance, + found >= 0 ? found : references.push(orientation) - 1 + ); + }); + + // One normal for the whole bucket: two members agree within the tolerance, + // so projecting each on its own cosines would spread one slice plane over + // several positions. The reference stays the key, which a collection ID is + // minted from; the axes are the ones most members declare, so a stray slice + // that happens to be walked first does not lean every other one. + const buckets = references.map((reference, index) => { + const orientation = mostDeclared( + walked + .filter((instance) => bucketOf.get(instance) === index) + .map((instance) => instance.orientation as number[]) + ); + return { + value: orientationValue(reference) as string | null, + orientation: orientation as number[] | null, + normal: sliceNormalOf(orientation) as number[] | null, + members: [] as InstanceFacts[], + }; + }); + const unreadable = { + value: null, + orientation: null, + normal: null, + members: [] as InstanceFacts[], + }; + + instances.forEach((instance) => { + const index = bucketOf.get(instance) ?? -1; + const bucket = index === -1 ? unreadable : buckets[index]; + bucket.members.push(instance); + }); + + return unreadable.members.length > 0 ? [...buckets, unreadable] : buckets; +}; + +// A repeated position breaks on the instance number, keeping the scanner's +// own sequence for the tied members. Position stays primary: the allocator +// places slot i at origin + i * spacing along the normal, so any order that +// is not monotone in position mirrors or scrambles the volume. Anonymous +// members that still tie order by content rather than by input position. +const comparePosition = + (positionOf: PositionOf) => (left: InstanceFacts, right: InstanceFacts) => + (positionOf(left) as number) - (positionOf(right) as number) || + compareNumber(left.instanceNumber, right.instanceNumber) || + compareWalkOrder(left, right); + +const compareInstanceNumber = (left: InstanceFacts, right: InstanceFacts) => + (left.instanceNumber as number) - (right.instanceNumber as number) || + compareWalkOrder(left, right); + +/** Never inherits input order silently: the order actually used is recorded. */ +const orderMembers = (members: InstanceFacts[], positionOf: PositionOf) => { + const numbered = members.every((m) => readableNumber(m.instanceNumber)); + + if (members.every((m) => readableNumber(positionOf(m)))) + return { + members: [...members].sort(comparePosition(positionOf)), + order: 'spatial' as MemberOrder, + diagnostics: [] as string[], + }; + + const positionless = (ordered: InstanceFacts[]) => + ordered + .filter((m) => !readableNumber(positionOf(m))) + .map((m) => `${label(m)} has no readable position`); + + if (numbered) { + const ordered = [...members].sort(compareInstanceNumber); + return { + members: ordered, + order: 'instance-number' as MemberOrder, + diagnostics: positionless(ordered), + }; + } + + return { + members: [...members], + order: 'input' as MemberOrder, + diagnostics: [ + ...positionless(members), + ...members + .filter((m) => !readableNumber(m.instanceNumber)) + .map((m) => `${label(m)} has no readable instance number`), + ], + }; +}; + +/** Occurrences per instance, so an input holding one object twice needs two. */ +const tally = (instances: InstanceFacts[]) => { + const counts = new Map(); + instances.forEach((instance) => + counts.set(instance, (counts.get(instance) ?? 0) + 1) + ); + return counts; +}; + +/** + * Throws when the collections do not hold every instance as many times as the + * input does, when they hold one the input never gave, or when two collections + * share a key. + */ +export function validateCollections( + instances: InstanceFacts[], + collections: DicomCollection[] +) { + const expected = tally(instances); + const placed = tally(collections.flatMap((collection) => collection.members)); + + expected.forEach((count, instance) => { + const found = placed.get(instance) ?? 0; + if (found === count) return; + if (found === 0) + throw new Error(`${label(instance)} landed in no collection`); + throw new Error( + `${label(instance)} landed in ${found} collections, expected ${count}` + ); + }); + + placed.forEach((_count, instance) => { + if (!expected.has(instance)) + throw new Error( + `${label(instance)} landed in a collection without being an input` + ); + }); + + const seen = new Set(); + collections.forEach((collection) => { + const encoded = canonicalKey(collection.key); + if (seen.has(encoded)) + throw new Error(`two collections share the key ${encoded}`); + seen.add(encoded); + }); +} + +export function planDicomCollections(input: PlanInput) { + const { kept, diagnostics: dedupeDiagnostics } = dedupe(input.instances); + const labelHardFacts = hardFactLabeler(kept); + + const multiframe = (instance: InstanceFacts) => + Number(instance.numberOfFrames) > 1; + const groups = [ + ...groupBy( + kept.filter((instance) => !multiframe(instance)), + hardFactSignature + ).values(), + ...kept.filter(multiframe).map((instance) => [instance]), + ]; + const planned = groups + .flatMap((group) => + bucketByOrientation(group).map((bucket) => ({ + group, + bucket, + positionOf: ((member) => + projectOnNormal(bucket.normal, member.position)) as PositionOf, + })) + ) + .flatMap(({ group, bucket, positionOf }) => + splitOverlappingAcquisitions(bucket.members, positionOf).map((part) => ({ + group, + bucket, + positionOf, + part, + })) + ) + .map(({ group, bucket, positionOf, part }) => { + const ordered = orderMembers(part.members, positionOf); + const reconstruction = reconstructInstances( + ordered.members, + bucket.normal + ); + const key: CollectionKey = { + seriesKey: input.seriesKey, + parts: [ + ...hardFactParts(group[0]), + [ORIENTATION_RULE, bucket.value], + ...part.parts, + ...(multiframe(group[0]) + ? [['instance', instanceKey(group[0])] as [string, string]] + : []), + ], + }; + return { + key, + members: ordered.members, + order: ordered.order, + orientation: bucket.orientation, + reconstruction, + label: + [labelHardFacts(group[0]), part.label].filter(Boolean).join(', ') || + null, + diagnostics: [ + ...ordered.members.flatMap((member) => { + const dropped = dedupeDiagnostics.get(member); + return dropped ? [dropped] : []; + }), + ...(bucket.value === null + ? ordered.members.map( + (member) => `${label(member)} has no readable orientation` + ) + : []), + ...ordered.diagnostics, + ], + warnings: [ + ...(part.repeatedPositions ? [REPEATED_POSITIONS_WARNING] : []), + ...(part.unreadablePositions && !multiframe(group[0]) + ? [UNREADABLE_POSITION_WARNING] + : []), + ...reconstructionWarnings( + reconstruction, + ordered.members.length === 1 && + !!ordered.members[0].frameReconstruction + ), + ...(nonparallel(bucket.orientation, ordered.members) + ? [NONPARALLEL_SLICES_WARNING] + : []), + ], + }; + }) + .sort((left, right) => + canonicalKey(left.key) < canonicalKey(right.key) ? -1 : 1 + ); + + // A series that plans to one instance is a whole volume: nothing was held + // out of a sibling, and one slice has no order or spacing to get wrong. + const lone = planned.length === 1 && planned[0].members.length === 1; + const collections = lone + ? planned.map((collection) => ({ + ...collection, + warnings: collection.warnings.filter( + (warning) => warning !== UNREADABLE_POSITION_WARNING + ), + })) + : planned; + + validateCollections(kept, collections); + + return { collections }; +} diff --git a/packages/dicom/core/collections/reconstructVolume.ts b/packages/dicom/core/collections/reconstructVolume.ts new file mode 100644 index 000000000..2d38813ea --- /dev/null +++ b/packages/dicom/core/collections/reconstructVolume.ts @@ -0,0 +1,220 @@ +import type { InstanceFacts } from './planDicomCollections'; +import { projectOnNormal, sliceNormalOf } from './instanceFacts'; + +/** The geometry a reconstruction judges. Nothing else about an instance. */ +export type ReconstructionMember = Pick< + InstanceFacts, + 'orientation' | 'position' | 'pixelSpacing' +> & { frameReconstruction?: Reconstruction; numberOfFrames?: string | null }; + +export type IrregularReason = + | 'unreadable-geometry' + | 'repeated-position' + | 'uneven-slice-spacing' + | 'in-plane-shift' + | 'mixed-pixel-spacing'; + +/** + * What the members can be reconstructed as. + * + * `regular` means every consecutive pair of slice planes is the same distance + * apart and the members share one in-plane grid, so member i belongs at slot + * `slots[i]` of a volume sampled at `sliceSpacing`. `irregular` means they do + * not: the members still load, placed one slot apart at the step the stack + * does take, but no lattice describes where they actually are. + * + * A slice spacing of null means there is nothing to derive one from, which one + * member alone always is. + */ +export type Reconstruction = + | { kind: 'regular'; sliceSpacing: number | null; slots: number[] } + | { + kind: 'irregular'; + reason: IrregularReason; + sliceSpacing: number | null; + slots: number[]; + }; + +/** + * How far apart two slice gaps may be and still be one lattice: a tenth of a + * millimetre (capped at a tenth of the gap), or one part in a hundred of the + * gap, whichever is larger. DICOM + * prints a position as a decimal string, so the projection of an oblique stack + * onto its normal jitters in the last digits; a genuine slab boundary or a + * missed slice is orders of magnitude larger. + */ +export const SLICE_SPACING_TOLERANCE_MM = 0.1; +export const SLICE_SPACING_RELATIVE_TOLERANCE = 0.01; + +/** How far a slice may sit from the in-plane origin of the first, in mm. */ +export const IN_PLANE_TOLERANCE_MM = 0.1; + +/** How far two in-plane sample spacings may differ and still be one grid. */ +export const PIXEL_SPACING_TOLERANCE_MM = 1e-4; + +const spacingTolerance = (gap: number) => + Math.max( + Math.min(SLICE_SPACING_TOLERANCE_MM, Math.abs(gap) * 0.1), + Math.abs(gap) * SLICE_SPACING_RELATIVE_TOLERANCE + ); + +// Lower median, so the fallback spacing of an irregular stack is one of its +// own gaps rather than an average of a gap and a hole. +const median = (values: number[]) => + [...values].sort((left, right) => left - right)[ + Math.floor((values.length - 1) / 2) + ]; + +const subtract = (left: number[], right: number[]) => + left.map((value, index) => value - right[index]); + +const scale = (vector: number[], factor: number) => + vector.map((value) => value * factor); + +const maxAbs = (values: number[]) => + values.reduce((largest, value) => Math.max(largest, Math.abs(value)), 0); + +const distance = (left: number[], right: number[]) => + Math.sqrt( + subtract(left, right).reduce((sum, value) => sum + value * value, 0) + ); + +/** + * The step a stack that is no lattice still takes: the lower median of the + * straight-line distance from each member to the next, in the order given. + * That is what ITK's series reader steps by, so a tilted gantry's slices, + * whose planes shift sideways as they advance, keep the extent they were + * scanned over. Null when a position is unreadable or the members never move. + */ +const positionStep = (members: ReconstructionMember[]) => { + const positions = members.map((member) => member.position); + if (positions.length < 2 || positions.some((position) => position === null)) + return null; + const gaps = positions + .slice(1) + .map((position, index) => + distance(position as number[], positions[index] as number[]) + ); + const step = median(gaps); + return step > 0 ? step : null; +}; + +// A member with no pixel spacing at all is unknown, not different: only two +// spacings that both read and disagree describe two grids. +const mixedPixelSpacing = (members: ReconstructionMember[]) => { + const spacings = members + .map((member) => member.pixelSpacing) + .filter((spacing): spacing is number[] => spacing !== null); + return spacings.some( + (spacing) => + maxAbs(subtract(spacing, spacings[0])) > PIXEL_SPACING_TOLERANCE_MM + ); +}; + +const irregular = ( + reason: IrregularReason, + sliceSpacing: number | null, + count: number +): Reconstruction => ({ + kind: 'irregular', + reason, + sliceSpacing, + slots: Array.from({ length: count }, (_, index) => index), +}); + +const inPlaneShifted = ( + members: ReconstructionMember[], + axis: number[], + along: number[] +) => { + const inPlaneOf = (index: number) => + subtract(members[index].position as number[], scale(axis, along[index])); + const origin = inPlaneOf(0); + return members.some( + (_member, index) => + maxAbs(subtract(inPlaneOf(index), origin)) > IN_PLANE_TOLERANCE_MM + ); +}; + +/** What stops these members from describing a volume at all, if anything. */ +const geometryFault = ( + members: ReconstructionMember[], + axis: number[] | null, + along: Array +): IrregularReason | null => { + if (along.some((position) => !Number.isFinite(position))) + return 'unreadable-geometry'; + if (mixedPixelSpacing(members)) return 'mixed-pixel-spacing'; + if (inPlaneShifted(members, axis as number[], along as number[])) + return 'in-plane-shift'; + return null; +}; + +/** The lattice the slice planes sit on, once they are known to be readable. */ +const lattice = (along: number[]): Reconstruction => { + if (along.length < 2) + return { kind: 'regular', sliceSpacing: null, slots: [0] }; + + const gaps = along.slice(1).map((position, index) => position - along[index]); + const step = median(gaps); + const count = along.length; + + if (gaps.some((gap) => gap <= 0)) + return irregular('repeated-position', step > 0 ? step : null, count); + if (gaps.some((gap) => Math.abs(gap - step) > spacingTolerance(step))) + return irregular('uneven-slice-spacing', step, count); + + // Every gap matches, so the endpoints fit the members better than any single + // printed gap does. + const sliceSpacing = (along[count - 1] - along[0]) / gaps.length; + const slots = along.map((position) => + Math.round((position - along[0]) / sliceSpacing) + ); + return slots.some((slot, index) => slot !== index) + ? irregular('uneven-slice-spacing', step, count) + : { kind: 'regular', sliceSpacing, slots }; +}; + +/** + * Whether the members sit on one sampled volume, and where each one belongs in + * it. Pure: the members are judged by their own geometry, in the order given. + * + * `normal` is the slice normal the positions are projected on. The planner + * passes the one normal its orientation bucket agreed on; without it, the + * first member's own cosines decide. + */ +export function reconstructVolume( + members: ReconstructionMember[], + normal?: number[] | null +): Reconstruction { + if ( + members.length < 2 && + !members.some((member) => Number(member.numberOfFrames) > 1) + ) + return { + kind: 'regular', + sliceSpacing: null, + slots: members.map(() => 0), + }; + + const axis = normal ?? sliceNormalOf(members[0].orientation); + const along = members.map((member) => projectOnNormal(axis, member.position)); + + const fault = geometryFault(members, axis, along); + return fault === null + ? lattice(along as number[]) + : irregular(fault, positionStep(members), members.length); +} + +/** Instance slots index source chunks even when one source contains many frames. */ +export function reconstructInstances( + members: ReconstructionMember[], + normal?: number[] | null, + supplied?: Reconstruction +): Reconstruction { + const framePlan = + members.length === 1 ? members[0].frameReconstruction : undefined; + return framePlan + ? { ...framePlan, slots: [0] } + : (supplied ?? reconstructVolume(members, normal)); +} diff --git a/packages/dicom/core/collections/splitOverlappingAcquisitions.ts b/packages/dicom/core/collections/splitOverlappingAcquisitions.ts new file mode 100644 index 000000000..63fa4a143 --- /dev/null +++ b/packages/dicom/core/collections/splitOverlappingAcquisitions.ts @@ -0,0 +1,292 @@ +import type { InstanceFacts } from './planDicomCollections'; +import { groupBy } from './groupBy'; + +export const DESCRIPTOR_AXES = [ + { rule: 'sequence', fact: 'sequenceName', counter: true }, + { rule: 'thickness', fact: 'sliceThickness', counter: true }, + { rule: 'series', fact: 'seriesNumber', counter: true }, + { rule: 'date', fact: 'seriesDate', counter: true }, +] as const; + +/** + * Facts tried, in order, as the identity of one scan within a series. An axis + * that does not split hands the members to the next; an axis that does split + * recurses into each part with the remaining axes, so a 4D multi-echo series + * separates on both. Acquisition descriptors provide a fallback when the + * specific contrast tags are absent. Stack ID is absent on purpose: bilateral + * slab series put two stacks in one sound volume. + * + * Acquisition and phase counters number passes over time. Scanners sometimes + * stamp them per slice, so they split only multi-slice groups and preserve a + * repeated single plane as a time series. Descriptors require multi-slice + * groups too, except when all images share one plane: separating those cannot + * remove a slice from a spatial stack. + */ +export const SEMANTIC_AXES = [ + { rule: 'acquisition', fact: 'acquisitionNumber', counter: true }, + { rule: 'phase', fact: 'temporalPositionIdentifier', counter: true }, + { rule: 'echo', fact: 'echoNumbers', counter: false }, + { rule: 'b-value', fact: 'diffusionBValue', counter: false }, + ...DESCRIPTOR_AXES, +] as const; + +type SemanticAxis = (typeof SEMANTIC_AXES)[number]; + +const isDescriptor = (axis: SemanticAxis) => + DESCRIPTOR_AXES.some((descriptor) => descriptor.fact === axis.fact); + +export type SemanticPart = { + // One entry per axis, in SEMANTIC_AXES order: the value the part was split + // out on, or null where the axis did not partition its members. + parts: Array<[string, string | null]>; + members: InstanceFacts[]; + // 'acquisition 2, echo 1'; null for members no axis separated. + label: string | null; + // Two members share a slice position and no axis separates them. + repeatedPositions: boolean; + // No member of this part carries a readable slice position, so nothing + // spatial was judged about it. + unreadablePositions: boolean; +}; + +// The key part that keeps the members of unreadable geometry apart from the +// judged parts of the same series. +export const GEOMETRY_RULE = 'geometry'; +export const UNREADABLE_GEOMETRY = 'unreadable'; +export const UNREADABLE_GEOMETRY_LABEL = 'position unknown'; + +/** + * Where a member sits along the slice axis. The planner passes the projection + * on its bucket's common normal; the member's own is the default. + */ +export type PositionOf = (member: InstanceFacts) => number | null; + +const ownPosition: PositionOf = (member) => member.projectedPosition; + +const countDistinctPositions = ( + members: InstanceFacts[], + positionOf: PositionOf +) => new Set(members.map(positionOf)).size; + +const hasRepeatedPositions = ( + members: InstanceFacts[], + positionOf: PositionOf +) => countDistinctPositions(members, positionOf) !== members.length; + +/** + * Whether any two groups cover overlapping stretches of the slice axis. + * Bounds are closed, so scans sharing a boundary slice count as overlapping: + * that shared position is a duplicate either way. + */ +const spanOf = (group: InstanceFacts[], positionOf: PositionOf) => + group.reduce( + (span, member) => ({ + min: Math.min(span.min, positionOf(member) as number), + max: Math.max(span.max, positionOf(member) as number), + }), + { min: Infinity, max: -Infinity } + ); + +const anySpansOverlap = (groups: InstanceFacts[][], positionOf: PositionOf) => { + const spans = groups + .map((group) => spanOf(group, positionOf)) + .sort((a, b) => a.min - b.min); + let reach = -Infinity; + return spans.some((span) => { + if (span.min <= reach) return true; + reach = Math.max(reach, span.max); + return false; + }); +}; + +/** Eligible groups in first-seen order, with all other members held apart. */ +const groupByAxis = ( + members: InstanceFacts[], + axis: SemanticAxis, + singlePlane: boolean +) => { + const independentImages = singlePlane && isDescriptor(axis); + const tagged = new Map(); + members.forEach((member) => { + const value = member[axis.fact]; + if (value === null && !independentImages) return; + const group = tagged.get(value); + if (group) group.push(member); + else tagged.set(value, [member]); + }); + // A counter stamped per slice cannot establish a separate acquisition. + // Descriptor differences on one plane distinguish images without removing + // a slice from a spatial stack. + const eligible = new Map( + [...tagged].filter( + ([, group]) => !axis.counter || independentImages || group.length > 1 + ) + ); + const remainder = members.filter((member) => { + const value = member[axis.fact]; + return !eligible.has(value); + }); + return { tagged: eligible, remainder }; +}; + +type Split = { value: string | null; members: InstanceFacts[] }; + +/** + * The first axis whose tagged groups cover overlapping stretches of the slice + * axis, with the members that carry no value for it as their own part. Scans + * that follow one another along the axis are one volume between them and stay + * merged, however their acquisition is numbered. + */ +const firstSplittingAxis = ( + members: InstanceFacts[], + axes: SemanticAxis[], + positionOf: PositionOf, + singlePlane: boolean +) => + axes + .map((axis) => ({ axis, ...groupByAxis(members, axis, singlePlane) })) + .find(({ tagged }) => { + const groups = [...tagged.values()]; + return groups.length >= 2 && anySpansOverlap(groups, positionOf); + }); + +const unsplit = ( + members: InstanceFacts[], + axes: SemanticAxis[], + repeatedPositions: boolean +): SemanticPart[] => [ + { + parts: axes.map((axis) => [axis.rule, null]), + members, + label: null, + repeatedPositions, + unreadablePositions: false, + }, +]; + +/** Members no axis can judge, held apart under a key part of their own. */ +const unreadableGeometry = ( + members: InstanceFacts[], + axes: SemanticAxis[] +): SemanticPart => ({ + parts: [ + ...axes.map((axis): [string, null] => [axis.rule, null]), + [GEOMETRY_RULE, UNREADABLE_GEOMETRY], + ], + members, + label: UNREADABLE_GEOMETRY_LABEL, + repeatedPositions: false, + unreadablePositions: true, +}); + +const labelFor = (axis: SemanticAxis, members: InstanceFacts[]) => { + const values = new Set(members.map((member) => member[axis.fact])); + const value = values.size === 1 ? [...values][0] : 'mixed'; + return `${axis.rule} ${value ?? 'unknown'}`; +}; + +const splitUnreadable = (members: InstanceFacts[], axes: SemanticAxis[]) => { + const descriptors = DESCRIPTOR_AXES.filter((axis) => axes.includes(axis)); + const groups = [ + ...groupBy(members, (member) => + JSON.stringify(descriptors.map((axis) => member[axis.fact])) + ).values(), + ]; + const differing = descriptors.filter( + (axis) => new Set(members.map((member) => member[axis.fact])).size > 1 + ); + return groups.map((group) => { + const part = unreadableGeometry(group, axes); + return { + ...part, + parts: part.parts.map(([rule, value]): [string, string | null] => { + const descriptor = descriptors.find((axis) => axis.rule === rule); + return [rule, descriptor ? group[0][descriptor.fact] : value]; + }), + label: [ + ...differing.map((axis) => labelFor(axis, group)), + part.label, + ].join(', '), + }; + }); +}; + +function splitByAxes( + members: InstanceFacts[], + axes: SemanticAxis[], + positionOf: PositionOf +): SemanticPart[] { + // Counters alone leave a repeatedly scanned plane as a time series. Contrast + // tags and descriptors can still distinguish independent images on it. + const singlePlane = countDistinctPositions(members, positionOf) === 1; + const found = firstSplittingAxis( + members, + singlePlane + ? axes.filter((axis) => !axis.counter || isDescriptor(axis)) + : axes, + positionOf, + singlePlane + ); + if (!found) + return unsplit(members, axes, hasRepeatedPositions(members, positionOf)); + + const { axis, tagged, remainder } = found; + const index = axes.indexOf(axis); + const skipped = axes.slice(0, index); + const rest = axes.slice(index + 1); + const splits: Split[] = [ + ...[...tagged].map(([value, group]) => ({ value, members: group })), + ...(remainder.length > 0 ? [{ value: null, members: remainder }] : []), + ]; + + return splits.flatMap(({ value, members: group }) => + splitByAxes(group, rest, positionOf).map((child) => ({ + ...child, + parts: [ + ...skipped.map((s): [string, null] => [s.rule, null]), + [axis.rule, value], + ...child.parts, + ], + label: [labelFor(axis, child.members), child.label] + .filter((part) => part !== null) + .join(', '), + })) + ); +} + +/** + * Separates members that hold more than one scan of the same anatomy. + * + * A single series can carry several scans of one range: overlapping + * acquisitions, DCE timepoints, Dixon echoes, or diffusion b-values. Merged, + * they interleave slices from different passes and derive a slice spacing from + * a lattice none of them sit on. The test is whether per-value groups cover + * overlapping stretches of the slice axis, decided by comparing positions + * rather than by measuring how even the spacing looks. + * + * Members whose position cannot be read are judged by nothing here, so they + * are held in a part of their own instead of suppressing the split of the + * members that can be judged. + * + * Conservative on the members it does judge: one overlapping pair separates + * every eligible group at that level. Acquisition and phase counters preserve + * repeated single planes and require groups of multiple slices. Descriptors + * retain the group-size guard only where several planes form a spatial stack. + * Members that lack the level's value and excluded singleton groups form a + * remainder instead of blocking the split. + */ +export function splitOverlappingAcquisitions( + members: InstanceFacts[], + positionOf: PositionOf = ownPosition +): SemanticPart[] { + const axes = [...SEMANTIC_AXES]; + const readable = (member: InstanceFacts) => + Number.isFinite(positionOf(member)); + const judgeable = members.filter(readable); + const unreadable = members.filter((member) => !readable(member)); + + return [ + ...(judgeable.length > 0 ? splitByAxes(judgeable, axes, positionOf) : []), + ...splitUnreadable(unreadable, axes), + ]; +} diff --git a/packages/dicom/core/instance/__tests__/instanceFixture.ts b/packages/dicom/core/instance/__tests__/instanceFixture.ts new file mode 100644 index 000000000..f09d857af --- /dev/null +++ b/packages/dicom/core/instance/__tests__/instanceFixture.ts @@ -0,0 +1,19 @@ +import type { DicomDataset } from '../../metadata/dicomDataset'; +import { fromBlob, type ByteSource } from '../../source/byteSource'; +import type { Instance } from '../readInstance'; + +const noBytes = fromBlob(new Blob([])); + +/** An instance as `readInstance` returns it, from a header built in memory. */ +export const instanceFor = ( + dataset: DicomDataset, + source: ByteSource = noBytes +): Instance => + Object.freeze({ + source, + dataset, + layout: null, + ultrasoundRegions: null, + transferSyntaxUid: null, + pixelData: null, + }); diff --git a/packages/dicom/core/instance/__tests__/readInstance.spec.ts b/packages/dicom/core/instance/__tests__/readInstance.spec.ts new file mode 100644 index 000000000..09f8e6c6f --- /dev/null +++ b/packages/dicom/core/instance/__tests__/readInstance.spec.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest'; +import { readInstance } from '../readInstance'; +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { + pixelDataStart, + syntheticSlice, + withoutPixelData, +} from '@/tests/dicomSourceFixtures'; +import { rawElement } from '@/tests/specs/syntheticDicom'; +import { trackedSource } from '../../source/__tests__/sourceFixtures'; + +const PATIENT_NAME = '00100010'; +const CHUNK = 256; + +const largeSlice = (modality = 'MR') => + syntheticSlice({ + rows: 64, + cols: 64, + modality, + patientName: 'DOE^JANE', + extraElements: [ + rawElement(0x0029, 0x0010, 'LO', new TextEncoder().encode('VENDOR')), + ], + }); + +const signal = () => new AbortController().signal; + +describe('readInstance', () => { + it('reads the public header and where Pixel Data starts', async () => { + const bytes = largeSlice(); + const { source } = trackedSource(bytes, CHUNK); + + const instance = await readInstance(source, signal()); + + expect(instance.source).toBe(source); + expect(getDatasetTag(instance.dataset, PATIENT_NAME)).toBe('DOE^JANE'); + expect( + instance.dataset.elements.some((element) => element.group === 0x0029) + ).toBe(false); + const start = pixelDataStart(bytes); + expect(instance.pixelData).toEqual({ + offset: start, + valueOffset: start + 12, + length: bytes.length - start - 12, + }); + expect(instance.transferSyntaxUid).toBe('1.2.840.10008.1.2.1'); + expect(instance.layout).toMatchObject({ preamble: true, fileMeta: true }); + expect(instance.ultrasoundRegions).toBeNull(); + expect(Object.isFrozen(instance)).toBe(true); + }); + + it('stops pulling bytes at the header and cancels the stream', async () => { + const bytes = largeSlice(); + const { source, stats } = trackedSource(bytes, CHUNK); + + await readInstance(source, signal()); + + expect(stats.cancelled).toBe(1); + expect(stats.delivered).toBeLessThanOrEqual( + pixelDataStart(bytes) + 2 * CHUNK + ); + expect(stats.delivered).toBeLessThan(bytes.length / 2); + }); + + it('reads an object without Pixel Data to its last byte', async () => { + const bytes = withoutPixelData(largeSlice()); + const { source, stats } = trackedSource(bytes, CHUNK); + + const instance = await readInstance(source, signal()); + + expect(instance.pixelData).toBeNull(); + expect(getDatasetTag(instance.dataset, PATIENT_NAME)).toBe('DOE^JANE'); + expect(stats.delivered).toBe(bytes.length); + }); + + it('returns after the Modality tag of an RT object only when asked to', async () => { + const bytes = largeSlice('RTDOSE'); + const skipped = trackedSource(bytes, CHUNK); + const complete = trackedSource(bytes, CHUNK); + + const shortcut = await readInstance(skipped.source, signal(), { + imageImportPolicy: 'skip-radiotherapy', + }); + const full = await readInstance(complete.source, signal()); + + expect(shortcut.pixelData).toBeNull(); + expect(getDatasetTag(shortcut.dataset, PATIENT_NAME)).toBeUndefined(); + expect(full.pixelData?.offset).toBe(pixelDataStart(bytes)); + expect(skipped.stats.delivered).toBeLessThan(complete.stats.delivered); + }); + + it('reads nothing once its signal has aborted', async () => { + const { source, stats } = trackedSource(largeSlice(), CHUNK); + const controller = new AbortController(); + controller.abort(new DOMException('stop', 'AbortError')); + + await expect(readInstance(source, controller.signal)).rejects.toMatchObject( + { name: 'AbortError' } + ); + expect(stats.reads).toBe(0); + }); +}); diff --git a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts new file mode 100644 index 000000000..c9ece0565 --- /dev/null +++ b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts @@ -0,0 +1,246 @@ +import { describe, expect, it } from 'vitest'; +import { readInstance } from '../readInstance'; +import { Tags } from '../../metadata/dicomTags'; +import { findElement, readDicomDataset } from '../../metadata/dicomDataset'; +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { sequenceItems } from '../../metadata/functionalGroups'; +import { + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, +} from '../../metadata/dicomLayout'; +import { fromBlob, fromUrl, readBytes } from '../../source/byteSource'; +import { trackedSource } from '../../source/__tests__/sourceFixtures'; +import { concatBytes } from '../../utils'; +import { + rawElement, + sequenceItem, + stripFileMeta, + stripPreamble, + toImplicitVr, + undefinedLengthItem, + undefinedLengthUnknown, +} from '@/tests/specs/syntheticDicom'; +import { + pixelDataStart, + readHeader, + syntheticSlice, + withoutPixelData, +} from '@/tests/dicomSourceFixtures'; + +const REGION = { physicalDeltaX: 0.0625, physicalDeltaY: 0.125 }; +const never = () => new AbortController().signal; + +describe('readInstance over byte sources', () => { + it.each([ + { name: 'defined-length item', item: sequenceItem }, + { name: 'undefined-length item', item: undefinedLengthItem }, + ])( + 'reads an undefined-length UN with $name across stream boundaries', + async ({ item }) => { + // A nonempty item catches treating the UN contents as Explicit VR. + // The value also contains delimiter-like bytes that must stay data. + const payload = new Uint8Array([ + 0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0, 0xfe, 0xff, 0x0d, 0xe0, 0, 0, 0, 0, + ]); + const content = toImplicitVr(rawElement(0x0043, 0x1030, 'OB', payload)); + const bytes = syntheticSlice({ + extraElements: [ + rawElement(0x0043, 0x0010, 'LO', new TextEncoder().encode('TEST')), + undefinedLengthUnknown(0x0043, 0x1029, item(content)), + ], + }); + + const { dataset } = await readHeader(bytes, 7); + + expect( + readDicomDataset(bytes).elements.find((el) => el.tag === '00431029') + ?.values + ).toMatchObject({ + kind: 'sequence', + items: [ + { + elements: [ + { tag: '00431030', values: { kind: 'bytes', values: [payload] } }, + ], + }, + ], + }); + expect(dataset).toEqual(readDicomDataset(syntheticSlice())); + } + ); + + it('reads a Part 10 file with its layout', async () => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN', modality: 'CT' }); + + const instance = await readHeader(bytes); + + expect(instance.dataset).toEqual(readDicomDataset(bytes)); + expect(instance.layout).toEqual({ preamble: true, fileMeta: true }); + }); + + it('reads a source without a preamble as the Part 10 file it came from', async () => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN' }); + + const instance = await readHeader(stripPreamble(bytes), 64); + + expect(instance.dataset).toEqual(readDicomDataset(bytes)); + expect(instance.layout).toEqual({ preamble: false, fileMeta: true }); + }); + + it.each([ + ['explicit', false, EXPLICIT_VR_LITTLE_ENDIAN], + ['implicit', true, IMPLICIT_VR_LITTLE_ENDIAN], + ])( + 'reads a bare %s VR data set with its transfer syntax assumed', + async (_kind, implicitVr, transferSyntaxUid) => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN', implicitVr }); + + const instance = await readHeader(stripFileMeta(bytes), 64); + + expect(instance.dataset).toEqual(readDicomDataset(bytes)); + expect(instance.layout).toEqual({ + preamble: false, + fileMeta: false, + transferSyntaxUid, + }); + } + ); + + it('parses nothing when the stream fails before the header ends', async () => { + const bytes = syntheticSlice(); + const seen: Uint8Array[] = []; + const failing = { + read: () => + new ReadableStream({ + start: (controller) => { + controller.enqueue(bytes.slice(0, 64)); + controller.error(new Error('connection reset')); + }, + }), + }; + + await expect( + readInstance(failing, never(), { + readDataset: (header) => { + seen.push(header); + return { elements: [], specificCharacterSet: null }; + }, + }) + ).rejects.toThrow('connection reset'); + expect(seen).toEqual([]); + }); + + it('hands the dataset reader the header bytes, once', async () => { + const bytes = syntheticSlice(); + const seen: Uint8Array[] = []; + + await readInstance(trackedSource(bytes).source, never(), { + readDataset: (header) => { + seen.push(header); + return { elements: [], specificCharacterSet: null }; + }, + }); + + expect(seen).toEqual([bytes.slice(0, pixelDataStart(bytes))]); + }); + + it('takes tags and ultrasound regions from one read', async () => { + const bytes = syntheticSlice({ modality: 'US', ultrasoundRegion: REGION }); + const { source, stats } = trackedSource(bytes); + + const instance = await readInstance(source, never()); + + expect(instance.dataset).toEqual(readDicomDataset(bytes)); + expect(instance.ultrasoundRegions?.regionCount).toBe(1); + expect(instance.ultrasoundRegions?.region?.physicalDeltaX).toBeCloseTo( + REGION.physicalDeltaX + ); + expect(instance.ultrasoundRegions?.region?.physicalDeltaY).toBeCloseTo( + REGION.physicalDeltaY + ); + expect(stats.reads).toBe(1); + }); + + it('reports no ultrasound regions for a non-ultrasound modality', async () => { + const bytes = syntheticSlice({ modality: 'MR', ultrasoundRegion: REGION }); + + expect((await readHeader(bytes)).ultrasoundRegions).toBeNull(); + }); + + it('reads every tag of an object that has no Pixel Data', async () => { + const bytes = withoutPixelData(syntheticSlice({ modality: 'SR' })); + + const { dataset } = await readHeader(bytes); + + expect(dataset).toEqual(readDicomDataset(bytes)); + expect(dataset.elements.length).toBeGreaterThan(1); + }); + + it('reads a radiotherapy object without Pixel Data no further than its modality', async () => { + const bytes = withoutPixelData(syntheticSlice({ modality: 'RTSTRUCT' })); + const { source, stats } = trackedSource(bytes, 32); + + const { dataset } = await readInstance(source, never(), { + imageImportPolicy: 'skip-radiotherapy', + }); + + expect(getDatasetTag(dataset, Tags.Modality)?.trim()).toBe('RTSTRUCT'); + expect(stats.delivered).toBeLessThan(bytes.length); + }); + + it('rejects a byte source that is not DICOM', async () => { + await expect(readHeader(new Uint8Array(512))).rejects.toThrow(); + }); + + it('drops private payloads, nested ones too, while the source keeps every byte', async () => { + const privateElement = rawElement( + 0x0029, + 0x1010, + 'OB', + new Uint8Array(100_000).fill(0x41) + ); + const bytes = syntheticSlice({ + extraElements: [ + privateElement, + rawElement( + 0x0008, + 0x1140, + 'SQ', + sequenceItem( + concatBytes([ + rawElement(8, 0x1155, 'UI', new TextEncoder().encode('1.2.3\0')), + privateElement, + ]) + ) + ), + ], + }); + const source = fromBlob(new Blob([bytes as BlobPart])); + + const { dataset } = await readInstance(source, never()); + + expect(findElement(readDicomDataset(bytes), '00291010')).toBeDefined(); + expect(findElement(dataset, '00291010')).toBeUndefined(); + const reference = sequenceItems(dataset, '00081140')[0]; + expect(getDatasetTag(reference, '00081155')).toBe('1.2.3'); + expect(findElement(reference, '00291010')).toBeUndefined(); + expect(await readBytes(source, never())).toEqual(bytes); + }); + + it('reads only the header from an HTTP response', async () => { + const bytes = syntheticSlice({ + patientName: 'DOE^JOHN', + rows: 64, + cols: 64, + }); + const served = trackedSource(bytes, 256); + const source = fromUrl('https://example.test/slice.dcm', { + fetch: async () => new Response(served.source.read(never())), + }); + + const { dataset } = await readInstance(source, never()); + + expect(getDatasetTag(dataset, '00100010')).toBe('DOE^JOHN'); + expect(served.stats.delivered).toBeLessThan(bytes.length / 2); + }); +}); diff --git a/packages/dicom/core/instance/readInstance.ts b/packages/dicom/core/instance/readInstance.ts new file mode 100644 index 000000000..617aae6f1 --- /dev/null +++ b/packages/dicom/core/instance/readInstance.ts @@ -0,0 +1,67 @@ +import type { ByteSource } from '../source/byteSource'; +import { + readDicomDataset, + withoutPrivateElements, + type DicomDataset, +} from '../metadata/dicomDataset'; +import type { DicomLayout } from '../metadata/dicomLayout'; +import { getDatasetModality } from '../metadata/datasetAccess'; +import { + readDicomHeader, + type ImageImportPolicy, + type PixelDataElement, +} from '../streaming/dicom/readDicomHeader'; +import { + readUltrasoundRegions, + type UltrasoundRegions, +} from '../streaming/dicom/ultrasoundRegion'; +import type { Awaitable } from '../utils'; + +/** + * One parsed header and where its bytes live. The dataset omits private + * elements, including those nested in public sequences; the source still + * holds every original byte. Identity matters: registries and volumes + * recognize an instance by this object. + */ +export type Instance = Readonly<{ + source: ByteSource; + dataset: DicomDataset; + /** How the bytes opened: with or without the Part 10 preamble and file meta. */ + layout: DicomLayout | null; + ultrasoundRegions: UltrasoundRegions | null; + /** As the file meta names it, or as a bare data set's first element suggests. */ + transferSyntaxUid: string | null; + /** Null when the header names no Pixel Data or its element head is cut short. */ + pixelData: PixelDataElement | null; +}>; + +export type ReadInstanceOptions = { + readDataset?: (bytes: Uint8Array) => Awaitable; + imageImportPolicy?: ImageImportPolicy; +}; + +/** Reads the header only, cancelling the stream where Pixel Data begins. */ +export async function readInstance( + source: ByteSource, + signal: AbortSignal, + options: ReadInstanceOptions = {} +): Promise { + signal.throwIfAborted(); + const { header, layout, transferSyntaxUid, pixelData } = + await readDicomHeader(source.read(signal), options.imageImportPolicy); + signal.throwIfAborted(); + const parsed = await (options.readDataset ?? readDicomDataset)(header); + signal.throwIfAborted(); + const dataset = withoutPrivateElements(parsed); + return Object.freeze({ + source, + dataset, + layout, + ultrasoundRegions: + getDatasetModality(dataset) === 'US' + ? readUltrasoundRegions(dataset) + : null, + transferSyntaxUid, + pixelData, + }); +} diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts new file mode 100644 index 000000000..701034e26 --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -0,0 +1,331 @@ +import { readDicomDataset, findElement } from '../dicomDataset'; +import { getDatasetTag } from '../datasetAccess'; +import { getFrameTag } from '../functionalGroups'; +import { createDicomParser } from '../../streaming/dicom/dicomParser'; +import { deflateRawSync } from 'node:zlib'; +import { describe, expect, it } from 'vitest'; +import { parseDicomElements } from '../dcmjsParser'; +import { PART_10_HEADER_LENGTH, PREAMBLE_LENGTH } from '../dicomLayout'; +import { concatBytes } from '../../utils'; +import { buildSlice } from '@/src/io/__tests__/readDicomTagsFixtures'; +import { pixelDataStart, readHeader } from '@/tests/dicomSourceFixtures'; +import { + rawElement, + sequenceItem, + toImplicitVr, + stripFileMeta, + stripPreamble, + undefinedLengthItem, + undefinedLengthSequence, +} from '@/tests/specs/syntheticDicom'; + +// (0002,0000) UL occupies twelve bytes, including its value. +const GROUP_LENGTH_ELEMENT_LENGTH = 12; +const withoutGroupLength = (file: Uint8Array) => + concatBytes([ + file.subarray(0, PART_10_HEADER_LENGTH), + file.subarray(PART_10_HEADER_LENGTH + GROUP_LENGTH_ELEMENT_LENGTH), + ]); + +// An empty fixed-Huffman block followed by a stored block and a final empty +// block is valid raw DEFLATE. Its first two bytes look like DICOM group 2. +const deflateWithMetaGroupPrefix = (data: Uint8Array) => { + const header = new Uint8Array([2, 0, 0, 0, 0, 0]); + const view = new DataView(header.buffer); + view.setUint16(2, data.length, true); + view.setUint16(4, 0xffff ^ data.length, true); + return concatBytes([header, data, new Uint8Array([3, 0])]); +}; + +describe('file meta information', () => { + it.each([ + { vr: 'explicit', implicitVr: false, preamble: true }, + { vr: 'implicit', implicitVr: true, preamble: true }, + { vr: 'explicit', implicitVr: false, preamble: false }, + { vr: 'implicit', implicitVr: true, preamble: false }, + ])( + 'reads $vr VR without group length (preamble: $preamble)', + ({ implicitVr, preamble }) => { + const file = buildSlice({ implicitVr }); + file.fill(0x41, 0, PREAMBLE_LENGTH); + const input = withoutGroupLength(file); + + expect( + parseDicomElements(preamble ? input : stripPreamble(input)) + ).toEqual(parseDicomElements(file)); + } + ); + + it.each([ + { groupLength: true, prefix: 'normal', deflate: deflateRawSync }, + { groupLength: false, prefix: 'normal', deflate: deflateRawSync }, + { + groupLength: true, + prefix: 'group 2', + deflate: deflateWithMetaGroupPrefix, + }, + ])( + 'reads deflated data after nonzero preamble bytes (group length: $groupLength, prefix: $prefix)', + ({ groupLength, deflate }) => { + const file = buildSlice(); + file.fill(0x41, 0, PREAMBLE_LENGTH); + const encode = (text: string) => new TextEncoder().encode(text); + const meta = concatBytes([ + rawElement(0x0002, 0x0010, 'UI', encode('1.2.840.10008.1.2.1.99')), + // The transfer syntax need not be the last file-meta element. + rawElement(0x0002, 0x0013, 'SH', encode('VOLVIEW ')), + ]); + const length = new Uint8Array(4); + new DataView(length.buffer).setUint32(0, meta.length, true); + const input = concatBytes([ + file.subarray(0, PART_10_HEADER_LENGTH), + ...(groupLength ? [rawElement(0x0002, 0x0000, 'UL', length)] : []), + meta, + deflate(stripFileMeta(file)), + ]); + + expect(parseDicomElements(input)).toEqual(parseDicomElements(file)); + } + ); + + it('still rejects file meta information without a transfer syntax', () => { + const file = buildSlice(); + const input = concatBytes([ + file.subarray(0, PART_10_HEADER_LENGTH), + rawElement(0x0002, 0x0000, 'UL', new Uint8Array(4)), + stripFileMeta(file), + ]); + + expect(() => parseDicomElements(input)).toThrow( + 'the transfer syntax is missing' + ); + }); +}); + +describe('lenient headers with standards-defined values', () => { + const encode = (text: string) => new TextEncoder().encode(text); + it.each([false, true])( + 'ignores an undersized meta group length (implicit: %s)', + (implicitVr) => { + const original = buildSlice({ implicitVr }); + const input = original.slice(); + new DataView(input.buffer).setUint32(PART_10_HEADER_LENGTH + 8, 0, true); + expect(parseDicomElements(input)).toEqual(parseDicomElements(original)); + } + ); + + it('reads a defined-length SQ containing a redundant sequence delimiter', async () => { + const value = concatBytes([ + sequenceItem(rawElement(0x0008, 0x1155, 'UI', encode('1.2.3\0'))), + new Uint8Array([0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0]), + ]); + const bytes = buildSlice({ + extraElements: [rawElement(0x0008, 0x1140, 'SQ', value)], + }); + const instance = await readHeader(bytes); + expect(getDatasetTag(instance.dataset, '00280010')).toBe('4'); + }); + + it('keeps a prematurely delimited SQ inside its declared boundary', async () => { + const sequence = rawElement( + 0x0008, + 0x1140, + 'SQ', + concatBytes([ + new Uint8Array([0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0]), + rawElement(0x7fe0, 0x0010, 'OW', new Uint8Array(16)), + ]) + ); + const trailing = rawElement(0x4008, 0x0103, 'LO', encode('AFTER ')); + const bytes = buildSlice({ extraElements: [sequence, trailing] }); + const expectedPixelStart = + pixelDataStart(buildSlice()) + sequence.length + trailing.length; + const parse = createDicomParser({ + stopAtElement: (group, element) => group === 0x7fe0 && element === 0x0010, + }); + expect(parse(bytes)).toMatchObject({ + done: true, + value: { position: expectedPixelStart }, + }); + + const instance = await readHeader(bytes, 7); + expect(getDatasetTag(instance.dataset, '40080103')).toBe('AFTER '); + expect(instance.dataset).toEqual(readDicomDataset(bytes)); + }); + + it('rejects a sequence whose declared boundary exceeds the file', async () => { + const sequence = rawElement( + 0x0008, + 0x1140, + 'SQ', + concatBytes([ + new Uint8Array([0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0]), + new Uint8Array(16), + ]) + ); + const base = buildSlice(); + const bytes = concatBytes([ + base.subarray(0, pixelDataStart(base)), + sequence.subarray(0, sequence.length - 2), + ]); + expect(() => readDicomDataset(bytes)).toThrow('available dataset bytes'); + await expect(readHeader(bytes, 7)).rejects.toThrow( + 'available dataset bytes' + ); + }); + + it('does not recover a nested sequence past its enclosing item', async () => { + const inner = rawElement( + 0x0008, + 0x1140, + 'SQ', + concatBytes([ + new Uint8Array([0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0]), + new Uint8Array(16), + ]) + ); + const bytes = buildSlice({ + extraElements: [ + rawElement(0x0040, 0x0275, 'SQ', sequenceItem(inner.subarray(0, 20))), + rawElement(0x0043, 0x1030, 'LO', encode('AFTER ')), + ], + }); + const dataset = readDicomDataset(bytes); + expect(findElement(dataset, '00400275')?.values.kind).toBe('unread'); + expect(getDatasetTag(dataset, '00431030')).toBe('AFTER '); + await expect(readHeader(bytes, 7)).rejects.toThrow( + 'enclosing sequence or item' + ); + }); + + it('decodes a known defined-length UN using the dataset character set', () => { + const dataset = readDicomDataset( + concatBytes([ + rawElement(0x0008, 0x0005, 'CS', encode('ISO_IR 192')), + rawElement(0x0010, 0x0010, 'UN', encode('M\u00dcLLER ')), + ]) + ); + expect(getDatasetTag(dataset, '00100010')?.trim()).toBe('M\u00dcLLER'); + }); + + it('reads functional groups stored as defined-length UN with implicit items', () => { + const spacing = rawElement( + 0x0028, + 0x9110, + 'SQ', + sequenceItem(rawElement(0x0028, 0x0030, 'DS', encode('0.5\\0.75'))) + ); + const dataset = readDicomDataset( + concatBytes([ + rawElement(0x0008, 0x0060, 'CS', encode('CT')), + rawElement(0x5200, 0x9229, 'UN', sequenceItem(toImplicitVr(spacing))), + ]) + ); + expect(getFrameTag(dataset, '00280030')).toBe('0.5\\0.75'); + }); + + it('starts undeclared escape runs in the first declared repertoire', () => { + const dataset = readDicomDataset( + buildSlice({ + specificCharacterSet: 'ISO 2022 IR 100\\ISO 2022 IR 126', + patientNameBytes: new Uint8Array([0x52, 0xe9, 0x6d, 0x79]), + }) + ); + expect(getDatasetTag(dataset, '00100010')).toBe('R\u00e9my'); + }); + + it('preserves binary values in sequence items', () => { + const bytes = new Uint8Array([1, 2, 3, 4]); + const dataset = readDicomDataset( + buildSlice({ + extraElements: [ + rawElement( + 0x0008, + 0x1140, + 'SQ', + sequenceItem(rawElement(0x0029, 0x1010, 'OB', bytes)) + ), + ], + }) + ); + const sequence = findElement(dataset, '00081140')!.values; + if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); + expect(findElement(sequence.items[0], '00291010')!.values).toEqual({ + kind: 'bytes', + values: [bytes], + }); + }); + + it.each([false, true])( + 'reads ultrasound calibration from the structured header (implicit: %s)', + async (implicitVr) => { + const bytes = buildSlice({ + implicitVr, + modality: 'US', + ultrasoundRegion: { physicalDeltaX: 0.05, physicalDeltaY: 0.1 }, + }); + const instance = await readHeader(bytes); + expect(instance.ultrasoundRegions).toMatchObject({ + regionCount: 1, + region: { physicalDeltaX: 0.05, physicalDeltaY: 0.1 }, + }); + } + ); +}); + +it.each([sequenceItem, undefinedLengthItem])( + 'reads an implicit private undefined-length sequence with %s', + async (item) => { + const encode = (text: string) => new TextEncoder().encode(text); + const content = toImplicitVr( + rawElement(0x0010, 0x0010, 'PN', encode('DOE^JANE')) + ); + const explicit = undefinedLengthSequence(0x0043, 0x1029, item(content)); + const implicit = concatBytes([ + explicit.subarray(0, 4), + explicit.subarray(8), + ]); + const base = buildSlice({ implicitVr: true }); + const pixelStart = pixelDataStart(base); + const bytes = concatBytes([ + base.subarray(0, pixelStart), + implicit, + base.subarray(pixelStart), + ]); + const dataset = readDicomDataset(bytes); + const sequence = findElement(dataset, '00431029')!.values; + expect(findElement(dataset, '00431029')!.bytes).toBeUndefined(); + if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); + expect(getDatasetTag(sequence.items[0], '00100010')).toBe('DOE^JANE'); + const instance = await readHeader(bytes, 7); + expect(instance.dataset).toEqual(readDicomDataset(base)); + } +); + +it('decodes a known UN nested inside an explicit sequence with inherited UTF-8', () => { + const encode = (text: string) => new TextEncoder().encode(text); + const dataset = readDicomDataset( + concatBytes([ + rawElement(0x0008, 0x0005, 'CS', encode('ISO_IR 192')), + rawElement( + 0x0008, + 0x1140, + 'SQ', + sequenceItem(rawElement(0x0010, 0x0010, 'UN', encode('M\u00dcLLER '))) + ), + ]) + ); + const sequence = findElement(dataset, '00081140')!.values; + if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); + expect(getDatasetTag(sequence.items[0], '00100010')?.trim()).toBe( + 'M\u00dcLLER' + ); +}); + +it('stops before a known UN Pixel Data value, even when only its header is present', () => { + const input = concatBytes([ + rawElement(0x0008, 0x0060, 'CS', new TextEncoder().encode('CT')), + rawElement(0x7fe0, 0x0010, 'UN', new Uint8Array(16)).subarray(0, 12), + ]); + expect(parseDicomElements(input)).toHaveLength(1); +}); diff --git a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts new file mode 100644 index 000000000..4d4436b4b --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts @@ -0,0 +1,356 @@ +import { describe, expect, it } from 'vitest'; +import { DicomDataset, findElement, readDicomDataset } from '../dicomDataset'; +import { + rawElement, + sequenceItem, + undefinedLengthItem, + undefinedLengthSequence, +} from '@/tests/specs/syntheticDicom'; +import { + buildSlice, + JAPANESE_NAME, + JAPANESE_NAME_BYTES, + MIXED_VR_ELEMENTS, + UTF8_NAME, + UTF8_NAME_BYTES, +} from '@/src/io/__tests__/readDicomTagsFixtures'; + +const PATIENT_NAME = '00100010'; +const PIXEL_SPACING = '00280030'; +const IMAGE_POSITION_PATIENT = '00200032'; +const SPECIFIC_CHARACTER_SET = '00080005'; +const ICC_PROFILE = '00282000'; +const FRAME_DIMENSION_POINTER = '0028000A'; +const SIEMENS_CSA_DATA = '00291010'; +const GE_PRIVATE_TAG = '00091001'; +const ULTRASOUND_REGIONS = '00186011'; +const PHYSICAL_DELTA_X = '0018602C'; +const REQUEST_ATTRIBUTES = '00400275'; +const REFERENCED_STUDY = '00400008'; +const CODE_MEANING = '00080104'; +const SCHEDULED_PROCEDURE_STEP_ID = '00400009'; +const CURRENT_PATIENT_LOCATION = '00380300'; +const PERFORMING_PHYSICIAN_NAME = '00081050'; +const STUDY_COMMENTS = '00324000'; + +const ascii = (text: string) => new TextEncoder().encode(text); + +const concat = (...parts: Uint8Array[]) => { + const out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0)); + parts.reduce((offset, part) => { + out.set(part, offset); + return offset + part.length; + }, 0); + return out; +}; + +const item = sequenceItem; + +const sequence = (group: number, element: number, items: Uint8Array) => + rawElement(group, element, 'SQ', items); + +// (0040,0275) holding one item that itself holds a sequence, which is the +// shape an enhanced object's functional groups take. +const NESTED_SEQUENCE = sequence( + 0x0040, + 0x0275, + item( + concat( + sequence( + 0x0040, + 0x0008, + item(rawElement(0x0008, 0x0104, 'LO', ascii('MEANING '))) + ), + rawElement(0x0040, 0x0009, 'SH', ascii('SPS1 ')) + ) + ) +); + +// A Japanese data set names the default repertoire and the extension its +// ideographic runs escape into, which is the shape real studies write. +const JAPANESE_CHARACTER_SET = 'ISO 2022 IR 6\\ISO 2022 IR 87'; + +// A code meaning whose UTF-8 bytes no single byte character set survives. +const UTF8_ITEM_TEXT = '\u738b '; + +const valuesOf = (dataset: DicomDataset, tag: string) => + findElement(dataset, tag)?.values; + +describe('readDicomDataset', () => { + it('keeps the tag, VR and value multiplicity of every element', () => { + const dataset = readDicomDataset( + buildSlice({ pixelSpacing: [0.5, 0.75], imagePositionPatient: [0, 0, 0] }) + ); + + expect(findElement(dataset, PIXEL_SPACING)).toMatchObject({ + tag: PIXEL_SPACING, + group: 0x0028, + element: 0x0030, + vr: 'DS', + }); + expect(valuesOf(dataset, PIXEL_SPACING)).toEqual({ + kind: 'decimal', + values: [0.5, 0.75], + text: ['0.5', '0.75'], + }); + expect(valuesOf(dataset, IMAGE_POSITION_PATIENT)).toEqual({ + kind: 'decimal', + values: [0, 0, 0], + text: ['0', '0', '0 '], + }); + }); + + it('reads a DS value that is not a number as null, not as zero', () => { + const dataset = readDicomDataset( + buildSlice({ + extraElements: [rawElement(0x0040, 0x9224, 'DS', ascii('1\\\\3'))], + }) + ); + + expect(valuesOf(dataset, '00409224')).toEqual({ + kind: 'decimal', + values: [1, null, 3], + text: ['1', '', '3'], + }); + }); + + it('descends into a sequence and into the sequence inside it', () => { + const dataset = readDicomDataset( + buildSlice({ extraElements: [NESTED_SEQUENCE] }) + ); + const outer = valuesOf(dataset, REQUEST_ATTRIBUTES); + if (outer?.kind !== 'sequence') throw new Error('not a sequence'); + const inner = valuesOf(outer.items[0], REFERENCED_STUDY); + if (inner?.kind !== 'sequence') throw new Error('not a sequence'); + + expect(outer.items).toHaveLength(1); + expect(valuesOf(outer.items[0], SCHEDULED_PROCEDURE_STEP_ID)).toEqual({ + kind: 'text', + values: ['SPS1 '], + }); + expect(inner.items).toHaveLength(1); + expect(valuesOf(inner.items[0], CODE_MEANING)).toEqual({ + kind: 'text', + values: ['MEANING '], + }); + }); + + it.each([ + ['inherits the enclosing', []], + [ + 'declares its own', + [rawElement(0x0008, 0x0005, 'CS', ascii('ISO_IR 192'))], + ], + ])('decodes an item that %s character set once', (_, localCharacterSet) => { + const dataset = readDicomDataset( + buildSlice({ + specificCharacterSet: 'ISO_IR 192', + extraElements: [ + sequence( + 0x0040, + 0x0275, + item( + concat( + ...localCharacterSet, + rawElement(0x0008, 0x0104, 'LO', ascii(UTF8_ITEM_TEXT)) + ) + ) + ), + ], + }) + ); + const values = valuesOf(dataset, REQUEST_ATTRIBUTES); + if (values?.kind !== 'sequence') throw new Error('not a sequence'); + + expect(valuesOf(values.items[0], CODE_MEANING)).toEqual({ + kind: 'text', + values: [UTF8_ITEM_TEXT], + }); + }); + + it.each([ + [ + 'a defined length', + (content: Uint8Array) => sequence(0x0040, 0x0275, item(content)), + ], + [ + 'an undefined length', + (content: Uint8Array) => + undefinedLengthSequence(0x0040, 0x0275, undefinedLengthItem(content)), + ], + ])( + 'decodes an item of %s sequence that declares a character set extension', + (_, build) => { + const dataset = readDicomDataset( + buildSlice({ + specificCharacterSet: JAPANESE_CHARACTER_SET, + extraElements: [ + build( + concat( + rawElement(0x0008, 0x0005, 'CS', ascii(JAPANESE_CHARACTER_SET)), + rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES) + ) + ), + ], + }) + ); + const values = valuesOf(dataset, REQUEST_ATTRIBUTES); + if (values?.kind !== 'sequence') throw new Error('not a sequence'); + + expect(values.items[0].specificCharacterSet).toEqual([ + 'ISO 2022 IR 6', + 'ISO 2022 IR 87', + ]); + expect(valuesOf(values.items[0], PATIENT_NAME)).toEqual({ + kind: 'text', + values: [JAPANESE_NAME], + }); + } + ); + + it.each([ + ['explicit', false], + ['implicit', true], + ])( + 'reads the elements of an %s VR ultrasound region item', + (_, implicitVr) => { + const dataset = readDicomDataset( + buildSlice({ + implicitVr, + ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, + }) + ); + const values = valuesOf(dataset, ULTRASOUND_REGIONS); + if (values?.kind !== 'sequence') throw new Error('not a sequence'); + + expect(values.items[0].elements.map(({ tag }) => tag)).toEqual([ + '00186024', + '00186026', + '0018602C', + '0018602E', + ]); + expect(valuesOf(values.items[0], PHYSICAL_DELTA_X)).toEqual({ + kind: 'number', + values: [0.1], + }); + } + ); + + it('keeps the bytes of a sequence whose items it cannot read', () => { + // An item that claims more bytes than the sequence holds. + const truncatedItem = new Uint8Array([ + 0xfe, 0xff, 0x00, 0xe0, 0x40, 0x00, 0x00, 0x00, 0x18, 0x00, 0x24, 0x60, + ]); + const dataset = readDicomDataset( + buildSlice({ + extraElements: [rawElement(0x0018, 0x6011, 'SQ', truncatedItem)], + }) + ); + const values = valuesOf(dataset, ULTRASOUND_REGIONS); + if (values?.kind !== 'unread') throw new Error('unexpectedly read'); + + expect(values.bytes).toEqual(truncatedItem); + expect(values.reason.length).toBeGreaterThan(0); + }); + + it('keeps a private element and the bytes of its value', () => { + const dataset = readDicomDataset( + buildSlice({ extraElements: MIXED_VR_ELEMENTS }) + ); + + expect(findElement(dataset, SIEMENS_CSA_DATA)?.bytes).toEqual( + new Uint8Array(6).fill(0x41) + ); + expect(findElement(dataset, GE_PRIVATE_TAG)?.bytes).toEqual( + ascii('GEPRIV ') + ); + expect(findElement(dataset, GE_PRIVATE_TAG)?.vr).toBe('SH'); + }); + + it('leaves a public element of a known VR without a byte copy', () => { + const dataset = readDicomDataset(buildSlice()); + + expect(findElement(dataset, PATIENT_NAME)?.bytes).toBeUndefined(); + }); + + it('reads a buffer VR as bytes and an AT as referenced tags', () => { + const dataset = readDicomDataset( + buildSlice({ extraElements: MIXED_VR_ELEMENTS }) + ); + + expect(valuesOf(dataset, ICC_PROFILE)).toEqual({ + kind: 'bytes', + values: [new Uint8Array(8).fill(0x7f)], + }); + expect(valuesOf(dataset, FRAME_DIMENSION_POINTER)).toEqual({ + kind: 'attributeTag', + values: [ + { group: 0x0018, element: 0x1063 }, + { group: 0x0028, element: 0x00ff }, + ], + }); + }); + + it('applies the declared character set to the VRs it reaches', () => { + const dataset = readDicomDataset( + buildSlice({ + specificCharacterSet: 'ISO_IR 192', + patientNameBytes: UTF8_NAME_BYTES, + }) + ); + + expect(dataset.specificCharacterSet).toEqual(['ISO_IR 192']); + expect(valuesOf(dataset, PATIENT_NAME)).toEqual({ + kind: 'text', + values: [UTF8_NAME], + }); + }); + + it.each([ + ['LO', 0x0038, 0x0300, CURRENT_PATIENT_LOCATION], + ['PN', 0x0008, 0x1050, PERFORMING_PHYSICIAN_NAME], + ])( + 'separates %s values on a delimiter, not on a multibyte character', + (vr, group, element, tag) => { + const dataset = readDicomDataset( + buildSlice({ + specificCharacterSet: 'GB18030', + extraElements: [ + rawElement( + group, + element, + vr, + new Uint8Array([0x81, 0x5c, 0x5c, 0x81, 0x40]) + ), + ], + }) + ); + + expect(valuesOf(dataset, tag)).toEqual({ + kind: 'text', + values: ['\u4e57', '\u4e02 '], + }); + } + ); + + it('keeps a backslash inside a single valued text VR as a character', () => { + const dataset = readDicomDataset( + buildSlice({ + extraElements: [rawElement(0x0032, 0x4000, 'LT', ascii('C:\\DICOM'))], + }) + ); + + expect(valuesOf(dataset, STUDY_COMMENTS)).toEqual({ + kind: 'text', + values: ['C:\\DICOM'], + }); + }); + + it('reports a missing attribute as missing rather than as a default', () => { + const dataset = readDicomDataset(buildSlice()); + + expect(dataset.specificCharacterSet).toBeNull(); + expect(findElement(dataset, SPECIFIC_CHARACTER_SET)).toBeUndefined(); + expect(findElement(dataset, ICC_PROFILE)).toBeUndefined(); + }); +}); diff --git a/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts b/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts new file mode 100644 index 000000000..d56e742d4 --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; +import { + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, + PART_10_HEADER_LENGTH, + sniffDicomLayout, +} from '../dicomLayout'; +import { stripFileMeta, stripPreamble } from '@/tests/specs/syntheticDicom'; +import { buildSlice } from '@/src/io/__tests__/readDicomTagsFixtures'; + +const head = (bytes: Uint8Array) => bytes.subarray(0, PART_10_HEADER_LENGTH); + +describe('sniffDicomLayout', () => { + it('reads a Part 10 file as preamble and file meta information', () => { + expect(sniffDicomLayout(head(buildSlice()))).toEqual({ + preamble: true, + fileMeta: true, + }); + }); + + it('reads file meta information at the first byte when the preamble is missing', () => { + expect(sniffDicomLayout(head(stripPreamble(buildSlice())))).toEqual({ + preamble: false, + fileMeta: true, + }); + }); + + it('assumes explicit VR little endian for a bare data set that spells VRs', () => { + expect(sniffDicomLayout(head(stripFileMeta(buildSlice())))).toEqual({ + preamble: false, + fileMeta: false, + transferSyntaxUid: EXPLICIT_VR_LITTLE_ENDIAN, + }); + }); + + it('assumes implicit VR little endian for a bare data set that does not', () => { + expect( + sniffDicomLayout(head(stripFileMeta(buildSlice({ implicitVr: true })))) + ).toEqual({ + preamble: false, + fileMeta: false, + transferSyntaxUid: IMPLICIT_VR_LITTLE_ENDIAN, + }); + }); + + it('judges a first element from fewer bytes than a preamble takes', () => { + expect( + sniffDicomLayout(stripFileMeta(buildSlice()).subarray(0, 8)) + ).toMatchObject({ fileMeta: false }); + }); + + it.each([ + ['all zeros', new Uint8Array(512)], + [ + 'a first element outside group 0008', + new Uint8Array([0x10, 0x00, 0x10, 0x00, 0x50, 0x4e, 0, 0]), + ], + ['letters all the way down', new Uint8Array(256).fill(0x41)], + ['too few bytes for an element', new Uint8Array([0x08, 0x00, 0x16])], + ])('rejects %s', (_case, bytes) => { + expect(() => sniffDicomLayout(bytes)).toThrow(/Not DICOM/); + }); +}); diff --git a/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts b/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts new file mode 100644 index 000000000..1177c24b5 --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest'; +import { readDicomDataset } from '../dicomDataset'; +import { createMetadataReader } from '../../runtime/metadataReader'; +const readDicomDatasetOffThread = createMetadataReader().read; +import { buildSlice } from '@/src/io/__tests__/readDicomTagsFixtures'; + +// The test DOM has no Worker, so this covers the in-place path only; the +// worker path is the same reader behind a message. +describe('readDicomDatasetOffThread', () => { + it('reads what the reader reads', async () => { + const bytes = buildSlice({ patientName: 'DOE^JOHN' }); + + expect(await readDicomDatasetOffThread(bytes)).toEqual( + readDicomDataset(bytes) + ); + }); + + it('reads a view that does not own its buffer', async () => { + const whole = buildSlice(); + const padded = new Uint8Array(whole.length + 3); + padded.set(whole, 3); + + expect(await readDicomDatasetOffThread(padded.subarray(3))).toEqual( + readDicomDataset(whole) + ); + }); + + it('rejects what the reader rejects', async () => { + await expect( + readDicomDatasetOffThread(new Uint8Array(256).fill(0x41)) + ).rejects.toThrow(/Not DICOM/); + }); +}); + +class MetadataWorker extends EventTarget { + terminated = false; + postMessage() {} + terminate() { + this.terminated = true; + } +} + +describe('metadata worker ownership', () => { + it('settles worker failure, allows retry, and terminates pending work on disposal', async () => { + const workers: MetadataWorker[] = []; + const reader = createMetadataReader({ + metadataWorkerFactory: () => { + const worker = new MetadataWorker(); + workers.push(worker); + return worker as unknown as Worker; + }, + }); + const first = reader.read(buildSlice()); + const failure = expect(first).rejects.toThrow('worker failed'); + workers[0].dispatchEvent(new Event('error')); + await failure; + expect(workers[0].terminated).toBe(true); + const retry = reader.read(buildSlice()); + const stopped = expect(retry).rejects.toMatchObject({ name: 'AbortError' }); + reader.dispose(); + await stopped; + expect(workers[1].terminated).toBe(true); + await expect(reader.read(buildSlice())).rejects.toMatchObject({ + name: 'AbortError', + }); + }); +}); diff --git a/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts b/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts new file mode 100644 index 000000000..7c9551c01 --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { datasetFromTags } from '@/tests/dicomDataset'; +import { readGeometryFacts } from '../../collections/instanceFacts'; +import { getDatasetTag } from '../datasetAccess'; +import { readPixelSpacing } from '../spatialMetadata'; + +const spacingDataset = (value: string) => + datasetFromTags([['00280030', value]]); + +describe('single-value PixelSpacing display compatibility', () => { + it.each([ + ['0.5', 0.5], + ['0.0104', 0.0104], + [' 2.5\u0000', 2.5], + ] as const)( + 'displays %s as square pixels without claiming calibration', + (raw, value) => { + const dataset = spacingDataset(raw); + const axes = readPixelSpacing(dataset); + + expect(axes.map((axis) => axis.value)).toEqual([value, value]); + for (const axis of axes) { + expect(axis).toMatchObject({ + unit: 'unknown', + status: 'fallback', + source: 'Single PixelSpacing value', + }); + expect(axis.reason).toContain('square pixels are assumed for display'); + } + expect(readGeometryFacts(dataset).pixelSpacing).toBeNull(); + expect(getDatasetTag(dataset, '00280030')).toBe(raw); + } + ); + + it.each(['0', '-0.5', 'NaN', 'Infinity', ''])( + 'does not use %s as display spacing', + (raw) => { + expect(readPixelSpacing(spacingDataset(raw))).toEqual([ + expect.objectContaining({ + value: 1, + unit: 'unknown', + status: 'fallback', + }), + expect.objectContaining({ + value: 1, + unit: 'unknown', + status: 'fallback', + }), + ]); + } + ); +}); diff --git a/packages/dicom/core/metadata/datasetAccess.ts b/packages/dicom/core/metadata/datasetAccess.ts new file mode 100644 index 000000000..26ee74de1 --- /dev/null +++ b/packages/dicom/core/metadata/datasetAccess.ts @@ -0,0 +1,30 @@ +import type { DicomDataset, DicomElement } from './dicomDataset'; +import { trimDicomPadding } from '../utils'; + +const canonicalTag = (tag: string) => tag.replace('|', '').toUpperCase(); + +/** Text and numeric values retain multiplicity; sequences and opaque bytes do not become text. */ +export function getElementText(element: DicomElement): string | undefined { + const { values } = element; + switch (values.kind) { + case 'text': + case 'number': + return values.values.join('\\'); + case 'decimal': + return values.text.join('\\'); + default: + return undefined; + } +} + +export function getDatasetTag( + dataset: DicomDataset | null | undefined, + tag: string +) { + const requestedTag = canonicalTag(tag); + const element = dataset?.elements.find((entry) => entry.tag === requestedTag); + return element ? getElementText(element) : undefined; +} + +export const getDatasetModality = (dataset: DicomDataset | null | undefined) => + trimDicomPadding(getDatasetTag(dataset, '00080060') ?? '') || null; diff --git a/packages/dicom/core/metadata/dcmjs.d.ts b/packages/dicom/core/metadata/dcmjs.d.ts new file mode 100644 index 000000000..dccff0f97 --- /dev/null +++ b/packages/dicom/core/metadata/dcmjs.d.ts @@ -0,0 +1,83 @@ +declare module 'dcmjs' { + export type DicomTag = { + toCleanString(): string; + }; + + /** `vr` and `values` are `0` for the element a read stopped at. */ + export type DicomElement = { + tag: DicomTag; + vr: { type: string } | 0; + values: unknown; + rawValues: unknown; + }; + + export type DicomReadOptions = { + untilTag?: string; + includeUntilTagValue?: boolean; + forceStoreRaw?: boolean; + ignoreErrors?: boolean; + }; + + export type DicomStringDecoder = { + decode(view: ArrayBufferView): string; + }; + + export type DicomReadStream = { + offset: number; + readonly endOffset: number; + reset(): DicomReadStream; + end(): boolean; + increment(count: number): void; + setEndian(littleEndian: boolean): void; + readAsciiString(length: number): string; + readVR(): string; + readUint16(): number; + readUint32(): number; + setDecoder(decoder: DicomStringDecoder): void; + more(length: number): DicomReadStream; + slice(start: number, end: number): ArrayBuffer; + }; + + export type DicomDictionaryEntry = { + tag: string; + vr: string; + vm: string; + name: string; + }; + + export type DicomDataElement = { + vr: string; + Value: unknown[]; + _rawValue: unknown; + }; + + const dcmjs: { + constants: { + encodingMapping: Record; + }; + data: { + DicomMetaDictionary: { + dictionary: Record; + }; + ReadBufferStream: new (buffer: ArrayBuffer) => DicomReadStream; + DeflatedReadBufferStream: new ( + stream: DicomReadStream + ) => DicomReadStream; + DicomMessage: { + _readTag( + stream: DicomReadStream, + syntax: string, + options?: DicomReadOptions + ): DicomElement; + _read( + stream: DicomReadStream, + syntax: string, + options?: DicomReadOptions + ): Record; + _normalizeSyntax(syntax: string): string; + }; + }; + }; + + export default dcmjs; +} diff --git a/packages/dicom/core/metadata/dcmjsParser.ts b/packages/dicom/core/metadata/dcmjsParser.ts new file mode 100644 index 000000000..d5358b6ba --- /dev/null +++ b/packages/dicom/core/metadata/dcmjsParser.ts @@ -0,0 +1,444 @@ +import dcmjs, { DicomElement, DicomReadStream } from 'dcmjs'; +import { + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, + PART_10_HEADER_LENGTH, + sniffDicomLayout, +} from './dicomLayout'; + +const { encodingMapping } = dcmjs.constants; +const { + DicomMessage, + DicomMetaDictionary, + ReadBufferStream, + DeflatedReadBufferStream, +} = dcmjs.data; + +const FILE_META_GROUP = 0x0002; +const FILE_META_GROUP_LENGTH = '00020000'; +const TRANSFER_SYNTAX_UID = '00020010'; +const PIXEL_DATA = '7FE00010'; +const EXPLICIT_VR_BIG_ENDIAN = '1.2.840.10008.1.2.2'; +const DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1.99'; +const RESERVED_LENGTH = 2; +const UNDEFINED_LENGTH = 0xffffffff; + +/** VRs whose explicit form carries two reserved bytes and a 32 bit length. */ +const LENGTH_32_VRS = new Set([ + 'OB', + 'OD', + 'OF', + 'OL', + 'OV', + 'OW', + 'SQ', + 'SV', + 'UC', + 'UN', + 'UR', + 'UT', +]); + +/** Bound on one `String.fromCharCode` spread, which is an argument list. */ +const SPREAD_LIMIT = 4096; + +/** A byte string holds one code unit per byte, which `toBytes` reverses. */ +export const binaryString = (bytes: Uint8Array) => { + let text = ''; + for (let i = 0; i < bytes.length; i += SPREAD_LIMIT) + text += String.fromCharCode(...bytes.subarray(i, i + SPREAD_LIMIT)); + return text; +}; + +export const toBytes = (raw: string) => + Uint8Array.from(raw, (char) => char.charCodeAt(0) & 0xff); + +/** DICOM character set name to `TextDecoder` label, as dcmjs tabulates it. */ +export const encodingLabel = (name: string) => + encodingMapping[name.trim().replace(/[_ ]/g, '-').toLowerCase()]; + +/** + * One value as the file wrote it. A text VR is a byte string, so the Specific + * Character Set can be applied once the whole data set is known. + */ +export type ParsedValue = string | number | Uint8Array; + +/** One element, with no dcmjs object left in it. */ +export type ParsedElement = { + group: number; + element: number; + vr: string; + values: ParsedValue[]; + /** Items of a sequence, each a list of elements. */ + items?: ParsedElement[][]; + /** Set when the element's header was read but its value was not. */ + unread?: { bytes: Uint8Array; reason: string }; +}; + +/** + * Keeps one code unit per byte so the Specific Character Set can be applied + * once the whole data set is read. dcmjs otherwise picks a single decoder from + * character set value 1, which is the default repertoire rather than the + * extension that covers the non-ASCII characters. + */ +const byteDecoder = { + decode: (view: ArrayBufferView) => + binaryString(new Uint8Array(view.buffer, view.byteOffset, view.byteLength)), +}; + +/** + * Bounded item streams must keep their bytes until the enclosing dataset's + * Specific Character Set is known, including an item's inherited repertoire. + */ +const readsBytes = (stream: DicomReadStream) => { + stream.setDecoder(byteDecoder); + const derive = stream.more.bind(stream); + stream.more = (length: number) => readsBytes(derive(length)); + return stream; +}; + +const viewBytes = (value: unknown) => { + if (value instanceof ArrayBuffer) return new Uint8Array(value); + if (ArrayBuffer.isView(value)) + return new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + return null; +}; + +/** A group or element number as four upper case hexadecimal digits. */ +export const hex4 = (value: number) => + value.toString(16).padStart(4, '0').toUpperCase(); + +const dictionaryVr = (group: number, element: number) => + DicomMetaDictionary.dictionary[`(${hex4(group)},${hex4(element)})`]?.vr; + +/** dcmjs reads from an ArrayBuffer, which a whole-buffer view already is. */ +const bufferOf = (bytes: Uint8Array) => + bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength + ? (bytes.buffer as ArrayBuffer) + : (bytes.slice().buffer as ArrayBuffer); + +/** + * Opens the data set. A file without the Part 10 preamble is read from its + * first element; one without file meta information is read in the transfer + * syntax its first element suggests. + */ +const pastDeflatedMeta = (syntax: unknown, offset: number, end: number) => + syntax === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN && offset >= end; + +const openFile = (bytes: Uint8Array) => { + const layout = sniffDicomLayout(bytes.subarray(0, PART_10_HEADER_LENGTH)); + + const stream = new ReadBufferStream(bufferOf(bytes)); + stream.reset(); + if (layout.preamble) stream.increment(PART_10_HEADER_LENGTH); + if (!layout.fileMeta) + return { + dataSet: readsBytes(stream), + syntax: DicomMessage._normalizeSyntax(layout.transferSyntaxUid), + }; + + // Read group 2 sequentially when its group length is absent. A declared + // length also prevents compressed data from being mistaken for more meta. + let syntax: unknown; + let metaEnd = bytes.length; + stream.setEndian(true); + while (!stream.end() && !pastDeflatedMeta(syntax, stream.offset, metaEnd)) { + const start = stream.offset; + const group = stream.readUint16(); + stream.offset = start; + if (group !== FILE_META_GROUP) break; + const attribute = DicomMessage._readTag(stream, EXPLICIT_VR_LITTLE_ENDIAN); + const tag = attribute.tag.toCleanString(); + if (tag === FILE_META_GROUP_LENGTH) { + const [length] = attribute.values as number[]; + metaEnd = stream.offset + length; + } + if (tag === TRANSFER_SYNTAX_UID) [syntax] = attribute.values as unknown[]; + } + if (typeof syntax !== 'string') + throw new Error('Not a DICOM file: the transfer syntax is missing'); + + const dataSet = + syntax === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN + ? new DeflatedReadBufferStream(stream) + : stream; + return { + dataSet: readsBytes(dataSet), + syntax: DicomMessage._normalizeSyntax(syntax), + }; +}; + +const needsSequenceReader = (vr: string | undefined, length: number) => + vr === 'SQ' || + ((vr === 'UN' || vr === undefined) && length === UNDEFINED_LENGTH); + +/** + * A known UN retains its implicit encoding even inside an explicit dataset. + */ +const isKnownUnknown = ( + vr: string | undefined, + group: number, + element: number +) => { + if (vr !== 'UN') return false; + const known = dictionaryVr(group, element); + return known !== undefined && known !== 'UN'; +}; + +const peekSequence = (dataSet: DicomReadStream, syntax: string) => { + const start = dataSet.offset; + const implicit = syntax === IMPLICIT_VR_LITTLE_ENDIAN; + dataSet.setEndian(syntax !== EXPLICIT_VR_BIG_ENDIAN); + const group = dataSet.readUint16(); + const element = dataSet.readUint16(); + const vr = implicit ? dictionaryVr(group, element) : dataSet.readVR(); + const length32 = implicit || LENGTH_32_VRS.has(vr ?? ''); + if (length32 && !implicit) dataSet.increment(RESERVED_LENGTH); + const length = length32 ? dataSet.readUint32() : dataSet.readUint16(); + const valueStart = dataSet.offset; + dataSet.offset = start; + const knownUnknown = isKnownUnknown(vr, group, element); + return needsSequenceReader(vr, length) || knownUnknown + ? { + unknown: vr === 'UN', + group, + element, + valueStart, + end: length === UNDEFINED_LENGTH ? null : valueStart + length, + } + : null; +}; + +/** + * dcmjs drops the trailing byte that padded a value to an even length, which + * the file wrote. A UI's pad is a null byte and carries no value, so only the + * space that pads a text VR is put back. + */ +const restorePadByte = (vr: string, values: string[]) => { + const byteLength = values.reduce( + (total, value) => total + value.length, + values.length - 1 + ); + return vr !== 'UI' && byteLength % 2 === 1 + ? values.map((value, index) => + index === values.length - 1 ? `${value} ` : value + ) + : values; +}; + +const rawValuesOf = (rawValues: unknown) => { + if (rawValues == null) return []; + return Array.isArray(rawValues) ? (rawValues as unknown[]) : [rawValues]; +}; + +const parsedValues = (vr: string, rawValues: unknown): ParsedValue[] => { + const values = rawValuesOf(rawValues); + if (values.every((value): value is string => typeof value === 'string')) + return restorePadByte(vr, values); + return values.map((value) => { + const bytes = viewBytes(value); + if (bytes) return bytes; + return typeof value === 'number' ? value : String(value); + }); +}; + +const groupOf = (tag: string) => Number.parseInt(tag.slice(0, 4), 16); +const elementOf = (tag: string) => Number.parseInt(tag.slice(4), 16); + +const parsedElement = (element: DicomElement): ParsedElement => { + const tag = element.tag.toCleanString(); + const vr = element.vr === 0 ? '' : element.vr.type; + return { + group: groupOf(tag), + element: elementOf(tag), + vr, + values: parsedValues(vr, element.rawValues), + }; +}; + +const READ_OPTIONS = { + untilTag: PIXEL_DATA, + includeUntilTagValue: false, + forceStoreRaw: true, +}; + +const readSequence = ( + dataSet: DicomReadStream, + syntax: string, + sequence: { + group: number; + element: number; + valueStart: number; + end: number | null; + unknown?: boolean; + } +): ParsedElement => { + if (sequence.end !== null && sequence.end > dataSet.endOffset) + throw new Error('Sequence exceeds the available dataset bytes'); + if (sequence.unknown && sequence.end !== null) { + // PS3.5 6.2.2: a known UN value retains Implicit VR Little Endian encoding. + const value = new Uint8Array( + dataSet.slice(sequence.valueStart, sequence.end) + ); + const bytes = new Uint8Array(8 + value.length); + const header = new DataView(bytes.buffer); + header.setUint16(0, sequence.group, true); + header.setUint16(2, sequence.element, true); + header.setUint32(4, value.length, true); + bytes.set(value, 8); + dataSet.offset = sequence.end; + return readElements( + readsBytes(new ReadBufferStream(bytes.buffer)), + IMPLICIT_VR_LITTLE_ENDIAN, + { stopAtPixelData: false } + )[0]; + } + + const itemSyntax = sequence.unknown ? IMPLICIT_VR_LITTLE_ENDIAN : syntax; + dataSet.offset = sequence.valueStart; + try { + const items = readSequenceItems(dataSet, itemSyntax, sequence.end); + return { + group: sequence.group, + element: sequence.element, + vr: sequence.unknown ? 'UN' : 'SQ', + values: [], + items, + }; + } catch (error) { + if (sequence.end === null) throw error; + const bytes = new Uint8Array( + dataSet.slice(sequence.valueStart, sequence.end) + ); + dataSet.offset = sequence.end; + return { + group: sequence.group, + element: sequence.element, + vr: sequence.unknown ? 'UN' : 'SQ', + values: [], + unread: { bytes, reason: String(error) }, + }; + } +}; + +const assertSequenceBounds = ( + offset: number, + end: number | null, + length = 0 +) => { + if (end !== null && offset + length > end) + throw new Error('Sequence item exceeds the declared sequence length'); +}; + +function readSequenceItemLength(dataSet: DicomReadStream, syntax: string) { + dataSet.setEndian(syntax !== EXPLICIT_VR_BIG_ENDIAN); + const group = dataSet.readUint16(); + const element = dataSet.readUint16(); + const length = dataSet.readUint32(); + if (group === 0xfffe && element === 0xe0dd && length === 0) return null; + if (group !== 0xfffe || element !== 0xe000) + throw new Error('Expected a sequence item'); + return length; +} + +function readSequenceItems( + dataSet: DicomReadStream, + syntax: string, + end: number | null +) { + const items: ParsedElement[][] = []; + while (end === null || dataSet.offset < end) { + assertSequenceBounds(dataSet.offset, end, 8); + const length = readSequenceItemLength(dataSet, syntax); + if (length === null) { + assertSequenceBounds(dataSet.offset, end); + // A defined length still bounds the value after a premature delimiter. + // Its trailing bytes cannot become elements of the enclosing dataset. + if (end !== null) dataSet.offset = end; + return items; + } + assertSequenceBounds( + dataSet.offset, + end, + length === UNDEFINED_LENGTH ? 0 : length + ); + items.push( + length === UNDEFINED_LENGTH + ? readElements(dataSet, syntax, { + untilItemDelimiter: true, + stopAtPixelData: false, + }) + : readElements(dataSet.more(length), syntax, { stopAtPixelData: false }) + ); + assertSequenceBounds(dataSet.offset, end); + } + return items; +} + +/** Consumes an item delimiter, leaving any other element unread. */ +const readItemDelimiter = (dataSet: DicomReadStream, syntax: string) => { + const start = dataSet.offset; + dataSet.setEndian(syntax !== EXPLICIT_VR_BIG_ENDIAN); + const group = dataSet.readUint16(); + const element = dataSet.readUint16(); + if (group !== 0xfffe || element !== 0xe00d) { + dataSet.offset = start; + return false; + } + if (dataSet.readUint32() !== 0) + throw new Error('Invalid item delimiter length'); + return true; +}; + +const readNextElement = ( + dataSet: DicomReadStream, + syntax: string, + stopAtPixelData: boolean +) => { + const sequence = peekSequence(dataSet, syntax); + if ( + sequence && + stopAtPixelData && + sequence.group === 0x7fe0 && + sequence.element === 0x0010 + ) + return { element: null, done: true }; + if (sequence) + return { element: readSequence(dataSet, syntax, sequence), done: false }; + + const element = DicomMessage._readTag( + dataSet, + syntax, + stopAtPixelData ? READ_OPTIONS : { forceStoreRaw: true } + ); + const done = stopAtPixelData && element.tag.toCleanString() === PIXEL_DATA; + return { + element: done || element.vr === 0 ? null : parsedElement(element), + done, + }; +}; + +const readElements = ( + dataSet: DicomReadStream, + syntax: string, + { untilItemDelimiter = false, stopAtPixelData = true } = {} +): ParsedElement[] => { + const elements: ParsedElement[] = []; + let done = false; + while (!done && !dataSet.end()) { + if (untilItemDelimiter && readItemDelimiter(dataSet, syntax)) + return elements; + const next = readNextElement(dataSet, syntax, stopAtPixelData); + done = next.done; + if (next.element) elements.push(next.element); + } + if (untilItemDelimiter) + throw new Error('Missing item delimiter in undefined-length UN'); + return elements; +}; + +/** Reads a Part 10 file's data set elements, stopping before Pixel Data. */ +export const parseDicomElements = (bytes: Uint8Array) => { + const { dataSet, syntax } = openFile(bytes); + return readElements(dataSet, syntax); +}; diff --git a/packages/dicom/core/metadata/dicomCharacterSet.ts b/packages/dicom/core/metadata/dicomCharacterSet.ts new file mode 100644 index 000000000..d5a6ae45d --- /dev/null +++ b/packages/dicom/core/metadata/dicomCharacterSet.ts @@ -0,0 +1,206 @@ +import { encodingLabel, toBytes } from './dcmjsParser'; + +const ESCAPE_BYTE = 0x1b; + +export const VALUE_DELIMITER = '\\'; + +/** Bytes a conforming writer resets the repertoire before. */ +const DELIMITER_BYTES = new Set([0x0a, 0x0c, 0x0d, 0x3d, 0x5c, 0x5e]); + +/** + * The VRs a Specific Character Set applies to, from PS3.5 6.1.2 and PS3.3 + * C.12.1.1.2. Every other string VR, DS and IS included, stays in the default + * repertoire, so no charset transform can reach a numeric value. + */ +export const CHARSET_VRS = new Set(['SH', 'LO', 'ST', 'PN', 'LT', 'UC', 'UT']); + +/** Bytes of a VR the Specific Character Set does not reach are code points. */ +export const defaultRepertoire = (raw: string) => raw; + +/** A repertoire in force over one run of bytes. */ +type Repertoire = { + decode: (bytes: Uint8Array) => string; + multibyte: boolean; +}; + +const tryDecode = (decoder: TextDecoder, bytes: Uint8Array) => { + try { + return decoder.decode(bytes); + } catch { + return undefined; + } +}; + +const highHalf = (bytes: Uint8Array) => bytes.map((byte) => byte | 0x80); + +/** JIS X 0212 rides EUC-JP's third plane, one 0x8f before each high half pair. */ +const jisX0212Bytes = (bytes: Uint8Array) => + Uint8Array.from( + Array.from({ length: Math.floor(bytes.length / 2) }, (_, pair) => [ + 0x8f, + bytes[pair * 2] | 0x80, + bytes[pair * 2 + 1] | 0x80, + ]).flat() + ); + +const repertoire = ( + label: string, + { + multibyte = false, + mapBytes = (bytes: Uint8Array) => bytes, + }: { multibyte?: boolean; mapBytes?: (bytes: Uint8Array) => Uint8Array } = {} +): Repertoire => { + const decoder = new TextDecoder(label); + return { decode: (bytes) => decoder.decode(mapBytes(bytes)), multibyte }; +}; + +/** Final byte of an `ESC -` designation to the decoder for its high half. */ +const G1_LABELS: Record = { + A: 'latin1', + B: 'iso-8859-2', + C: 'iso-8859-3', + D: 'iso-8859-4', + F: 'iso-ir-126', + G: 'iso-ir-127', + H: 'iso-ir-138', + L: 'iso-ir-144', + M: 'iso-ir-148', + T: 'tis-620', +}; + +/** + * The ISO 2022 designations DICOM allows, keyed by the bytes following the + * escape. `ESC ( B` and `ESC ( J` return to the default repertoire, so they are + * added per file where that default is known. + */ +const DESIGNATIONS: Record = { + '(I': repertoire('shift-jis', { mapBytes: highHalf }), + ')I': repertoire('shift-jis'), + $B: repertoire('euc-jp', { multibyte: true, mapBytes: highHalf }), + $A: repertoire('gbk', { multibyte: true, mapBytes: highHalf }), + '$(D': repertoire('euc-jp', { multibyte: true, mapBytes: jisX0212Bytes }), + '$)C': repertoire('euc-kr', { multibyte: true }), + '$)A': repertoire('gbk', { multibyte: true }), + ...Object.fromEntries( + Object.entries(G1_LABELS).map(([final, label]) => [ + `-${final}`, + repertoire(label), + ]) + ), +}; + +/** Designations are two or three bytes wide, longest match first. */ +const designationAt = ( + bytes: Uint8Array, + at: number, + table: Record +) => + [3, 2] + .map((width) => ({ + width, + mode: table[String.fromCharCode(...bytes.subarray(at, at + width))], + })) + .find(({ mode }) => mode != null); + +/** + * Reads a value whose repertoire switches mid stream. Every run between two + * escapes decodes under the repertoire the earlier escape designated, and a + * delimiter returns a single byte repertoire to the default, as the standard + * requires a writer to do explicitly. + */ +const decodeDesignations = ( + bytes: Uint8Array, + initial: Repertoire, + table: Record +) => { + const runs: string[] = []; + let mode = initial; + let start = 0; + let at = 0; + const flush = (end: number) => { + if (end > start) runs.push(mode.decode(bytes.subarray(start, end))); + }; + + while (at < bytes.length) { + const designation = + bytes[at] === ESCAPE_BYTE + ? designationAt(bytes, at + 1, table) + : undefined; + if (designation) { + flush(at); + mode = designation.mode; + at += 1 + designation.width; + start = at; + } else { + if ( + mode !== initial && + !mode.multibyte && + DELIMITER_BYTES.has(bytes[at]) + ) { + flush(at); + mode = initial; + start = at; + } + at += 1; + } + } + flush(bytes.length); + return runs.join(''); +}; + +/** + * Value 1 of Specific Character Set is the default repertoire and values 2 and + * up are extensions. Bytes outside an escape sequence use value 1; another + * declared set is tried only if that decoder rejects the bytes. ISO 2022 IR 13 holds half width + * katakana as raw bytes that the escape driven ISO 2022 IR 87 decoder rejects, + * so no single decoder covers every value of such a file. + */ +export const characterSetDecoder = (specificCharacterSet: string[]) => { + const first = specificCharacterSet[0]?.trim() ?? ''; + const declared = specificCharacterSet + .slice(1) + .filter((name) => name.trim().length > 0) + .map(encodingLabel) + .filter((label): label is string => label != null); + const labels = [encodingLabel(first) ?? 'utf-8', ...declared]; + const asciiDefault = !first || /^ISO[ _](?:2022[ _])?IR[ _]6$/.test(first); + const strict = labels.map((label) => new TextDecoder(label, { fatal: true })); + const lenient = new TextDecoder(labels[0]); + // JIS X 0201 has no backslash or tilde; those code points are the yen sign + // and the overline, which is what GDCM emitted for such a file. + const jisRoman = labels.includes('shift-jis'); + + const initial: Repertoire = { + decode: (bytes) => + strict.reduce( + (text, decoder, index) => + text ?? + (index === 0 && asciiDefault && bytes.some((byte) => byte > 0x7f) + ? undefined + : tryDecode(decoder, bytes)), + undefined + ) ?? lenient.decode(bytes), + multibyte: false, + }; + const table = { ...DESIGNATIONS, '(B': initial, '(J': initial }; + + const decode = (raw: string) => { + const bytes = toBytes(raw); + return bytes.includes(ESCAPE_BYTE) + ? decodeDesignations(bytes, initial, table) + : initial.decode(bytes); + }; + const repertoireText = (text: string) => + jisRoman ? text.replace(/\\/g, '\u00a5').replace(/~/g, '\u203e') : text; + + return { + /** An element of value multiplicity 1, whose backslash is a character. */ + value: (raw: string) => repertoireText(decode(raw)), + /** + * A whole element's bytes, split into its values once decoded: byte 0x5c + * delimits values only where it is not part of a multibyte character. + */ + values: (raw: string) => + decode(raw).split(VALUE_DELIMITER).map(repertoireText), + }; +}; diff --git a/packages/dicom/core/metadata/dicomDataset.ts b/packages/dicom/core/metadata/dicomDataset.ts new file mode 100644 index 000000000..601ec68ba --- /dev/null +++ b/packages/dicom/core/metadata/dicomDataset.ts @@ -0,0 +1,269 @@ +import { + hex4, + ParsedElement, + ParsedValue, + parseDicomElements, + toBytes, +} from './dcmjsParser'; +import { concatBytes, trimDicomPadding } from '../utils'; +import { + CHARSET_VRS, + characterSetDecoder, + defaultRepertoire, + VALUE_DELIMITER, +} from './dicomCharacterSet'; + +const SPECIFIC_CHARACTER_SET = '00080005'; + +/** A tag as `ggggeeee` in upper case hexadecimal. */ +export type DicomTagKey = string; + +export type AttributeTag = { group: number; element: number }; + +/** VRs whose values are text under the default repertoire or a declared set. */ +const TEXT_VRS = new Set([ + 'AE', + 'AS', + 'CS', + 'DA', + 'DT', + 'LO', + 'LT', + 'PN', + 'SH', + 'ST', + 'TM', + 'UC', + 'UI', + 'UR', + 'UT', +]); + +/** Text VRs of value multiplicity 1, whose backslash is a character. */ +const SINGLE_VALUED_TEXT_VRS = new Set(['LT', 'ST', 'UT']); + +/** VRs holding a number written as characters. */ +const DECIMAL_VRS = new Set(['DS', 'IS']); + +/** VRs holding a number written as bytes. */ +const NUMBER_VRS = new Set(['FL', 'FD', 'SL', 'SS', 'SV', 'UL', 'US', 'UV']); + +/** VRs whose value is an opaque buffer. */ +const BYTES_VRS = new Set(['OB', 'OD', 'OF', 'OL', 'OV', 'OW', 'UN']); + +const KNOWN_VRS = new Set([ + ...TEXT_VRS, + ...DECIMAL_VRS, + ...NUMBER_VRS, + ...BYTES_VRS, + 'AT', + 'SQ', +]); + +export type DicomValues = + /** A text VR, one entry per value, with the Specific Character Set applied. */ + | { kind: 'text'; values: string[] } + /** DS and IS: the numbers, next to the characters the file wrote. A value + * that is not a number is null rather than zero. */ + | { kind: 'decimal'; values: Array; text: string[] } + /** A binary numeric VR. */ + | { kind: 'number'; values: number[] } + /** AT, each value a referenced tag. */ + | { kind: 'attributeTag'; values: AttributeTag[] } + /** SQ, one data set per item. */ + | { kind: 'sequence'; items: DicomDataset[] } + /** A buffer VR. */ + | { kind: 'bytes'; values: Uint8Array[] } + /** An element whose header was read and whose value was not. */ + | { kind: 'unread'; bytes: Uint8Array; reason: string }; + +export type DicomElement = { + tag: DicomTagKey; + group: number; + element: number; + vr: string; + values: DicomValues; + /** Value bytes, kept where the VR alone does not say how to read them. */ + bytes?: Uint8Array; +}; + +export type DicomDataset = { + /** Elements in the order the parser reported them. */ + elements: DicomElement[]; + /** (0008,0005) as this data set declares it, or null when it declares none. */ + specificCharacterSet: string[] | null; +}; + +export const tagKey = (group: number, element: number) => + `${hex4(group)}${hex4(element)}`; + +export const isPrivateElement = ({ group }: DicomElement) => (group & 1) === 1; + +export const findElement = (dataset: DicomDataset, tag: DicomTagKey) => + dataset.elements.find((element) => element.tag === tag); + +const isText = (value: ParsedValue): value is string => + typeof value === 'string'; + +const isNumber = (value: ParsedValue): value is number => + typeof value === 'number'; + +const isBytes = (value: ParsedValue): value is Uint8Array => + value instanceof Uint8Array; + +const decimalOf = (text: string) => { + const trimmed = trimDicomPadding(text); + const value = Number(trimmed); + return trimmed.length > 0 && Number.isFinite(value) ? value : null; +}; + +const attributeTagOf = (packed: number) => ({ + group: packed >>> 16, + element: packed & 0xffff, +}); + +/** Undecoded value bytes, where every value carries them. */ +const rawBytesOf = ({ values }: ParsedElement) => { + if (values.every(isText)) return toBytes(values.join(VALUE_DELIMITER)); + if (values.every(isBytes)) + return values.length === 1 ? values[0] : concatBytes(values); + return undefined; +}; + +/** + * A private element's meaning follows its private creator, and an unknown VR + * says nothing at all, so both keep the bytes the file wrote. + */ +const keepsBytes = ({ group, vr }: ParsedElement) => + (group & 1) === 1 || vr === 'UN' || !KNOWN_VRS.has(vr); + +type CharacterSetDecoder = ReturnType; + +/** + * dcmjs splits a value on every 0x5c byte, which GB18030, GBK and ISO 2022 + * write inside multibyte characters, so a value the character set reaches is + * put back together and separated again once its characters are known. + */ +const textValues = ( + vr: string, + values: string[], + decode: CharacterSetDecoder +) => { + if (!CHARSET_VRS.has(vr) || values.length === 0) + return values.map(defaultRepertoire); + const raw = values.join(VALUE_DELIMITER); + return SINGLE_VALUED_TEXT_VRS.has(vr) + ? [decode.value(raw)] + : decode.values(raw); +}; + +const classifiedValues = ( + vr: string, + values: ParsedValue[], + decode: CharacterSetDecoder +): DicomValues => { + if (vr === 'AT' && values.every(isNumber)) + return { kind: 'attributeTag', values: values.map(attributeTagOf) }; + if (DECIMAL_VRS.has(vr) && values.every(isText)) + return { kind: 'decimal', values: values.map(decimalOf), text: values }; + if (values.every(isText)) + return { kind: 'text', values: textValues(vr, values, decode) }; + if (values.every(isNumber)) return { kind: 'number', values }; + if (values.every(isBytes)) return { kind: 'bytes', values }; + return { + kind: 'unread', + bytes: new Uint8Array(0), + reason: `mixed value types for VR ${vr}`, + }; +}; + +const elementValues = ( + parsed: ParsedElement, + decode: CharacterSetDecoder, + charset: string[] | null +): DicomValues => { + if (parsed.unread) + return { + kind: 'unread', + bytes: parsed.unread.bytes, + reason: parsed.unread.reason, + }; + if (parsed.items) + return { + kind: 'sequence', + items: parsed.items.map((item) => buildDataset(item, charset, decode)), + }; + return classifiedValues(parsed.vr, parsed.values, decode); +}; + +const buildElement = ( + parsed: ParsedElement, + decode: CharacterSetDecoder, + charset: string[] | null +): DicomElement => { + const bytes = + !parsed.items && keepsBytes(parsed) ? rawBytesOf(parsed) : undefined; + return { + tag: tagKey(parsed.group, parsed.element), + group: parsed.group, + element: parsed.element, + vr: parsed.vr, + values: elementValues(parsed, decode, charset), + ...(bytes ? { bytes } : {}), + }; +}; + +// The declared set is the values the data set itself wrote, so a data set that +// declares none stays distinguishable from one that declares the default. +const declaredCharacterSet = (elements: ParsedElement[]) => { + const found = elements.find( + (element) => + tagKey(element.group, element.element) === SPECIFIC_CHARACTER_SET + ); + return found ? found.values.filter(isText).map((name) => name.trim()) : null; +}; + +function buildDataset( + elements: ParsedElement[], + inherited: string[] | null, + inheritedDecoder?: CharacterSetDecoder +): DicomDataset { + const declared = declaredCharacterSet(elements); + const charset = declared ?? inherited; + const decode = + declared === null && inheritedDecoder + ? inheritedDecoder + : characterSetDecoder(charset ?? []); + return { + elements: elements.map((element) => buildElement(element, decode, charset)), + specificCharacterSet: declared, + }; +} + +/** + * Reads a Part 10 file's header into a standards-shaped data set: every element + * keeps its tag, VR, value multiplicity, nested items and, where the VR alone + * cannot say how to read it, its bytes. Nothing missing is filled in. + */ +export const readDicomDataset = (bytes: Uint8Array) => + buildDataset(parseDicomElements(bytes), null); + +/** Image loading uses public attributes; private payloads stay in the source. */ +export const withoutPrivateElements = ( + dataset: DicomDataset +): DicomDataset => ({ + ...dataset, + elements: dataset.elements + .filter((element) => !isPrivateElement(element)) + .map((element) => + element.values.kind === 'sequence' + ? { + ...element, + values: { + ...element.values, + items: element.values.items.map(withoutPrivateElements), + }, + } + : element + ), +}); diff --git a/packages/dicom/core/metadata/dicomLayout.ts b/packages/dicom/core/metadata/dicomLayout.ts new file mode 100644 index 000000000..af3b2c294 --- /dev/null +++ b/packages/dicom/core/metadata/dicomLayout.ts @@ -0,0 +1,90 @@ +import { toAscii } from '../utils'; + +/** + * How a DICOM byte stream opens. + * + * Part 10 puts 128 bytes of preamble and the letters DICM before the file meta + * information, but files written without them are common enough that GDCM + * reads them, so the opening is sniffed rather than required: the file meta + * information may start at the first byte, or the data set itself may, with + * nothing to name its transfer syntax but the shape of its first element. + */ +export const PREAMBLE_LENGTH = 128; +export const DICOM_PREFIX = 'DICM'; +/** The bytes a Part 10 file spends before its first element. */ +export const PART_10_HEADER_LENGTH = PREAMBLE_LENGTH + DICOM_PREFIX.length; + +export const IMPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2'; +export const EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1'; + +export type DicomLayout = + /** Part 10: preamble, prefix and file meta information. */ + | { preamble: true; fileMeta: true } + /** File meta information from the first byte, with no preamble. */ + | { preamble: false; fileMeta: true } + /** + * A bare data set, with no file meta information to name its transfer + * syntax. The syntax is what the encoding of the first element suggests. + */ + | { preamble: false; fileMeta: false; transferSyntaxUid: string }; + +const FILE_META_GROUP = 0x0002; + +/** + * The group a bare data set opens with: every SOP instance carries a SOP Class + * UID in it, and Specific Character Set and Image Type sort ahead of that. + * Bytes that open with any other group are not a data set, and reading them + * as one would take arbitrary noise for a header. + */ +const FIRST_DATA_SET_GROUP = 0x0008; + +/** The bytes needed to judge one element's tag and, in explicit VR, its VR. */ +const ELEMENT_HEAD_LENGTH = 6; + +// prettier-ignore +const VRS = new Set([ + 'AE', 'AS', 'AT', 'CS', 'DA', 'DS', 'DT', 'FD', 'FL', 'IS', 'LO', 'LT', 'OB', + 'OD', 'OF', 'OL', 'OV', 'OW', 'PN', 'SH', 'SL', 'SQ', 'SS', 'ST', 'SV', 'TM', + 'UC', 'UI', 'UL', 'UN', 'UR', 'US', 'UT', 'UV', +]); + +const littleEndianGroup = (head: Uint8Array) => head[0] | (head[1] << 8); + +/** Whether the two bytes after the first tag spell a VR, as explicit VR does. */ +const opensWithVr = (head: Uint8Array) => + VRS.has(toAscii(head.subarray(4, ELEMENT_HEAD_LENGTH))); + +/** + * Reads how `head` opens. `head` should hold the first 132 bytes of the file; + * fewer decide what they can. Throws when no reading fits, since guessing past + * this point would parse noise as a header. + */ +export function sniffDicomLayout(head: Uint8Array): DicomLayout { + if ( + head.length >= PART_10_HEADER_LENGTH && + toAscii(head.subarray(PREAMBLE_LENGTH, PART_10_HEADER_LENGTH)) === + DICOM_PREFIX + ) + return { preamble: true, fileMeta: true }; + + if (head.length < ELEMENT_HEAD_LENGTH) + throw new Error('Not DICOM: too short to hold a data element'); + + // File meta information is always explicit VR little endian. + const group = littleEndianGroup(head); + if (group === FILE_META_GROUP && opensWithVr(head)) + return { preamble: false, fileMeta: true }; + + if (group !== FIRST_DATA_SET_GROUP) + throw new Error( + 'Not DICOM: no preamble, file meta information or data set' + ); + + return { + preamble: false, + fileMeta: false, + transferSyntaxUid: opensWithVr(head) + ? EXPLICIT_VR_LITTLE_ENDIAN + : IMPLICIT_VR_LITTLE_ENDIAN, + }; +} diff --git a/src/core/dicomTags.ts b/packages/dicom/core/metadata/dicomTags.ts similarity index 86% rename from src/core/dicomTags.ts rename to packages/dicom/core/metadata/dicomTags.ts index 585f43ac7..4bc1e6fe5 100644 --- a/src/core/dicomTags.ts +++ b/packages/dicom/core/metadata/dicomTags.ts @@ -18,7 +18,9 @@ const tags: Tag[] = [ { name: 'Modality', tag: '0008|0060' }, { name: 'SeriesInstanceUID', tag: '0020|000e' }, { name: 'SeriesNumber', tag: '0020|0011' }, + { name: 'SeriesDate', tag: '0008|0021' }, { name: 'SeriesDescription', tag: '0008|103e' }, + { name: 'InstanceNumber', tag: '0020|0013' }, { name: 'WindowLevel', tag: '0028|1050' }, { name: 'WindowWidth', tag: '0028|1051' }, { name: 'VOILUTFunction', tag: '0028|1056' }, @@ -27,10 +29,16 @@ const tags: Tag[] = [ { name: 'BitsAllocated', tag: '0028|0100' }, { name: 'BitsStored', tag: '0028|0101' }, { name: 'PixelRepresentation', tag: '0028|0103' }, + { name: 'AcquisitionNumber', tag: '0020|0012' }, + { name: 'TemporalPositionIdentifier', tag: '0020|0100' }, + { name: 'EchoNumbers', tag: '0018|0086' }, + { name: 'DiffusionBValue', tag: '0018|9087' }, { name: 'ImagePositionPatient', tag: '0020|0032' }, { name: 'ImageOrientationPatient', tag: '0020|0037' }, { name: 'PixelSpacing', tag: '0028|0030' }, { name: 'SpacingBetweenSlices', tag: '0018|0088' }, + { name: 'SliceThickness', tag: '0018|0050' }, + { name: 'SequenceName', tag: '0018|0024' }, { name: 'SamplesPerPixel', tag: '0028|0002' }, { name: 'RescaleIntercept', tag: '0028|1052' }, { name: 'RescaleSlope', tag: '0028|1053' }, @@ -62,16 +70,7 @@ export function isUltrasoundMultiframeSopClass(uid: string): boolean { ); } -export const TAG_TO_NAME = new Map(tags.map((t) => [t.tag, t.name])); -export const NAME_TO_TAG = new Map(tags.map((t) => [t.name, t.tag])); export const Tags = Object.fromEntries(tags.map((t) => [t.name, t.tag])); -// Splits an itk-wasm-style "GGGG|EEEE" tag into the numeric [group, element] -// pair emitted by the streaming DICOM parser. -export const tagToGroupElement = (tag: string): [number, number] => { - const [group, element] = tag.split('|'); - return [parseInt(group, 16), parseInt(element, 16)]; -}; - // Converts an itk-wasm-style "GGGG|EEEE" tag to a dicom-parser element key. export const toDicomParserKey = (tag: string) => `x${tag.replace('|', '')}`; diff --git a/packages/dicom/core/metadata/functionalGroups.ts b/packages/dicom/core/metadata/functionalGroups.ts new file mode 100644 index 000000000..2f84c1a99 --- /dev/null +++ b/packages/dicom/core/metadata/functionalGroups.ts @@ -0,0 +1,54 @@ +import type { DicomDataset } from './dicomDataset'; +import { findElement } from './dicomDataset'; +import { getDatasetTag } from './datasetAccess'; +import { getNmDetectorTag } from './nmReconstruction'; + +const SHARED_GROUPS = '52009229'; +const PER_FRAME_GROUPS = '52009230'; + +const IMAGE_MACROS = new Map([ + ['00180050', '00289110'], // Pixel Measures: Slice Thickness + ['00180088', '00289110'], // Pixel Measures: Spacing Between Slices + ['00280030', '00289110'], // Pixel Measures: Pixel Spacing + ['00200032', '00209113'], // Plane Position (Patient) + ['00200037', '00209116'], // Plane Orientation (Patient) + ['00281052', '00289145'], // Pixel Value Transformation: Intercept + ['00281053', '00289145'], // Pixel Value Transformation: Slope +]); + +export function sequenceItems(dataset: DicomDataset, tag: string) { + const values = findElement(dataset, tag)?.values; + return values?.kind === 'sequence' ? values.items : []; +} + +const macroValue = ( + group: DicomDataset | undefined, + macro: string, + tag: string +) => (group ? getDatasetTag(sequenceItems(group, macro)[0], tag) : undefined); + +/** + * Image attributes have specific Functional Group paths. Unrelated nested + * sequences, including referenced images, never supply the image's own tags. + */ +export function getFrameTag( + dataset: DicomDataset | null | undefined, + tag: string, + frameIndex = 0 +) { + if (!dataset) return undefined; + const key = tag.replace('|', '').toUpperCase(); + const macro = IMAGE_MACROS.get(key); + if (!macro) return getDatasetTag(dataset, key); + const perFrame = sequenceItems(dataset, PER_FRAME_GROUPS)[frameIndex]; + const shared = sequenceItems(dataset, SHARED_GROUPS)[0]; + return ( + macroValue(perFrame, macro, key) ?? + macroValue(shared, macro, key) ?? + getNmDetectorTag(dataset, key) ?? + getDatasetTag(dataset, key) + ); +} + +export const perFrameGroups = (dataset: DicomDataset) => + sequenceItems(dataset, PER_FRAME_GROUPS); diff --git a/packages/dicom/core/metadata/modalityRescale.ts b/packages/dicom/core/metadata/modalityRescale.ts new file mode 100644 index 000000000..24a70e515 --- /dev/null +++ b/packages/dicom/core/metadata/modalityRescale.ts @@ -0,0 +1,32 @@ +import type { DicomDataset } from './dicomDataset'; +import { getFrameTag, perFrameGroups } from './functionalGroups'; +import { numberOr } from '../utils'; + +export const readModalityRescale = ( + metadata: DicomDataset | null | undefined, + frameIndex = 0 +) => ({ + // GDCM reads a zero slope as 1; matching it keeps native and GDCM pixels equal. + rescaleSlope: numberOr(getFrameTag(metadata, '00281053', frameIndex), 1) || 1, + rescaleIntercept: numberOr(getFrameTag(metadata, '00281052', frameIndex), 0), +}); + +/** Whether every frame shares the first frame's slope and intercept. */ +export function hasUniformModalityRescale(metadata: DicomDataset) { + const first = readModalityRescale(metadata); + return perFrameGroups(metadata).every((_, index) => { + const frame = readModalityRescale(metadata, index); + return ( + frame.rescaleSlope === first.rescaleSlope && + frame.rescaleIntercept === first.rescaleIntercept + ); + }); +} + +/** GDCM applies one transform to an instance, so its frames must agree. */ +export function assertUniformModalityRescale(metadata: DicomDataset) { + if (!hasUniformModalityRescale(metadata)) + throw new Error( + 'Cannot load DICOM frames with differing modality rescale: the decoder applies one transform to the entire instance' + ); +} diff --git a/packages/dicom/core/metadata/nmReconstruction.ts b/packages/dicom/core/metadata/nmReconstruction.ts new file mode 100644 index 000000000..52723d68d --- /dev/null +++ b/packages/dicom/core/metadata/nmReconstruction.ts @@ -0,0 +1,146 @@ +import { findElement, type DicomDataset } from './dicomDataset'; +import { getDatasetTag } from './datasetAccess'; +import { trimDicomPadding } from '../utils'; + +const NM_IMAGE_STORAGE = '1.2.840.10008.5.1.4.1.1.20'; +const SLICE_VECTOR = '00540080'; +const DETECTOR_INFORMATION = '00540022'; + +const text = (metadata: DicomDataset, tag: string) => + trimDicomPadding(getDatasetTag(metadata, tag) ?? ''); + +const number = (metadata: DicomDataset, tag: string) => { + const value = text(metadata, tag); + return value ? Number(value) : NaN; +}; + +const vector = (metadata: DicomDataset, tag: string) => + text(metadata, tag) + .split('\\') + .map((value) => Number(trimDicomPadding(value))); + +const detectorItems = (metadata: DicomDataset) => { + const values = findElement(metadata, DETECTOR_INFORMATION)?.values; + return values?.kind === 'sequence' ? values.items : []; +}; + +const spatialPointer = (metadata: DicomDataset) => { + const pointer = findElement(metadata, '00280009'); + if (!pointer) return true; + return ( + pointer.values.kind === 'attributeTag' && + pointer.values.values.length === 1 && + pointer.values.values[0].group === 0x0054 && + pointer.values.values[0].element === 0x0080 + ); +}; + +const singleDimension = (metadata: DicomDataset) => + [ + '00540011', + '00540031', + '00540051', + '00540061', + '00540071', + '00540101', + ].every((tag) => !text(metadata, tag) || number(metadata, tag) === 1); + +const singleDimensionVectors = (metadata: DicomDataset) => + [ + '00540010', + '00540020', + '00540030', + '00540050', + '00540060', + '00540070', + '00540100', + ].every( + (tag) => + !text(metadata, tag) || + vector(metadata, tag).every((value) => value === 1) + ); + +const orderedSlices = (metadata: DicomDataset, count: number) => { + const values = text(metadata, SLICE_VECTOR); + if (!values) return !findElement(metadata, '00280009'); + const slices = vector(metadata, SLICE_VECTOR); + return ( + slices.length === count && + slices.every((slice, index) => slice === index + 1) + ); +}; + +type NmReconstruction = + | { error: string } + | { detector: DicomDataset; count: number; sliceSpacing: number | null }; + +const dimensionError = ( + metadata: DicomDataset, + type: string, + count: number +) => { + if (!text(metadata, '00540081')) + return 'Cannot allocate NM volume without NumberOfSlices'; + return type !== 'RECON TOMO' || + count !== number(metadata, '00540081') || + !singleDimension(metadata) || + !singleDimensionVectors(metadata) || + !spatialPointer(metadata) + ? 'Unsupported NM volume with multiple spatial/time dimensions' + : null; +}; + +const detectorError = (metadata: DicomDataset, detectors: DicomDataset[]) => + number(metadata, '00540021') !== 1 || detectors.length !== 1 + ? 'Unsupported NM volume with multiple or missing detectors' + : null; + +function sliceError(metadata: DicomDataset, count: number) { + if ( + !Number.isSafeInteger(count) || + count <= 0 || + !orderedSlices(metadata, count) + ) + return 'Unsupported NM volume with unordered or missing slice indices'; + const spacing = number(metadata, '00180088'); + return !text(metadata, '00180088') || + (Number.isFinite(spacing) && spacing !== 0) + ? null + : 'Cannot allocate NM volume without nonzero slice spacing'; +} + +/** + * NM detector coordinates describe a volume only for a single reconstructed + * spatial stack. Projection and gated dimensions require their own assembly. + */ +export function readNmReconstruction( + metadata: DicomDataset +): NmReconstruction | null { + if (text(metadata, '00080016') !== NM_IMAGE_STORAGE) return null; + const imageType = text(metadata, '00080008').split('\\')[2]?.trim() ?? ''; + if (imageType !== 'RECON TOMO' && imageType !== 'RECON GATED TOMO') + return null; + const count = number(metadata, '00280008'); + const detectors = detectorItems(metadata); + const error = + dimensionError(metadata, imageType, count) ?? + detectorError(metadata, detectors) ?? + sliceError(metadata, count); + return error + ? { error } + : { + detector: detectors[0], + count, + sliceSpacing: text(metadata, '00180088') + ? number(metadata, '00180088') + : null, + }; +} + +export function getNmDetectorTag(metadata: DicomDataset, tag: string) { + if (tag !== '00200032' && tag !== '00200037') return undefined; + const reconstruction = readNmReconstruction(metadata); + return reconstruction && !('error' in reconstruction) + ? getDatasetTag(reconstruction.detector, tag) + : undefined; +} diff --git a/packages/dicom/core/metadata/readDicomDataset.worker.ts b/packages/dicom/core/metadata/readDicomDataset.worker.ts new file mode 100644 index 000000000..4446f9a64 --- /dev/null +++ b/packages/dicom/core/metadata/readDicomDataset.worker.ts @@ -0,0 +1,5 @@ +import * as Comlink from 'comlink'; +import { readDicomDataset } from './dicomDataset'; + +export type DicomDatasetWorker = { readDicomDataset: typeof readDicomDataset }; +Comlink.expose({ readDicomDataset }); diff --git a/packages/dicom/core/metadata/spatialMetadata.ts b/packages/dicom/core/metadata/spatialMetadata.ts new file mode 100644 index 000000000..e5406c490 --- /dev/null +++ b/packages/dicom/core/metadata/spatialMetadata.ts @@ -0,0 +1,70 @@ +import type { IrregularReason } from '../collections/reconstructVolume'; +import type { DicomDataset } from './dicomDataset'; +import { getFrameTag } from './functionalGroups'; +import { trimDicomPadding } from '../utils'; + +/** Describes the spacing actually used by the image, not independent calibration. */ +export type AxisSpacing = { + value: number; + unit: 'mm' | 'unknown'; + status: 'declared' | 'derived' | 'fallback'; + source: string; + reason?: string; +}; + +export type SpatialMetadata = { + /** Image index axes, in x/y/z order. */ + axes: [AxisSpacing, AxisSpacing, AxisSpacing]; + reconstruction?: { kind: 'regular' | 'irregular'; reason?: IrregularReason }; + notes: string[]; + calibration?: { type?: string; description?: string }; +}; + +export const physicalSpacing = ( + value: number, + source: string, + status: 'declared' | 'derived' = 'declared' +): AxisSpacing => ({ value, unit: 'mm', status, source }); + +export const fallbackSpacing = (reason: string): AxisSpacing => ({ + value: 1, + unit: 'unknown', + status: 'fallback', + source: 'Display default', + reason, +}); + +export function declaredSpacing(raw: string | undefined, source: string) { + const text = trimDicomPadding(raw ?? ''); + if (!text) return fallbackSpacing(`${source} is not supplied.`); + const value = Number(text); + return Number.isFinite(value) && value > 0 + ? physicalSpacing(value, source) + : fallbackSpacing(`${source} has no usable positive spacing.`); +} + +function singletonPixelSpacing(raw: string) { + const declared = declaredSpacing(raw, 'PixelSpacing'); + if (declared.status === 'fallback') return declared; + return { + ...fallbackSpacing( + 'PixelSpacing has only one value; square pixels are assumed for display.' + ), + value: declared.value, + source: 'Single PixelSpacing value', + }; +} + +/** Preserve a usable axis even when the other axis is missing or unusable. */ +export function readPixelSpacing(metadata: DicomDataset | null | undefined) { + const raw = trimDicomPadding(getFrameTag(metadata, '00280030') ?? ''); + const parts = raw ? raw.split('\\') : undefined; + if (parts && parts.length < 2) { + const assumed = singletonPixelSpacing(parts[0]); + return [assumed, { ...assumed }] as const; + } + return [ + declaredSpacing(parts?.[1], 'PixelSpacing'), + declaredSpacing(parts?.[0], 'PixelSpacing'), + ] as const; +} diff --git a/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts b/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts new file mode 100644 index 000000000..65367980f --- /dev/null +++ b/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import { + defaultDecoderTable, + planDecode, + wholeInstanceDecoderTable, +} from '../decoderTable'; +import { pixelInstance } from './pixelFixture'; + +describe('planDecode', () => { + it('plans native frames for an uncompressed instance it reproduces', async () => { + const { instance } = await pixelInstance({ frames: 3 }); + + const plan = planDecode(defaultDecoderTable, instance); + + expect(plan).toMatchObject({ + kind: 'frames', + format: { rows: 5, columns: 3, bitsAllocated: 16 }, + }); + expect(plan.kind === 'frames' && plan.index.frames).toHaveLength(3); + }); + + it('hands a declined uncompressed instance to the whole-instance decoder', async () => { + const { instance } = await pixelInstance({ photometric: 'MONOCHROME1' }); + + expect(planDecode(defaultDecoderTable, instance)).toEqual({ + kind: 'whole-instance', + reason: expect.stringMatching(/MONOCHROME1/), + }); + }); + + it.each([ + ['a codec GDCM provides', '1.2.840.10008.1.2.4.90'], + ['an unlisted transfer syntax', '1.2.3.4'], + ])('hands %s to the whole-instance decoder', async (_name, syntax) => { + const { instance } = await pixelInstance({ transferSyntaxUid: syntax }); + + expect(planDecode(defaultDecoderTable, instance)).toEqual({ + kind: 'whole-instance', + }); + }); + + it('names a known transfer syntax that has no decoder', async () => { + const { instance } = await pixelInstance({ + transferSyntaxUid: '1.2.840.10008.1.2.4.102', + }); + + const plan = planDecode(defaultDecoderTable, instance); + + expect(plan.kind === 'unsupported' && plan.error.message).toBe( + 'Known transfer syntax MPEG-4 AVC/H.264 High Profile (1.2.840.10008.1.2.4.102) has no decoder' + ); + }); + + it('leaves everything to an injected whole-instance decoder', async () => { + const { instance } = await pixelInstance(); + + expect(planDecode(wholeInstanceDecoderTable, instance)).toEqual({ + kind: 'whole-instance', + }); + }); +}); diff --git a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts new file mode 100644 index 000000000..2ac8379ee --- /dev/null +++ b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest'; +import { indexFrames } from '../frameIndex'; +import { fromBlob } from '../../source/byteSource'; +import { + EXPLICIT_BE, + EXPLICIT_LE, + IMPLICIT_LE, +} from '@/tests/nativePixelDicom'; +import { pixelInstance, withNumber } from './pixelFixture'; + +const words = Array.from({ length: 3 * 2 * 4 }, (_, index) => index * 257); + +const wordsIn = (bytes: Uint8Array, littleEndian: boolean) => { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length); + return Array.from({ length: bytes.length / 2 }, (_, index) => + view.getUint16(index * 2, littleEndian) + ); +}; + +describe('indexFrames', () => { + it.each([ + ['Explicit VR Little Endian', EXPLICIT_LE, 12, true], + ['Implicit VR Little Endian', IMPLICIT_LE, 8, true], + ['Explicit VR Big Endian', EXPLICIT_BE, 12, false], + ])( + 'locates every frame of %s Pixel Data', + async (_name, transferSyntaxUid, headLength, littleEndian) => { + const { bytes, instance } = await pixelInstance({ + transferSyntaxUid, + rows: 2, + columns: 3, + frames: 4, + words, + }); + + const index = indexFrames(instance); + + if (index.kind !== 'indexed') throw new Error(index.detail); + expect(instance.pixelData!.valueOffset).toBe( + instance.pixelData!.offset + headLength + ); + expect(index.littleEndian).toBe(littleEndian); + expect(index.frameLength).toBe(12); + expect(index.frames).toHaveLength(4); + const read = index.frames.flatMap(({ start, end }) => + wordsIn(bytes.subarray(start, end), littleEndian) + ); + expect(read).toEqual(words); + } + ); + + it.each([ + ['encapsulated', { transferSyntaxUid: '1.2.840.10008.1.2.4.50' }], + ['truncated', { extra: [{ tag: 0x00280008, vr: 'IS', value: '9' }] }], + ['invalid-shape', { extra: [{ tag: 0x00280008, vr: 'IS', value: '0' }] }], + ] as const)('reports %s Pixel Data as unindexed', async (reason, options) => { + const { instance } = await pixelInstance(options); + expect(indexFrames(instance)).toMatchObject({ kind: 'unindexed', reason }); + }); + + it('reports a file cut short after its header as truncated', async () => { + const { bytes, instance } = await pixelInstance({ + rows: 2, + columns: 3, + frames: 4, + words, + }); + const cut = fromBlob(new Blob([bytes.subarray(0, bytes.length - 12)])); + + expect(indexFrames({ ...instance, source: cut })).toMatchObject({ + kind: 'unindexed', + reason: 'truncated', + }); + }); + + it('reports samples packed across bytes as unindexed', async () => { + const { instance } = await pixelInstance(); + expect(indexFrames(withNumber(instance, '00280100', 1))).toMatchObject({ + kind: 'unindexed', + reason: 'packed-bits', + }); + }); + + it('reports an instance without Pixel Data as unindexed', () => { + expect( + indexFrames({ + source: { read: () => new ReadableStream() }, + dataset: { elements: [], specificCharacterSet: null }, + layout: null, + ultrasoundRegions: null, + transferSyntaxUid: EXPLICIT_LE, + pixelData: null, + }) + ).toMatchObject({ kind: 'unindexed', reason: 'no-pixel-data' }); + }); +}); diff --git a/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts b/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts new file mode 100644 index 000000000..a67bd3d0a --- /dev/null +++ b/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts @@ -0,0 +1,238 @@ +import { describe, expect, it } from 'vitest'; +import { + decodeNativeFrame, + nativeCapability, + type NativePixelFormat, +} from '../nativeFrame'; +import { EXPLICIT_BE, type DataElement } from '@/tests/nativePixelDicom'; +import { pixelInstance } from './pixelFixture'; + +const mono = (overrides: Partial): NativePixelFormat => ({ + rows: 1, + columns: 4, + samplesPerPixel: 1, + photometricInterpretation: 'MONOCHROME2', + planar: false, + bitsAllocated: 16, + bitsStored: 16, + highBit: 15, + signed: false, + littleEndian: true, + rescaleSlope: 1, + rescaleIntercept: 0, + ...overrides, +}); + +const littleEndian16 = (words: number[]) => + new Uint8Array(new Uint16Array(words).buffer); + +describe('decodeNativeFrame', () => { + it('masks bits above Bits Stored and sign-extends from the high bit', () => { + const format = mono({ bitsStored: 12, highBit: 11, signed: true }); + const bytes = littleEndian16([0xf7ff, 0x0800, 0x1fff, 0xa001]); + + const { samples, range } = decodeNativeFrame(bytes, format, Int16Array); + + expect(Array.from(samples)).toEqual([2047, -2048, -1, 1]); + expect(range).toEqual([[-2048, 2047]]); + }); + + it('reads unsigned and 32 bit words whole', () => { + const unsigned = decodeNativeFrame( + littleEndian16([0xf123, 0, 1, 0xffff]), + mono({ bitsStored: 12, highBit: 11 }), + Uint16Array + ); + const words32 = new Uint8Array(new Uint32Array([0xffffffff, 7]).buffer); + const signed32 = decodeNativeFrame( + words32, + mono({ + columns: 2, + bitsAllocated: 32, + bitsStored: 32, + highBit: 31, + signed: true, + }), + Int32Array + ); + const unsigned32 = decodeNativeFrame( + words32, + mono({ columns: 2, bitsAllocated: 32, bitsStored: 32, highBit: 31 }), + Uint32Array + ); + + expect(Array.from(unsigned.samples)).toEqual([0x123, 0, 1, 0xfff]); + expect(Array.from(signed32.samples)).toEqual([-1, 7]); + expect(Array.from(unsigned32.samples)).toEqual([4294967295, 7]); + }); + + it('reads big endian words, from any byte offset', () => { + const file = new Uint8Array([ + 0xff, 0x01, 0x02, 0x80, 0x00, 0, 0, 0xff, 0xff, + ]); + + const { samples } = decodeNativeFrame( + file.subarray(1), + mono({ littleEndian: false, signed: true }), + Int16Array + ); + + expect(Array.from(samples)).toEqual([0x0102, -32768, 0, -1]); + }); + + it('interleaves planar colour and ranges each component', () => { + const planes = new Uint8Array([1, 2, 30, 40, 250, 200]); + + const { samples, range } = decodeNativeFrame( + planes, + mono({ + columns: 2, + samplesPerPixel: 3, + photometricInterpretation: 'RGB', + planar: true, + bitsAllocated: 8, + bitsStored: 8, + highBit: 7, + }), + Uint8Array + ); + + expect(Array.from(samples)).toEqual([1, 30, 250, 2, 40, 200]); + expect(range).toEqual([ + [1, 2], + [30, 40], + [200, 250], + ]); + }); + + it('applies the modality rescale and ranges values before storing them', () => { + const bytes = littleEndian16([3, 0, 1, 600]); + + const fractional = decodeNativeFrame( + bytes, + mono({ rescaleSlope: 0.5, rescaleIntercept: -0.25 }), + Float64Array + ); + const narrow = decodeNativeFrame(bytes, mono({}), Uint8Array); + + expect(Array.from(fractional.samples)).toEqual([1.25, -0.25, 0.25, 299.75]); + expect(narrow.range).toEqual([[0, 600]]); + }); + + it('rounds a fractional rescale into a Float32 volume as GDCM samples are', () => { + const format = mono({ rescaleSlope: 0.1, rescaleIntercept: 0.3 }); + + const { samples, range } = decodeNativeFrame( + littleEndian16([3, 0, 1, 600]), + format, + Float32Array + ); + + const exact = [3, 0, 1, 600].map((stored) => stored * 0.1 + 0.3); + expect(Array.from(samples)).toEqual(exact.map(Math.fround)); + expect(range).toEqual([[Math.min(...exact), Math.max(...exact)]]); + }); + + it('rejects a frame shorter than its format', () => { + expect(() => + decodeNativeFrame(new Uint8Array(6), mono({}), Uint16Array) + ).toThrow('A frame needs 8 bytes of Pixel Data; 6 were read'); + }); +}); + +const element = (tag: number, vr: string, value: string | number[]) => + ({ tag, vr, value }) as DataElement; + +describe('nativeCapability', () => { + it.each([ + ['signed 12 bit monochrome', { bitsStored: 12, pixelRepresentation: 1 }], + [ + '8 bit RGB', + { samplesPerPixel: 3, bitsAllocated: 8, planarConfiguration: 1 }, + ], + ['32 bit words', { bitsAllocated: 32 }], + ['big endian 16 bit words', { transferSyntaxUid: EXPLICIT_BE }], + [ + 'a uniform per-frame rescale', + { + frames: 2, + frameRescales: [ + [2, 1], + [2, 1], + ], + }, + ], + ['Pixel Padding Value', { extra: [element(0x00280120, 'US', [0])] }], + ] as const)('decodes %s natively', async (_name, options) => { + const { instance } = await pixelInstance(options); + expect( + nativeCapability(instance, !('transferSyntaxUid' in options)) + ).toMatchObject({ + kind: 'native', + }); + }); + + it.each([ + [ + 'MONOCHROME1, which GDCM inverts', + { photometric: 'MONOCHROME1' }, + /MONOCHROME1/, + ], + [ + 'YBR colour', + { samplesPerPixel: 3, bitsAllocated: 8, photometric: 'YBR_FULL' }, + /YBR_FULL/, + ], + [ + 'palette colour', + { bitsAllocated: 8, photometric: 'PALETTE COLOR' }, + /PALETTE COLOR/, + ], + [ + '8 bit words with unstored bits, which GDCM keeps', + { bitsAllocated: 8, bitsStored: 6 }, + /6 of 8/, + ], + [ + '32 bit words with unstored bits', + { bitsAllocated: 32, bitsStored: 24 }, + /24 of 32/, + ], + ['a shifted high bit', { bitsStored: 12, highBit: 14 }, /High Bit 14/], + [ + 'big endian 8 bit words', + { transferSyntaxUid: EXPLICIT_BE, bitsAllocated: 8 }, + /Big endian 8/, + ], + ['16 bit RGB', { samplesPerPixel: 3 }, /RGB/], + [ + 'rescaled RGB', + { samplesPerPixel: 3, bitsAllocated: 8, rescale: [2, 0] }, + /RGB/, + ], + [ + 'differing per-frame rescale', + { + frames: 2, + frameRescales: [ + [1, 0], + [2, 0], + ], + }, + /differing modality rescale/, + ], + ['overlay planes', { extra: [element(0x60000100, 'US', [1])] }, /Overlay/], + [ + 'a Modality LUT', + { extra: [element(0x00283000, 'SQ', [])] }, + /Modality LUT/, + ], + ] as const)('declines %s', async (_name, options, reason) => { + const { instance } = await pixelInstance(options); + const littleEndian = !('transferSyntaxUid' in options); + expect(nativeCapability(instance, littleEndian)).toEqual({ + kind: 'declined', + reason: expect.stringMatching(reason), + }); + }); +}); diff --git a/packages/dicom/core/pixels/__tests__/pixelFixture.ts b/packages/dicom/core/pixels/__tests__/pixelFixture.ts new file mode 100644 index 000000000..a2df5c889 --- /dev/null +++ b/packages/dicom/core/pixels/__tests__/pixelFixture.ts @@ -0,0 +1,33 @@ +import { readInstance, type Instance } from '../../instance/readInstance'; +import { fromBlob } from '../../source/byteSource'; +import { + nativePixelDicom, + type NativePixelOptions, +} from '@/tests/nativePixelDicom'; + +/** An instance read from a synthesized file, as the runtime would read it. */ +export async function pixelInstance(options: NativePixelOptions = {}) { + const bytes = nativePixelDicom(options); + const instance = await readInstance( + fromBlob(new Blob([bytes as Uint8Array])), + new AbortController().signal + ); + return { bytes, instance }; +} + +/** The same instance with one numeric header value replaced. */ +export const withNumber = ( + instance: Instance, + tag: string, + value: number +): Instance => ({ + ...instance, + dataset: { + ...instance.dataset, + elements: instance.dataset.elements.map((element) => + element.tag === tag + ? { ...element, values: { kind: 'number', values: [value] } } + : element + ), + }, +}); diff --git a/packages/dicom/core/pixels/decoderTable.ts b/packages/dicom/core/pixels/decoderTable.ts new file mode 100644 index 000000000..8b8581b42 --- /dev/null +++ b/packages/dicom/core/pixels/decoderTable.ts @@ -0,0 +1,128 @@ +import type { Instance } from '../instance/readInstance'; +import { indexFrames, type FrameIndex } from './frameIndex'; +import { + decodeNativeFrame, + nativeCapability, + type NativePixelFormat, +} from './nativeFrame'; + +/** + * How one transfer syntax decodes: per frame without a codec, as a whole + * instance by the runtime's decoder, or not at all. + */ +export type DecoderEntry = + | Readonly<{ + kind: 'native'; + name: string; + capability: typeof nativeCapability; + decode: typeof decodeNativeFrame; + }> + | Readonly<{ kind: 'whole-instance'; name: string }> + | Readonly<{ kind: 'unsupported'; name: string }>; + +export type DecoderTable = Readonly<{ + byTransferSyntax: ReadonlyMap; + /** For transfer syntaxes the table does not list. */ + fallback: DecoderEntry; +}>; + +const native = (name: string): DecoderEntry => ({ + kind: 'native', + name, + capability: nativeCapability, + decode: decodeNativeFrame, +}); +const wholeInstance = (name: string): DecoderEntry => ({ + kind: 'whole-instance', + name, +}); +const unsupported = (name: string): DecoderEntry => ({ + kind: 'unsupported', + name, +}); + +// prettier-ignore +const ENTRIES: Array<[string, DecoderEntry]> = [ + ['1.2.840.10008.1.2', native('Implicit VR Little Endian')], + ['1.2.840.10008.1.2.1', native('Explicit VR Little Endian')], + ['1.2.840.10008.1.2.2', native('Explicit VR Big Endian')], + ['1.2.840.10008.1.2.1.99', wholeInstance('Deflated Explicit VR Little Endian')], + ['1.2.840.10008.1.2.4.50', wholeInstance('JPEG Baseline')], + ['1.2.840.10008.1.2.4.51', wholeInstance('JPEG Extended')], + ['1.2.840.10008.1.2.4.57', wholeInstance('JPEG Lossless')], + ['1.2.840.10008.1.2.4.70', wholeInstance('JPEG Lossless, First-Order Prediction')], + ['1.2.840.10008.1.2.4.80', wholeInstance('JPEG-LS Lossless')], + ['1.2.840.10008.1.2.4.81', wholeInstance('JPEG-LS Near-Lossless')], + ['1.2.840.10008.1.2.4.90', wholeInstance('JPEG 2000 Lossless')], + ['1.2.840.10008.1.2.4.91', wholeInstance('JPEG 2000')], + ['1.2.840.10008.1.2.5', wholeInstance('RLE Lossless')], + ['1.2.840.10008.1.2.4.94', unsupported('JPIP Referenced')], + ['1.2.840.10008.1.2.4.95', unsupported('JPIP Referenced Deflate')], + ['1.2.840.10008.1.2.4.100', unsupported('MPEG2 Main Profile')], + ['1.2.840.10008.1.2.4.101', unsupported('MPEG2 High Profile')], + ['1.2.840.10008.1.2.4.102', unsupported('MPEG-4 AVC/H.264 High Profile')], + ['1.2.840.10008.1.2.4.103', unsupported('MPEG-4 AVC/H.264 BD-compatible High Profile')], + ['1.2.840.10008.1.2.4.104', unsupported('MPEG-4 AVC/H.264 High Profile For 2D Video')], + ['1.2.840.10008.1.2.4.105', unsupported('MPEG-4 AVC/H.264 High Profile For 3D Video')], + ['1.2.840.10008.1.2.4.106', unsupported('MPEG-4 AVC/H.264 Stereo High Profile')], + ['1.2.840.10008.1.2.4.107', unsupported('HEVC/H.265 Main Profile')], + ['1.2.840.10008.1.2.4.108', unsupported('HEVC/H.265 Main 10 Profile')], + ['1.2.840.10008.1.2.4.110', unsupported('JPEG XL Lossless')], + ['1.2.840.10008.1.2.4.111', unsupported('JPEG XL JPEG Recompression')], + ['1.2.840.10008.1.2.4.112', unsupported('JPEG XL')], +]; + +/** Native syntaxes per frame; GDCM for every other syntax it may know. */ +export const defaultDecoderTable: DecoderTable = { + byTransferSyntax: new Map(ENTRIES), + fallback: wholeInstance('Unlisted transfer syntax'), +}; + +/** Hands every instance to the runtime's whole-instance decoder. */ +export const wholeInstanceDecoderTable: DecoderTable = { + byTransferSyntax: new Map(), + fallback: wholeInstance('Whole-instance decoder'), +}; + +type IndexedFrames = Extract; + +export type DecodePlan = + | Readonly<{ + kind: 'frames'; + index: IndexedFrames; + format: NativePixelFormat; + decode: typeof decodeNativeFrame; + }> + /** `reason` says why a native syntax still needs the whole instance. */ + | Readonly<{ kind: 'whole-instance'; reason?: string }> + | Readonly<{ kind: 'unsupported'; error: Error }>; + +/** How `instance` should decode under `table`. Pure: reads only the header. */ +export function planDecode( + table: DecoderTable, + instance: Instance +): DecodePlan { + const syntax = instance.transferSyntaxUid; + const entry = + (syntax && table.byTransferSyntax.get(syntax)) || table.fallback; + if (entry.kind === 'unsupported') + return { + kind: 'unsupported', + error: new Error( + `Known transfer syntax ${entry.name} (${syntax}) has no decoder` + ), + }; + if (entry.kind === 'whole-instance') return { kind: 'whole-instance' }; + const index = indexFrames(instance); + if (index.kind === 'unindexed') + return { kind: 'whole-instance', reason: index.detail }; + const capability = entry.capability(instance, index.littleEndian); + if (capability.kind === 'declined') + return { kind: 'whole-instance', reason: capability.reason }; + return { + kind: 'frames', + index, + format: capability.format, + decode: entry.decode, + }; +} diff --git a/packages/dicom/core/pixels/frameIndex.ts b/packages/dicom/core/pixels/frameIndex.ts new file mode 100644 index 000000000..4b9031392 --- /dev/null +++ b/packages/dicom/core/pixels/frameIndex.ts @@ -0,0 +1,123 @@ +import type { Instance } from '../instance/readInstance'; +import type { ByteRange } from '../source/byteSource'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, +} from '../metadata/dicomLayout'; +import { numberOr } from '../utils'; + +export const EXPLICIT_VR_BIG_ENDIAN = '1.2.840.10008.1.2.2'; +export const DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1.99'; + +/** Transfer syntaxes whose Pixel Data is a plain run of fixed-size frames. */ +export const NATIVE_ENCODINGS: ReadonlyMap = + new Map([ + [IMPLICIT_VR_LITTLE_ENDIAN, { littleEndian: true }], + [EXPLICIT_VR_LITTLE_ENDIAN, { littleEndian: true }], + [EXPLICIT_VR_BIG_ENDIAN, { littleEndian: false }], + ]); + +export type UnindexedReason = + | 'no-pixel-data' + | 'deflated' + | 'encapsulated' + | 'packed-bits' + | 'invalid-shape' + | 'truncated'; + +/** + * Where each frame's bytes live. Only native encodings are indexed today; an + * encapsulated index (offset tables, then a fragment scan) would add an + * `encoding: 'encapsulated'` variant whose frames list fragment ranges. + */ +export type FrameIndex = + | Readonly<{ + kind: 'indexed'; + encoding: 'native'; + littleEndian: boolean; + frameLength: number; + frames: readonly ByteRange[]; + }> + | Readonly<{ kind: 'unindexed'; reason: UnindexedReason; detail: string }>; + +const unindexed = (reason: UnindexedReason, detail: string): FrameIndex => ({ + kind: 'unindexed', + reason, + detail, +}); + +const shapeOf = (instance: Instance) => { + const valueOf = (tag: string) => + numberOr(getDatasetTag(instance.dataset, tag), NaN); + return { + rows: valueOf('00280010'), + columns: valueOf('00280011'), + samplesPerPixel: numberOr(getDatasetTag(instance.dataset, '00280002'), 1), + bitsAllocated: valueOf('00280100'), + frames: numberOr(getDatasetTag(instance.dataset, '00280008'), 1), + }; +}; + +const positiveInteger = (value: number) => + Number.isSafeInteger(value) && value > 0; + +// A file cut short after its header would otherwise fail once per frame. +const truncation = ( + needed: number, + held: number, + end: number, + size: number | undefined +) => { + if (needed > held) + return `Pixel Data holds ${held} bytes; its frames need ${needed}`; + return size !== undefined && end > size + ? `The file holds ${size} bytes; its frames end at byte ${end}` + : null; +}; + +/** Byte ranges of every frame, from the header alone. */ +export function indexFrames(instance: Instance): FrameIndex { + const { pixelData, transferSyntaxUid } = instance; + if (!pixelData || !transferSyntaxUid) + return unindexed('no-pixel-data', 'The header locates no Pixel Data'); + if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) + return unindexed('deflated', 'The whole data set is deflated'); + const encoding = NATIVE_ENCODINGS.get(transferSyntaxUid); + if (!encoding || pixelData.length === null) + return unindexed( + 'encapsulated', + `Transfer syntax ${transferSyntaxUid} is not indexable without a codec` + ); + const { rows, columns, samplesPerPixel, bitsAllocated, frames } = + shapeOf(instance); + if (![rows, columns, samplesPerPixel, frames].every(positiveInteger)) + return unindexed( + 'invalid-shape', + 'Rows, Columns, Samples per Pixel or Number of Frames is unusable' + ); + if (!positiveInteger(bitsAllocated) || bitsAllocated % 8 !== 0) + return unindexed( + 'packed-bits', + `Bits Allocated ${bitsAllocated} packs samples across bytes` + ); + const frameLength = rows * columns * samplesPerPixel * (bitsAllocated / 8); + const needed = frameLength * frames; + const truncated = truncation( + needed, + pixelData.length, + pixelData.valueOffset + needed, + instance.source.size + ); + if (truncated) return unindexed('truncated', truncated); + return { + kind: 'indexed', + encoding: 'native', + littleEndian: encoding.littleEndian, + frameLength, + frames: Array.from({ length: frames }, (_, frame) => { + const start = pixelData.valueOffset + frame * frameLength; + return { start, end: start + frameLength }; + }), + }; +} diff --git a/packages/dicom/core/pixels/nativeFrame.ts b/packages/dicom/core/pixels/nativeFrame.ts new file mode 100644 index 000000000..a8de1696f --- /dev/null +++ b/packages/dicom/core/pixels/nativeFrame.ts @@ -0,0 +1,236 @@ +import type { Instance } from '../instance/readInstance'; +import type { DicomDataset } from '../metadata/dicomDataset'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { + hasUniformModalityRescale, + readModalityRescale, +} from '../metadata/modalityRescale'; +import { numberOr, trimDicomPadding } from '../utils'; +import type { VolumeBufferConstructor } from '../volume/pixelFormat'; + +/** What decides how one native frame's bytes become samples. */ +export type NativePixelFormat = Readonly<{ + rows: number; + columns: number; + samplesPerPixel: number; + photometricInterpretation: string; + /** Color planes stored one after another rather than interleaved. */ + planar: boolean; + bitsAllocated: number; + bitsStored: number; + highBit: number; + signed: boolean; + littleEndian: boolean; + rescaleSlope: number; + rescaleIntercept: number; +}>; + +export type NativeCapability = + | Readonly<{ kind: 'native'; format: NativePixelFormat }> + | Readonly<{ kind: 'declined'; reason: string }>; + +const text = (dataset: DicomDataset, tag: string) => + trimDicomPadding(getDatasetTag(dataset, tag) ?? ''); + +const number = (dataset: DicomDataset, tag: string) => + numberOr(getDatasetTag(dataset, tag), NaN); + +/** The header's pixel description, read without judging it. */ +export function readNativePixelFormat( + instance: Instance, + littleEndian: boolean +): NativePixelFormat { + const { dataset } = instance; + const { rescaleSlope, rescaleIntercept } = readModalityRescale(dataset); + return { + rows: number(dataset, '00280010'), + columns: number(dataset, '00280011'), + samplesPerPixel: numberOr(getDatasetTag(dataset, '00280002'), 1), + photometricInterpretation: text(dataset, '00280004'), + planar: number(dataset, '00280006') === 1, + bitsAllocated: number(dataset, '00280100'), + bitsStored: number(dataset, '00280101'), + highBit: number(dataset, '00280102'), + signed: number(dataset, '00280103') === 1, + littleEndian, + rescaleSlope, + rescaleIntercept, + }; +} + +const isOverlayOrCurve = (group: number) => + (group >= 0x5000 && group <= 0x501e) || (group >= 0x6000 && group <= 0x601e); + +/** Header elements whose effect on GDCM's output is not reproduced here. */ +const UNREPRODUCED_ELEMENTS = new Map([ + ['00283000', 'Modality LUT Sequence'], + ['00281101', 'Red Palette Color Lookup Table Descriptor'], + ['00282000', 'ICC Profile'], +]); + +const declinePhotometric = (format: NativePixelFormat) => { + const { samplesPerPixel, photometricInterpretation } = format; + const monochrome2 = + samplesPerPixel === 1 && photometricInterpretation === 'MONOCHROME2'; + const rgb = samplesPerPixel === 3 && photometricInterpretation === 'RGB'; + return monochrome2 || rgb + ? null + : `${photometricInterpretation || 'Unknown'} photometric interpretation with ${samplesPerPixel} samples per pixel`; +}; + +const declineBits = ({ + bitsAllocated, + bitsStored, + highBit, +}: NativePixelFormat) => { + if (![8, 16, 32].includes(bitsAllocated)) + return `Bits Allocated ${bitsAllocated}`; + const valid = + Number.isInteger(bitsStored) && + bitsStored >= 1 && + bitsStored <= bitsAllocated && + highBit === bitsStored - 1; + if (!valid) return `Bits Stored ${bitsStored} with High Bit ${highBit}`; + return bitsAllocated !== 16 && bitsStored < bitsAllocated + ? `${bitsStored} of ${bitsAllocated} allocated bits stored` + : null; +}; + +const declineByteOrder = ({ + littleEndian, + bitsAllocated, +}: NativePixelFormat) => + littleEndian || bitsAllocated === 16 + ? null + : `Big endian ${bitsAllocated} bit samples`; + +const declineRescale = (format: NativePixelFormat) => { + const { rescaleSlope: slope, rescaleIntercept: intercept } = format; + if (!Number.isFinite(slope) || !Number.isFinite(intercept)) + return 'Non-numeric modality rescale'; + const rgb = format.samplesPerPixel === 3; + const plain = format.bitsAllocated === 8 && !format.signed; + return rgb && !(plain && slope === 1 && intercept === 0) + ? 'RGB samples that are not unsigned 8 bit and unscaled' + : null; +}; + +// Each case was compared with GDCM in a browser: MONOCHROME1 comes back +// inverted, 8 bit words keep bits above Bits Stored, 32 bit words with fewer +// stored bits do not decode, and big endian words other than 16 bit are read +// as 16 bit pairs. Palette and YBR colour are not reproduced here. +const declineFormat = (format: NativePixelFormat) => + declinePhotometric(format) ?? + declineBits(format) ?? + declineByteOrder(format) ?? + declineRescale(format); + +function declineDataset(dataset: DicomDataset) { + if (!hasUniformModalityRescale(dataset)) + return 'Frames with differing modality rescale'; + const element = dataset.elements.find( + ({ tag, group }) => + UNREPRODUCED_ELEMENTS.has(tag) || isOverlayOrCurve(group) + ); + if (element) + return isOverlayOrCurve(element.group) + ? 'Overlay or curve data, which may share the pixel words' + : UNREPRODUCED_ELEMENTS.get(element.tag)!; + return null; +} + +/** + * Whether GDCM's output for this instance is reproduced exactly here. Every + * declined case keeps the whole-instance GDCM decode. + */ +export function nativeCapability( + instance: Instance, + littleEndian: boolean +): NativeCapability { + const format = readNativePixelFormat(instance, littleEndian); + const reason = declineFormat(format) ?? declineDataset(instance.dataset); + return reason ? { kind: 'declined', reason } : { kind: 'native', format }; +} + +/** Stored words as unsigned integers, viewed in place where alignment allows. */ +function storedWords( + bytes: Uint8Array, + format: NativePixelFormat, + count: number +) { + const { bitsAllocated, littleEndian } = format; + if (bitsAllocated === 8) return bytes.subarray(0, count); + const size = bitsAllocated / 8; + const Words = bitsAllocated === 16 ? Uint16Array : Uint32Array; + const platformLittleEndian = + new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + if (littleEndian === platformLittleEndian && bytes.byteOffset % size === 0) + return new Words(bytes.buffer as ArrayBuffer, bytes.byteOffset, count); + const view = new DataView(bytes.buffer, bytes.byteOffset, count * size); + const words = new Words(count); + for (let index = 0; index < count; index += 1) + words[index] = + size === 2 + ? view.getUint16(index * 2, littleEndian) + : view.getUint32(index * 4, littleEndian); + return words; +} + +/** Maps a stored word to its rescaled value. */ +function storedValue(format: NativePixelFormat) { + const { bitsStored, bitsAllocated, signed } = format; + const { rescaleSlope: slope, rescaleIntercept: intercept } = format; + // Bits Stored is below 32 when masking, so the bitwise result is nonnegative. + const mask = bitsStored < bitsAllocated ? 2 ** bitsStored - 1 : -1; + const signBit = signed ? 2 ** (bitsStored - 1) : Infinity; + const wrap = 2 ** bitsStored; + const stored = (word: number) => { + const value = mask === -1 ? word : word & mask; + return value >= signBit ? value - wrap : value; + }; + return slope === 1 && intercept === 0 + ? stored + : (word: number) => stored(word) * slope + intercept; +} + +/** + * Decodes one native frame into interleaved, modality-rescaled samples of the + * given element type. `range` is each component's [min, max] before the + * values are stored, so a caller can reject values `Target` cannot hold. + */ +export function decodeNativeFrame( + bytes: Uint8Array, + format: NativePixelFormat, + Target: VolumeBufferConstructor +) { + const { rows, columns, samplesPerPixel: components, planar } = format; + const pixels = rows * columns; + const count = pixels * components; + const frameLength = count * (format.bitsAllocated / 8); + if (bytes.length < frameLength) + throw new Error( + `A frame needs ${frameLength} bytes of Pixel Data; ${bytes.length} were read` + ); + const words = storedWords(bytes, format, count); + const valueOf = storedValue(format); + const samples = new Target(count); + const min = new Array(components).fill(Infinity); + const max = new Array(components).fill(-Infinity); + for (let component = 0; component < components; component += 1) { + for (let pixel = 0; pixel < pixels; pixel += 1) { + const source = planar + ? component * pixels + pixel + : pixel * components + component; + const value = valueOf(words[source]); + samples[pixel * components + component] = value; + if (value < min[component]) min[component] = value; + if (value > max[component]) max[component] = value; + } + } + return { + samples, + range: min.map( + (low, component) => [low, max[component]] as [number, number] + ), + }; +} diff --git a/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts b/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts new file mode 100644 index 000000000..cd59d41ad --- /dev/null +++ b/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest'; +import { createDicomRuntime } from '../createDicomRuntime'; +import { readDicomDataset } from '../../metadata/dicomDataset'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { enhancedFixtureBytes } from '@/tests/fixtures/dicom-consumer/enhancedFixtures'; + +const assets = { + pipelineWorkerUrl: '/unused-worker.js', + imageIOUrl: '/unused-image-io', +}; + +describe('Default DICOM decoder calibration', () => { + it('rejects varying frame transforms before invoking GDCM', async () => { + const bytes = enhancedFixtureBytes({ + pixelValues: [2, 2], + transforms: [ + [1, 0], + [2, 0], + ], + }); + const runtime = createDicomRuntime({ assets, decodeConcurrency: 1 }); + try { + await expect( + runtime.decode( + { instance: instanceFor(readDicomDataset(bytes)), bytes }, + new AbortController().signal + ) + ).rejects.toThrow('differing modality rescale'); + } finally { + runtime.dispose(); + } + }); +}); diff --git a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts new file mode 100644 index 000000000..a00fb1fe4 --- /dev/null +++ b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from 'vitest'; +import { + createDicomRuntime, + defaultDecodeConcurrency, + type PixelDecoder, +} from '../createDicomRuntime'; +import { defer } from '../../utils'; +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { fromBlob } from '../../source/byteSource'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { sliceDataset } from '../../collections/__tests__/sliceFixture'; +import { syntheticSlice } from '@/tests/dicomSourceFixtures'; + +const request = () => ({ + instance: instanceFor(sliceDataset()), + bytes: new Uint8Array(1), +}); +const decodedImage = { + size: [1, 1, 1], + data: new Uint16Array(1), + imageType: { components: 1 }, +}; +const signal = () => new AbortController().signal; + +describe('DICOM runtime', () => { + it.each([ + [undefined, 1], + [1, 1], + [6, 3], + [32, 4], + ])( + 'defaults to bounded decode concurrency for %s cores', + (cores, expected) => { + expect(defaultDecodeConcurrency(cores)).toBe(expected); + } + ); + + it('runs at most decodeConcurrency decodes at once', async () => { + let active = 0; + let peak = 0; + const gate = defer(); + const twoStarted = defer(); + const decoder: PixelDecoder = async () => { + active += 1; + peak = Math.max(peak, active); + if (active === 2) twoStarted.resolve(); + await gate.promise; + active -= 1; + return decodedImage; + }; + const runtime = createDicomRuntime({ decoder, decodeConcurrency: 2 }); + + const decodes = [0, 1, 2].map(() => runtime.decode(request(), signal())); + await twoStarted.promise; + gate.resolve(); + await Promise.all(decodes); + + expect(peak).toBe(2); + runtime.dispose(); + }); + + it('settles running and queued work when disposed', async () => { + const decoder: PixelDecoder = () => new Promise(() => {}); + const runtime = createDicomRuntime({ decoder, decodeConcurrency: 1 }); + + const running = runtime.decode(request(), signal()); + const queued = runtime.decode(request(), signal()); + runtime.dispose(); + + await expect(running).rejects.toMatchObject({ name: 'AbortError' }); + await expect(queued).rejects.toMatchObject({ name: 'AbortError' }); + await expect( + runtime.readInstance(fromBlob(new Blob([])), signal()) + ).rejects.toMatchObject({ name: 'AbortError' }); + }); + + it('settles a decode whose signal aborts', async () => { + const runtime = createDicomRuntime({ + decoder: () => new Promise(() => {}), + }); + const controller = new AbortController(); + + const decoding = runtime.decode(request(), controller.signal); + controller.abort(new DOMException('stop', 'AbortError')); + + await expect(decoding).rejects.toMatchObject({ name: 'AbortError' }); + runtime.dispose(); + }); + + it('reads instances with its own metadata reader', async () => { + const runtime = createDicomRuntime(); + const bytes = syntheticSlice({ patientName: 'DOE^JOHN' }); + + const instance = await runtime.readInstance( + fromBlob(new Blob([bytes as BlobPart])), + signal() + ); + + expect(getDatasetTag(instance.dataset, '00100010')).toBe('DOE^JOHN'); + await expect(runtime.decode(request(), signal())).rejects.toThrow( + 'Provide DICOM decoder assets or a decoder' + ); + runtime.dispose(); + }); +}); diff --git a/packages/dicom/core/runtime/createDicomRuntime.ts b/packages/dicom/core/runtime/createDicomRuntime.ts new file mode 100644 index 000000000..81efc5be8 --- /dev/null +++ b/packages/dicom/core/runtime/createDicomRuntime.ts @@ -0,0 +1,204 @@ +import type { ByteSource } from '../source/byteSource'; +import { readInstance, type Instance } from '../instance/readInstance'; +import type { ImageImportPolicy } from '../streaming/dicom/readDicomHeader'; +import { RequestPool } from '../streaming/requestPool'; +import { assertUniformModalityRescale } from '../metadata/modalityRescale'; +import { abortError, linkedController, untilAborted } from '../utils/abort'; +import { + createMetadataReader, + type MetadataReaderOptions, +} from './metadataReader'; +import { + defaultDecoderTable, + wholeInstanceDecoderTable, + type DecoderTable, +} from '../pixels/decoderTable'; +import { + createGdcmLane, + type DecodedDicomImage, + type DicomAssets, +} from './decoder'; + +/** The unit handed to a decoder: one whole instance and all of its bytes. */ +export type DecodeRequest = { instance: Instance; bytes: Uint8Array }; + +/** Returned pixels belong to the caller; `bytes` may be transferred away. */ +export type PixelDecoder = ( + request: DecodeRequest, + signal: AbortSignal +) => Promise; + +export type DicomRuntimeOptions = MetadataReaderOptions & { + fetch?: typeof fetch; + requestConcurrency?: number; + assets?: DicomAssets; + /** Replaces the GDCM decoder; it owns its own resources. */ + decoder?: PixelDecoder; + /** + * Which transfer syntaxes decode natively per frame. Defaults to native + * frames for uncompressed syntaxes, or, with a supplied `decoder`, to that + * decoder for everything. + */ + decoders?: DecoderTable; + /** Concurrent decodes. Each GDCM worker carries its own WASM heap. */ + decodeConcurrency?: number; + imageImportPolicy?: ImageImportPolicy; +}; + +const MAX_DEFAULT_DECODERS = 4; + +/** Half the cores, at least one and at most four, so WASM heaps stay bounded. */ +export const defaultDecodeConcurrency = ( + hardwareConcurrency: number | undefined +) => + Math.max( + 1, + Math.min(MAX_DEFAULT_DECODERS, Math.floor((hardwareConcurrency || 2) / 2)) + ); + +/** 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 }; +} + +function gdcmDecoder(assets: DicomAssets, count: number) { + const lanes = Array.from({ length: count }, () => createGdcmLane(assets)); + const decodeOn = async ( + index: number, + { instance, bytes }: DecodeRequest, + signal: AbortSignal + ) => { + signal.throwIfAborted(); + assertUniformModalityRescale(instance.dataset); + const lane = lanes[index]; + // 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)).image; + } finally { + signal.removeEventListener('abort', stop); + } + }; + const dispose = (reason: unknown) => + lanes.forEach((lane) => lane.reset(reason)); + return { decodeOn, dispose }; +} + +const missingDecoder = async (): Promise => { + throw new Error('Provide DICOM decoder assets or a decoder'); +}; + +/** + * Owns the request pool, the metadata workers and the decode pool. 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 = {}) { + const decodeConcurrency = + options.decodeConcurrency ?? + defaultDecodeConcurrency(globalThis.navigator?.hardwareConcurrency); + if (!Number.isInteger(decodeConcurrency) || decodeConcurrency < 1) + throw new Error('Decode concurrency must be a positive integer'); + const lifetime = new AbortController(); + const requests = new RequestPool(options.requestConcurrency, options.fetch); + const metadata = createMetadataReader(options); + const slots = createSlots(decodeConcurrency); + const gdcm = + options.assets && !options.decoder + ? gdcmDecoder(options.assets, decodeConcurrency) + : null; + const decodeOn = ( + index: number, + request: DecodeRequest, + signal: AbortSignal + ) => + gdcm + ? gdcm.decodeOn(index, request, signal) + : (options.decoder ?? missingDecoder)(request, signal); + + const withLifetime = async ( + signal: AbortSignal, + run: (linked: AbortSignal) => Promise + ) => { + const { controller, release } = linkedController(signal, lifetime.signal); + try { + return await untilAborted(run(controller.signal), controller.signal); + } finally { + release(); + } + }; + + const decode = (request: DecodeRequest, signal: AbortSignal) => + withLifetime(signal, async (linked) => { + const index = await slots.acquire(linked); + try { + return await decodeOn(index, request, linked); + } finally { + slots.release(index); + } + }); + + const read = (source: ByteSource, signal: AbortSignal) => + withLifetime(signal, (linked) => + readInstance(source, linked, { + readDataset: metadata.read, + imageImportPolicy: options.imageImportPolicy, + }) + ); + + const dispose = () => { + if (lifetime.signal.aborted) return; + const reason = abortError('DICOM runtime disposed'); + lifetime.abort(reason); + requests.dispose(); + metadata.dispose(); + gdcm?.dispose(reason); + }; + + return { + /** Pooled fetch for `fromUrl` sources; disposal aborts its requests. */ + fetch: requests.fetch, + /** Aborts when the runtime is disposed. */ + signal: lifetime.signal, + decodeConcurrency, + decoders: + options.decoders ?? + (options.decoder ? wholeInstanceDecoderTable : defaultDecoderTable), + /** Concurrent requests, which also bounds how far reads run ahead of decoding. */ + readConcurrency: requests.poolSize, + readInstance: read, + decode, + dispose, + }; +} + +export type DicomRuntime = ReturnType; diff --git a/packages/dicom/core/runtime/decoder.ts b/packages/dicom/core/runtime/decoder.ts new file mode 100644 index 000000000..3b908070e --- /dev/null +++ b/packages/dicom/core/runtime/decoder.ts @@ -0,0 +1,101 @@ +import { + InterfaceTypes, + runPipeline, + type Image, + type TypedArray, +} from 'itk-wasm'; + +export type DecodedDicomImage = { + size: number[]; + data: Exclude; + imageType: { components: number }; +}; +export type DicomAssets = { pipelineWorkerUrl: string; imageIOUrl: string }; + +function decodedImage(result: Awaited>) { + if (result.returnValue !== 0 || !result.outputs[0]?.data) + throw new Error(result.stderr || 'Could not decode DICOM image'); + const image = result.outputs[1]?.data as Image; + if (!image?.data) throw new Error('No pixel data decoded from DICOM image'); + if ( + image.data instanceof BigInt64Array || + image.data instanceof BigUint64Array + ) + throw new Error('DICOM pixel arrays must contain numbers'); + return { + image: { + size: image.size, + data: image.data, + imageType: { components: image.imageType.components }, + }, + }; +} + +/** + * One GDCM pipeline worker, created on first use. A worker error rejects the + * running decode and drops the worker, so the next decode starts a fresh one. + */ +export function createGdcmLane(assets: DicomAssets) { + let worker: Worker | null = null; + let rejectActive: ((reason: unknown) => void) | undefined; + const reset = (reason: unknown) => { + if (worker) { + worker.removeEventListener('error', onError); + worker.removeEventListener('messageerror', onMessageError); + worker.terminate(); + worker = null; + } + rejectActive?.(reason); + }; + const onError = () => reset(new Error('DICOM decoder worker failed')); + const onMessageError = () => + reset(new Error('DICOM decoder worker message failed')); + const startWorker = () => { + const ownedWorker = new Worker(assets.pipelineWorkerUrl, { + type: 'module', + }); + worker = ownedWorker; + const addEventListener = ownedWorker.addEventListener.bind(ownedWorker); + // ITK attaches its message listener asynchronously, after creation. + ownedWorker.addEventListener = ( + ...args: Parameters + ) => { + if (worker !== ownedWorker) + throw new DOMException('DICOM decoder worker stopped', 'AbortError'); + addEventListener(...args); + }; + ownedWorker.addEventListener('error', onError); + ownedWorker.addEventListener('messageerror', onMessageError); + return ownedWorker; + }; + const run = async (name: string, data: Uint8Array) => { + const active = worker ?? startWorker(); + const failed = new Promise((_, rejectFailure) => { + rejectActive = rejectFailure; + }); + try { + const result = await Promise.race([ + runPipeline( + 'gdcm-read-image', + [name, '0', '1', '--memory-io'], + [ + { type: InterfaceTypes.JsonCompatible }, + { type: InterfaceTypes.Image }, + ], + [{ type: InterfaceTypes.BinaryFile, data: { path: name, data } }], + { + webWorker: active, + pipelineWorkerUrl: assets.pipelineWorkerUrl, + pipelineBaseUrl: assets.imageIOUrl, + noCopy: true, + } + ), + failed, + ]); + return decodedImage(result); + } finally { + rejectActive = undefined; + } + }; + return { run, reset }; +} diff --git a/packages/dicom/core/runtime/metadataReader.ts b/packages/dicom/core/runtime/metadataReader.ts new file mode 100644 index 000000000..7b060352d --- /dev/null +++ b/packages/dicom/core/runtime/metadataReader.ts @@ -0,0 +1,80 @@ +import * as Comlink from 'comlink'; +import { readDicomDataset, type DicomDataset } from '../metadata/dicomDataset'; +import type { DicomDatasetWorker } from '../metadata/readDicomDataset.worker'; + +export type MetadataReaderOptions = { + metadataWorkerFactory?: () => Worker; + metadataConcurrency?: number; +}; + +/** Owns parser workers. Input bytes are copied before transfer; the caller keeps its buffer. */ +export function createMetadataReader(options: MetadataReaderOptions = {}) { + const count = options.metadataConcurrency ?? 2; + if (!Number.isInteger(count) || count < 1) + throw new Error('Metadata concurrency must be a positive integer'); + const workers: Array<{ + worker: Worker; + remote: Comlink.Remote; + }> = []; + const pending = new Set<(reason: unknown) => void>(); + let next = 0; + let disposed = false; + const createWorker = + options.metadataWorkerFactory ?? + (() => + new Worker( + new URL('../metadata/readDicomDataset.worker.ts', import.meta.url), + { type: 'module' } + )); + const resetWorkers = (error: unknown) => { + pending.forEach((reject) => reject(error)); + pending.clear(); + workers.forEach(({ remote, worker }) => { + remote[Comlink.releaseProxy](); + worker.terminate(); + }); + workers.length = 0; + }; + const read = async (bytes: Uint8Array): Promise => { + if (disposed) + throw new DOMException('Metadata reader disposed', 'AbortError'); + if (typeof Worker === 'undefined' && !options.metadataWorkerFactory) + return readDicomDataset(bytes); + if (workers.length < count) { + const worker = createWorker(); + const fail = (message: string) => { + if (workers.some((entry) => entry.worker === worker)) + resetWorkers(new Error(message)); + }; + worker.addEventListener( + 'error', + () => fail('DICOM metadata worker failed'), + { once: true } + ); + worker.addEventListener( + 'messageerror', + () => fail('DICOM metadata worker message failed'), + { once: true } + ); + workers.push({ + worker, + remote: Comlink.wrap(worker), + }); + } + const { remote } = workers[next++ % workers.length]; + const owned = bytes.slice(); + return new Promise((resolve, reject) => { + pending.add(reject); + remote + .readDicomDataset(Comlink.transfer(owned, [owned.buffer])) + .then(resolve, reject) + .finally(() => pending.delete(reject)); + }); + }; + const dispose = () => { + if (disposed) return; + disposed = true; + resetWorkers(new DOMException('Metadata reader disposed', 'AbortError')); + }; + return { read, dispose }; +} diff --git a/packages/dicom/core/source/__tests__/byteSource.spec.ts b/packages/dicom/core/source/__tests__/byteSource.spec.ts new file mode 100644 index 000000000..6db993f0b --- /dev/null +++ b/packages/dicom/core/source/__tests__/byteSource.spec.ts @@ -0,0 +1,166 @@ +import { describe, expect, it } from 'vitest'; +import { fromBlob, fromUrl, type ByteRange } from '../byteSource'; +import { readBytes } from './sourceFixtures'; + +const bytes = Uint8Array.from({ length: 1000 }, (_, index) => index % 251); +const expected = (range?: ByteRange) => + bytes.slice(range?.start ?? 0, range?.end ?? bytes.length); + +type ServerOptions = { + honorRange?: boolean; + exposeContentRange?: boolean; + status?: number; +}; + +/** A fetch that serves `bytes` in 64-byte chunks and records what it was asked. */ +const server = (options: ServerOptions = {}) => { + const { honorRange = true, exposeContentRange = true, status } = options; + const requests: Array = []; + const caches: Array = []; + const bodies: Array<{ cancelled: boolean }> = []; + const fetchFn: typeof fetch = async (_input, init) => { + const range = new Headers(init?.headers).get('Range'); + requests.push(range); + caches.push(init?.cache); + const match = range?.match(/^bytes=(\d+)-(\d*)$/); + const partial = honorRange && match !== null && match !== undefined; + const start = partial ? Number(match[1]) : 0; + const end = partial && match[2] ? Number(match[2]) + 1 : bytes.length; + const body = { cancelled: false }; + bodies.push(body); + let offset = start; + const stream = new ReadableStream({ + pull: (controller) => { + if (offset >= end) { + controller.close(); + return; + } + controller.enqueue(bytes.slice(offset, Math.min(end, offset + 64))); + offset += 64; + }, + cancel: () => { + body.cancelled = true; + }, + }); + const headers = new Headers({ 'content-length': String(end - start) }); + if (partial && exposeContentRange) + headers.set('content-range', `bytes ${start}-${end - 1}/${bytes.length}`); + return new Response(stream, { + status: status ?? (partial ? 206 : 200), + headers, + }); + }; + return { fetch: fetchFn, requests, caches, bodies }; +}; + +const signal = () => new AbortController().signal; + +describe('blob byte source', () => { + it.each([ + undefined, + { start: 10, end: 20 }, + { start: 990 }, + { start: 5, end: 5000 }, + ])('reads %j', async (range) => { + const source = fromBlob(new Blob([bytes])); + expect(source.size).toBe(bytes.length); + expect(await readBytes(source.read(signal(), range))).toEqual( + expected( + range && { + ...range, + end: Math.min(range.end ?? bytes.length, bytes.length), + } + ) + ); + }); + + it('errors its stream once the signal aborts', async () => { + const controller = new AbortController(); + const stream = fromBlob(new Blob([bytes])).read(controller.signal); + controller.abort(new DOMException('stop', 'AbortError')); + await expect(readBytes(stream)).rejects.toMatchObject({ + name: 'AbortError', + }); + }); +}); + +describe('URL byte source', () => { + it('reads the whole resource without a Range header', async () => { + const http = server(); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + expect(await readBytes(source.read(signal()))).toEqual(bytes); + expect(http.requests).toEqual([null]); + }); + + it.each([ + ['exposes Content-Range', { exposeContentRange: true }], + ['hides Content-Range from CORS', { exposeContentRange: false }], + ['ignores Range and answers 200', { honorRange: false }], + ])('reads a range when the server %s', async (_name, options) => { + const http = server(options); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + + const bounded = await readBytes( + source.read(signal(), { start: 100, end: 300 }) + ); + const open = await readBytes(source.read(signal(), { start: 900 })); + + expect(bounded).toEqual(expected({ start: 100, end: 300 })); + expect(open).toEqual(expected({ start: 900 })); + expect(http.requests).toEqual(['bytes=100-299', 'bytes=900-']); + }); + + it.each([ + [true, 'honoured'], + [false, 'ignored'], + ])( + 'reports a server that honours Range (%s) as %s, bypassing the HTTP cache for ranges', + async (honorRange, support) => { + const http = server({ honorRange }); + const source = fromUrl('https://example.test/a.dcm', { + fetch: http.fetch, + }); + expect(source.rangeSupport?.()).toBe('unknown'); + await readBytes(source.read(signal())); + expect(source.rangeSupport?.()).toBe('unknown'); + await readBytes(source.read(signal(), { start: 10, end: 20 })); + expect(source.rangeSupport?.()).toBe(support); + expect(http.caches).toEqual([undefined, 'no-store']); + } + ); + + it('stops the ignored-Range body once the range is read', async () => { + const http = server({ honorRange: false }); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + await readBytes(source.read(signal(), { start: 0, end: 10 })); + expect(http.bodies[0].cancelled).toBe(true); + }); + + it('opens a fresh request for every read', async () => { + const http = server(); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + await readBytes(source.read(signal(), { start: 0, end: 4 })); + await readBytes(source.read(signal(), { start: 0, end: 4 })); + expect(http.requests).toHaveLength(2); + }); + + it.each([ + [404, /could not be found/], + [416, /Range could not be satisfied/], + ])('fails a %i response', async (status, message) => { + const http = server({ status }); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + await expect( + readBytes(source.read(signal(), { start: 0, end: 4 })) + ).rejects.toThrow(message); + }); + + it('cancels the response body when the reader cancels', async () => { + const http = server(); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const reader = source.read(signal()).getReader(); + await reader.read(); + await reader.cancel(); + expect(http.bodies[0].cancelled).toBe(true); + }); +}); diff --git a/packages/dicom/core/source/__tests__/sourceFixtures.ts b/packages/dicom/core/source/__tests__/sourceFixtures.ts new file mode 100644 index 000000000..b0f3a94b3 --- /dev/null +++ b/packages/dicom/core/source/__tests__/sourceFixtures.ts @@ -0,0 +1,57 @@ +import { concatBytes, defer } from '../../utils'; +import type { ByteSource } from '../byteSource'; + +/** Hands out bytes a chunk at a time and counts what readers pulled and cancelled. */ +export const trackedSource = (bytes: Uint8Array, chunkSize = bytes.length) => { + const stats = { reads: 0, delivered: 0, cancelled: 0 }; + const source: ByteSource = { + size: bytes.length, + read: () => { + stats.reads += 1; + let offset = 0; + return new ReadableStream({ + pull: (controller) => { + if (offset >= bytes.length) { + controller.close(); + return; + } + const chunk = bytes.slice(offset, offset + chunkSize); + offset += chunk.length; + stats.delivered += chunk.length; + controller.enqueue(chunk); + }, + cancel: () => { + stats.cancelled += 1; + }, + }); + }, + }; + return { source, stats }; +}; + +/** A source whose bytes never arrive; it reports when it is pulled and cancelled. */ +export const hangingSource = () => { + const pulled = defer(); + const cancelled = defer(); + const source: ByteSource = { + read: () => + new ReadableStream({ + pull: () => { + pulled.resolve(); + return new Promise(() => {}); + }, + cancel: (reason) => cancelled.resolve(reason), + }), + }; + return { source, pulled: pulled.promise, cancelled: cancelled.promise }; +}; + +export const readBytes = async (stream: ReadableStream) => { + const parts: Uint8Array[] = []; + const reader = stream.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) return concatBytes(parts); + parts.push(value); + } +}; diff --git a/packages/dicom/core/source/byteSource.ts b/packages/dicom/core/source/byteSource.ts new file mode 100644 index 000000000..4099deea6 --- /dev/null +++ b/packages/dicom/core/source/byteSource.ts @@ -0,0 +1,220 @@ +import { + HTTP_STATUS_OK, + HTTP_STATUS_PARTIAL_CONTENT, + HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, + HttpNotFound, +} from '../streaming/httpCodes'; +import { linkedController } from '../utils/abort'; +import { concatBytes } from '../utils'; +import { parseContentRangeHeader } from '../utils/parseContentRangeHeader'; + +/** Half-open byte interval; an absent end reads to the last byte. */ +export type ByteRange = { start: number; end?: number }; + +/** + * Where an instance's bytes come from. Every read opens a fresh stream that + * the signal or a cancel closes; nothing stays open or cached between reads. + */ +export type ByteSource = { + size?: number; + read: (signal: AbortSignal, range?: ByteRange) => ReadableStream; + /** + * Whether a ranged read costs only its range. Absent means it does; a + * source that learns it from responses says `unknown` until one arrives. + */ + rangeSupport?: () => RangeSupport; +}; + +export type RangeSupport = 'unknown' | 'honoured' | 'ignored'; + +/** Read enough per pull that a header rarely needs a second slice. */ +const BLOB_CHUNK_SIZE = 64 * 1024; + +const rangeLength = (range?: ByteRange) => + range?.end === undefined ? Infinity : Math.max(0, range.end - range.start); + +export const fromBlob = (blob: Blob): ByteSource => ({ + size: blob.size, + read: (signal, range) => { + let offset = range?.start ?? 0; + const end = Math.min(blob.size, offset + rangeLength(range)); + return new ReadableStream({ + pull: async (controller) => { + signal.throwIfAborted(); + if (offset >= end) { + controller.close(); + return; + } + const next = Math.min(end, offset + BLOB_CHUNK_SIZE); + const bytes = new Uint8Array( + await blob.slice(offset, next).arrayBuffer() + ); + signal.throwIfAborted(); + offset = next; + controller.enqueue(bytes); + }, + }); + }, +}); + +/** Drops `skip` leading bytes and stops after `length` bytes. */ +export function sliceStream( + stream: ReadableStream, + skip: number, + length = Infinity +) { + const reader = stream.getReader(); + let toSkip = skip; + let remaining = length; + // A pull that enqueues nothing is not called again, so skip inside one pull. + const nextKept = async () => { + for (;;) { + const { done, value } = await reader.read(); + if (done) return null; + const dropped = Math.min(toSkip, value.length); + toSkip -= dropped; + if (dropped < value.length) + return value.subarray(dropped, dropped + remaining); + } + }; + return new ReadableStream({ + pull: async (controller) => { + const kept = remaining > 0 ? await nextKept() : null; + if (!kept) { + controller.close(); + reader.cancel().catch(() => {}); + return; + } + remaining -= kept.length; + controller.enqueue(kept); + }, + cancel: (reason) => reader.cancel(reason), + }); +} + +const rangeHeader = ({ start, end }: ByteRange) => + `bytes=${start}-${end === undefined ? '' : end - 1}`; + +// Content-Range is often not CORS-exposed; a 206 without it starts where asked. +function partialContentStart(response: Response, range: ByteRange) { + const contentRange = parseContentRangeHeader( + response.headers.get('content-range') + ); + if (contentRange.type === 'empty-range') return range.start; + if (contentRange.type !== 'range') + throw new Error('Invalid content-range header'); + if (contentRange.start > range.start) + throw new Error('The server answered a range that starts too late'); + return contentRange.start; +} + +function rangedBody(response: Response, range?: ByteRange) { + if (!response.body) throw new Error('Did not receive a response body'); + const start = range?.start ?? 0; + const bodyStart = + response.status === HTTP_STATUS_PARTIAL_CONTENT && range + ? partialContentStart(response, range) + : 0; + return sliceStream(response.body, start - bodyStart, rangeLength(range)); +} + +type UrlSourceOptions = { + fetch?: typeof fetch; + init?: Omit; +}; + +function assertReadableStatus(response: Response, url: string | URL) { + if ( + response.status === HTTP_STATUS_OK || + response.status === HTTP_STATUS_PARTIAL_CONTENT + ) + return; + response.body?.cancel().catch(() => {}); + if (response.status === HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE) + throw new Error('Range could not be satisfied'); + throw new HttpNotFound(url.toString()); +} + +/** + * Asks for a range with an HTTP Range request. A server that ignores Range + * answers 200 with the whole body, which is then skipped and cut to size; + * `rangeSupport` reports what the latest ranged response showed. + */ +export const fromUrl = ( + url: string | URL, + options: UrlSourceOptions = {} +): ByteSource => { + const fetchFn = + options.fetch ?? ((input, init) => globalThis.fetch(input, init)); + let rangeSupport: RangeSupport = 'unknown'; + const open = async (signal: AbortSignal, range?: ByteRange) => { + const headers = Object.fromEntries(new Headers(options.init?.headers)); + if (range) headers.Range = rangeHeader(range); + // Chrome can answer a Range from a cache entry an earlier cancelled read + // left behind with status 200 and only the range's bytes, which reads + // exactly like a server that ignored Range. + const cache = range ? { cache: 'no-store' as const } : {}; + const response = await fetchFn(url, { + ...cache, + ...options.init, + headers, + signal, + }); + assertReadableStatus(response, url); + if (range) + rangeSupport = + response.status === HTTP_STATUS_PARTIAL_CONTENT + ? 'honoured' + : 'ignored'; + return rangedBody(response, range).getReader(); + }; + return { + rangeSupport: () => rangeSupport, + read: (signal, range) => { + const { controller, release } = linkedController(signal); + const opened = open(controller.signal, range); + // Observed here so a stream nobody pulls does not reject unhandled. + opened.catch(release); + return new ReadableStream({ + pull: async (stream) => { + const { done, value } = await (await opened).read(); + if (!done) { + stream.enqueue(value); + return; + } + release(); + stream.close(); + }, + cancel: async (reason) => { + controller.abort(reason); + const reader = await opened.catch(() => null); + await reader?.cancel(reason); + }, + }); + }, + }; +}; + +/** Reads a whole source, or one range of it, into memory. */ +export async function readBytes( + source: ByteSource, + signal: AbortSignal, + range?: ByteRange +) { + const reader = source.read(signal, range).getReader(); + const cancel = () => reader.cancel(signal.reason).catch(() => {}); + signal.addEventListener('abort', cancel, { once: true }); + try { + const parts: Uint8Array[] = []; + for (;;) { + signal.throwIfAborted(); + const { done, value } = await reader.read(); + if (done) break; + parts.push(value); + } + signal.throwIfAborted(); + return concatBytes(parts); + } finally { + signal.removeEventListener('abort', cancel); + } +} diff --git a/src/core/streaming/__tests__/byteDeque.spec.ts b/packages/dicom/core/streaming/__tests__/byteDeque.spec.ts similarity index 97% rename from src/core/streaming/__tests__/byteDeque.spec.ts rename to packages/dicom/core/streaming/__tests__/byteDeque.spec.ts index 70d8777a1..c32e8a708 100644 --- a/src/core/streaming/__tests__/byteDeque.spec.ts +++ b/packages/dicom/core/streaming/__tests__/byteDeque.spec.ts @@ -1,4 +1,4 @@ -import ByteDeque from '@/src/core/streaming/byteDeque'; +import ByteDeque from '../byteDeque'; import { describe, it, expect } from 'vitest'; describe('ByteDeque', () => { diff --git a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts b/packages/dicom/core/streaming/__tests__/cachedStreamFetcher.spec.ts similarity index 80% rename from src/core/streaming/__tests__/cachedStreamFetcher.spec.ts rename to packages/dicom/core/streaming/__tests__/cachedStreamFetcher.spec.ts index d7eb46216..dbd74db9f 100644 --- a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts +++ b/packages/dicom/core/streaming/__tests__/cachedStreamFetcher.spec.ts @@ -1,8 +1,5 @@ -import { RequestPool } from '@/src/core/streaming/requestPool'; -import { - CachedStreamFetcher, - sliceChunks, -} from '@/src/core/streaming/cachedStreamFetcher'; +import { RequestPool } from '../requestPool'; +import { CachedStreamFetcher, sliceChunks } from '../cachedStreamFetcher'; import { describe, expect, it } from 'vitest'; const readStream = async ( @@ -118,3 +115,25 @@ describe('sliceChunks', () => { ).toEqual([new Uint8Array([1, 2]), new Uint8Array([3])]); }); }); + +it('rejects an unverified resumed range while preserving the cached header', async () => { + const prefix = new Uint8Array([1, 2, 3, 4]); + let requests = 0; + const fetcher = new CachedStreamFetcher( + 'https://example.test/hidden-headers', + { + prefixChunks: [prefix], + fetch: async () => + new Response(new Uint8Array([5, 6]), { + status: 206, + headers: requests++ === 0 ? {} : { 'content-range': 'bytes 4-5/6' }, + }), + } + ); + await expect(fetcher.connect()).rejects.toThrow('readable content range'); + expect(fetcher.connected).toBe(false); + expect(new Uint8Array(await (await fetcher.blob()).arrayBuffer())).toEqual( + new Uint8Array([1, 2, 3, 4, 5, 6]) + ); + fetcher.close(); +}); diff --git a/packages/dicom/core/streaming/__tests__/requestPool.spec.ts b/packages/dicom/core/streaming/__tests__/requestPool.spec.ts new file mode 100644 index 000000000..b5693228c --- /dev/null +++ b/packages/dicom/core/streaming/__tests__/requestPool.spec.ts @@ -0,0 +1,144 @@ +import { RequestPool } from '../requestPool'; +import { describe, it, expect } from 'vitest'; +import { defer } from '../../utils'; + +const neverResolvingFetch = async () => { + return new Promise(() => {}); +}; + +const abortableFetch = async ( + _input: RequestInfo | URL, + init?: RequestInit +) => { + return new Promise((_resolve, reject) => { + if (init?.signal) { + if (init.signal.aborted) { + reject(init.signal.reason); + return; + } + init.signal.addEventListener('abort', () => { + reject(init.signal!.reason); + }); + } + }); +}; + +describe('requestPool', () => { + it('should not have more active requests than the pool size', () => { + const N = 4; + const pool = new RequestPool(N, neverResolvingFetch); + for (let i = 0; i < 10; i++) { + pool.fetch('http://localhost/url'); + } + expect(pool.activeConnections).to.equal(N); + }); + + it('should support removal of requests via an AbortController', async () => { + const N = 4; + const pool = new RequestPool(N, abortableFetch); + const controllers: AbortController[] = []; + const promises: Promise[] = []; + + for (let i = 0; i < 10; i++) { + const controller = new AbortController(); + controllers.push(controller); + promises.push( + pool.fetch('http://localhost/url', { signal: controller.signal }) + ); + } + + controllers.forEach((controller) => { + controller.abort('cancelled'); + }); + + for (const p of promises) { + await expect(p).rejects.toThrow('cancelled'); + } + }); + + it('settles queued requests immediately on cancellation or disposal', async () => { + const fetchStarted = defer(); + const pool = new RequestPool( + 1, + (_request, init) => + new Promise((_resolve, reject) => { + fetchStarted.resolve(); + init?.signal?.addEventListener( + 'abort', + () => reject(init.signal?.reason), + { once: true } + ); + }) + ); + const first = pool.fetch('https://example.test/first'); + const firstRejected = expect(first).rejects.toMatchObject({ + name: 'AbortError', + }); + await fetchStarted.promise; + const cancellation = new AbortController(); + const second = pool.fetch('https://example.test/second', { + signal: cancellation.signal, + }); + const secondRejected = expect(second).rejects.toMatchObject({ + name: 'AbortError', + }); + cancellation.abort(); + await secondRejected; + pool.dispose(); + await firstRejected; + await expect( + pool.fetch('https://example.test/third') + ).rejects.toMatchObject({ name: 'AbortError' }); + }); + + it.each(['source', 'pool'])( + 'cancels the HTTP response body after headers through %s disposal', + async (owner) => { + const controller = new AbortController(); + const pool = new RequestPool( + 1, + async (_request, init) => + new Response( + new ReadableStream({ + start(stream) { + init?.signal?.addEventListener( + 'abort', + () => stream.error(init.signal?.reason), + { once: true } + ); + }, + }) + ) + ); + const response = await pool.fetch('https://example.test/stream', { + signal: controller.signal, + }); + const pending = response.body!.getReader().read(); + const rejected = expect(pending).rejects.toMatchObject({ + name: 'AbortError', + }); + if (owner === 'source') controller.abort(); + else pool.dispose(); + await rejected; + pool.dispose(); + } + ); +}); + +it('imports a remote resource without AbortSignal.any', async () => { + const descriptor = Object.getOwnPropertyDescriptor(AbortSignal, 'any'); + Object.defineProperty(AbortSignal, 'any', { + configurable: true, + value: undefined, + }); + const pool = new RequestPool(1, async () => new Response('resource')); + try { + expect( + await (await pool.fetch('https://example.test/resource')).text() + ).toBe('resource'); + } finally { + pool.dispose(); + if (descriptor) Object.defineProperty(AbortSignal, 'any', descriptor); + else Reflect.deleteProperty(AbortSignal, 'any'); + } +}); diff --git a/src/core/streaming/__tests__/streamingByteReader.spec.ts b/packages/dicom/core/streaming/__tests__/streamingByteReader.spec.ts similarity index 95% rename from src/core/streaming/__tests__/streamingByteReader.spec.ts rename to packages/dicom/core/streaming/__tests__/streamingByteReader.spec.ts index cbd4e5dd5..cc720f925 100644 --- a/src/core/streaming/__tests__/streamingByteReader.spec.ts +++ b/packages/dicom/core/streaming/__tests__/streamingByteReader.spec.ts @@ -1,4 +1,4 @@ -import StreamingByteReader from '@/src/core/streaming/streamingByteReader'; +import StreamingByteReader from '../streamingByteReader'; import { asCoroutine } from '@/src/utils'; import { describe, it, expect } from 'vitest'; diff --git a/src/core/streaming/byteDeque.ts b/packages/dicom/core/streaming/byteDeque.ts similarity index 100% rename from src/core/streaming/byteDeque.ts rename to packages/dicom/core/streaming/byteDeque.ts diff --git a/src/core/streaming/cachedStreamFetcher.ts b/packages/dicom/core/streaming/cachedStreamFetcher.ts similarity index 80% rename from src/core/streaming/cachedStreamFetcher.ts rename to packages/dicom/core/streaming/cachedStreamFetcher.ts index 7265ed2d0..423e3a646 100644 --- a/src/core/streaming/cachedStreamFetcher.ts +++ b/packages/dicom/core/streaming/cachedStreamFetcher.ts @@ -3,21 +3,21 @@ import { HTTP_STATUS_PARTIAL_CONTENT, HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, HttpNotFound, -} from '@/src/core/streaming/httpCodes'; -import { Fetcher, FetcherInit } from '@/src/core/streaming/types'; +} from './httpCodes'; +import { Fetcher, FetcherInit } from './types'; import { ContentRange, parseContentRangeHeader, -} from '@/src/utils/parseContentRangeHeader'; -import { Maybe } from '@/src/types'; +} from '../utils/parseContentRangeHeader'; +import { Maybe } from '../utils'; type FetchFunction = typeof fetch; -export interface CachedStreamFetcherRequestInit extends RequestInit { +export type CachedStreamFetcherRequestInit = RequestInit & { prefixChunks?: Uint8Array[]; contentLength?: number; fetch?: FetchFunction; -} +}; export const StopSignal = Symbol('StopSignal'); @@ -87,7 +87,9 @@ export class CachedStreamFetcher implements Fetcher { ) { this.chunks = [...(init?.prefixChunks ?? [])] as Uint8Array[]; this.contentLength = init?.contentLength ?? null; - this.fetch = init?.fetch ?? globalThis.fetch; + const fetchFn = + init?.fetch ?? ((input, options) => globalThis.fetch(input, options)); + this.fetch = (input, options) => fetchFn(input, options); } get connected() { @@ -98,10 +100,6 @@ export class CachedStreamFetcher implements Fetcher { return this.chunks.reduce((sum, chunk) => sum + chunk.length, 0); } - get cachedChunks() { - return this.chunks; - } - get abortSignal() { return this.abortController?.signal; } @@ -110,6 +108,7 @@ export class CachedStreamFetcher implements Fetcher { if (this.connected) return; this.abortController = init?.abortController ?? new AbortController(); + const connection = this.abortController; this.abortController.signal.addEventListener('abort', () => { this.cleanupAfterAbort(); }); @@ -130,6 +129,7 @@ export class CachedStreamFetcher implements Fetcher { signal: this.abortController.signal, }); + this.validateConnection(connection, response); this.contentType = response.headers.get('content-type') ?? ''; this.contentDisposition = response.headers.get('content-disposition') ?? ''; @@ -172,17 +172,7 @@ export class CachedStreamFetcher implements Fetcher { } if (response.status === HTTP_STATUS_PARTIAL_CONTENT) { - if (contentRange.type === 'invalid-range') - throw new Error('Invalid content-range header'); - if (contentRange.type === 'unsatisfied-range') - throw new Error('Range could not be satisfied'); - - let start: number = 0; - if (contentRange.type === 'range') { - start = contentRange.start; - } - - this.chunks = sliceChunks(this.chunks, start); + this.resumeChunks(response, contentRange); } else if (!noMoreContent) { this.chunks = []; } @@ -191,6 +181,29 @@ export class CachedStreamFetcher implements Fetcher { this.activeNetworkStreamReader = this.activeNetworkStream.getReader(); } + private resumeChunks(response: Response, contentRange: ContentRange) { + if (contentRange.type === 'invalid-range') + throw new Error('Invalid content-range header'); + if (contentRange.type === 'unsatisfied-range') + throw new Error('Range could not be satisfied'); + if (contentRange.type === 'empty-range' && this.size > 0) { + response.body?.cancel().catch(() => {}); + this.close(); + throw new Error( + 'Cannot resume a DICOM download without a readable content range' + ); + } + const start = contentRange.type === 'range' ? contentRange.start : 0; + this.chunks = sliceChunks(this.chunks, start); + } + + private validateConnection(connection: AbortController, response: Response) { + if (connection.signal.aborted || connection !== this.abortController) { + response.body?.cancel().catch(() => {}); + throw new DOMException('DICOM request cancelled', 'AbortError'); + } + } + close() { if (!this.abortController) return; this.abortController.abort(StopSignal); @@ -203,6 +216,7 @@ export class CachedStreamFetcher implements Fetcher { pull: async (controller) => { if (!this.connected) { controller.close(); + return; } if (chunkIndex > this.chunks.length) @@ -232,9 +246,11 @@ export class CachedStreamFetcher implements Fetcher { }); if (!this.promise) { + const connection = this.abortController; this.promise = this.activeNetworkStreamReader .read() .then((result) => { + if (connection !== this.abortController) throw StopSignal; if (!result.done) { this.chunks.push(result.value as Uint8Array); } else if (this.contentLength === null) { @@ -244,7 +260,7 @@ export class CachedStreamFetcher implements Fetcher { return result; }) .finally(() => { - this.promise = null; + if (connection === this.abortController) this.promise = null; }); } return this.promise; @@ -260,6 +276,7 @@ export class CachedStreamFetcher implements Fetcher { } private cleanupAfterAbort() { + this.promise = null; this.activeNetworkStreamReader = null; this.activeNetworkStream = null; this.abortController = null; diff --git a/packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts b/packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts new file mode 100644 index 000000000..f6e99395b --- /dev/null +++ b/packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest'; +import { findElement, readDicomDataset } from '../../../metadata/dicomDataset'; +import { getDatasetTag } from '../../../metadata/datasetAccess'; +import { sequenceItems } from '../../../metadata/functionalGroups'; +import { concatBytes } from '../../../utils'; +import { readHeader, syntheticSlice } from '@/tests/dicomSourceFixtures'; +import { + rawElement, + sequenceItem, + undefinedLengthItem, + undefinedLengthSequence, +} from '@/tests/specs/syntheticDicom'; + +const encode = (text: string) => new TextEncoder().encode(text); +const part10 = (syntax: string, dataset: Uint8Array) => { + const meta = rawElement(2, 0x10, 'UI', encode(`${syntax}\0`)); + const length = new Uint8Array(4); + new DataView(length.buffer).setUint32(0, meta.length, true); + return concatBytes([ + new Uint8Array(128), + encode('DICM'), + rawElement(2, 0, 'UL', length), + meta, + dataset, + ]); +}; + +// The fixture contains only text and SQ values; their bytes are endian-neutral. +const bigEndianElement = (bytes: Uint8Array, longLength = false) => { + const result = bytes.slice(); + const view = new DataView(result.buffer); + view.setUint16(0, view.getUint16(0, true)); + view.setUint16(2, view.getUint16(2, true)); + if (longLength) view.setUint32(8, view.getUint32(8, true)); + else view.setUint16(6, view.getUint16(6, true)); + return result; +}; + +const bigEndianItem = (element: number, length: number) => { + const bytes = new Uint8Array(8); + const view = new DataView(bytes.buffer); + view.setUint16(0, 0xfffe); + view.setUint16(2, element); + view.setUint32(4, length); + return bytes; +}; + +describe('streamed header encodings', () => { + it.each([sequenceItem, undefinedLengthItem])( + 'passes encapsulated icon fragments inside %s to the metadata reader', + async (item) => { + const payload = new Uint8Array([ + 0xff, 0xd8, 0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0, 0xff, 0xd9, + ]); + const pixels = undefinedLengthSequence( + 0x7fe0, + 0x0010, + concatBytes([sequenceItem(new Uint8Array()), sequenceItem(payload)]) + ); + pixels.set(encode('OB'), 4); + const bytes = syntheticSlice({ + extraElements: [ + undefinedLengthSequence(0x0088, 0x0200, item(pixels)), + rawElement(0x4008, 0x0103, 'LO', encode('AFTER ')), + ], + }); + const { dataset } = await readHeader(bytes, 7); + const icon = sequenceItems(dataset, '00880200')[0]; + expect(findElement(icon, '7FE00010')?.values).toEqual({ + kind: 'bytes', + values: [payload], + }); + expect(getDatasetTag(dataset, '40080103')).toBe('AFTER '); + expect(dataset).toEqual(readDicomDataset(bytes)); + } + ); + + it('reads undefined-length Big Endian items and their following attributes', async () => { + const sequence = bigEndianElement( + rawElement(0x0008, 0x1140, 'SQ', new Uint8Array()), + true + ); + new DataView(sequence.buffer).setUint32(8, 0xffffffff); + const bytes = part10( + '1.2.840.10008.1.2.2', + concatBytes([ + sequence, + bigEndianItem(0xe000, 0xffffffff), + bigEndianElement(rawElement(8, 0x1155, 'UI', encode('1.2.3\0'))), + bigEndianItem(0xe00d, 0), + bigEndianItem(0xe0dd, 0), + bigEndianElement(rawElement(0x0010, 0x0010, 'PN', encode('DOE^JANE'))), + ]) + ); + const { dataset } = await readHeader(bytes, 7); + expect(getDatasetTag(dataset, '00100010')).toBe('DOE^JANE'); + expect( + getDatasetTag(sequenceItems(dataset, '00081140')[0], '00081155') + ).toBe('1.2.3'); + }); + + it('does not interpret SQ-like compressed bytes as header elements', async () => { + // A non-final stored DEFLATE block of 0xacfe bytes has 0x53 in byte 4. + // Its first data byte is 0x51, so a DICOM element walk sees a false SQ VR. + const elements = concatBytes([ + rawElement(0x0051, 0x0010, 'LO', encode('TEST')), + rawElement(0x0051, 0x1010, 'OB', new Uint8Array(0xacfe - 38)), + rawElement(0x4008, 0x0103, 'LO', encode('AFTER ')), + ]); + const compressed = concatBytes([ + new Uint8Array([0, 0xfe, 0xac, 0x01, 0x53]), + elements, + new Uint8Array([3, 0]), + ]); + const bytes = part10('1.2.840.10008.1.2.1.99', compressed); + expect(getDatasetTag(readDicomDataset(bytes), '40080103')).toBe('AFTER '); + const { dataset } = await readHeader(bytes, 7); + expect(getDatasetTag(dataset, '40080103')).toBe('AFTER '); + }); +}); diff --git a/packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts b/packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts new file mode 100644 index 000000000..7bfbc4519 --- /dev/null +++ b/packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts @@ -0,0 +1,89 @@ +import { describe, it, expect } from 'vitest'; +import { readDicomDataset } from '../../../metadata/dicomDataset'; +import { concatBytes } from '../../../utils'; +import { syntheticSlice } from '@/tests/dicomSourceFixtures'; +import { rawElement, sequenceItem } from '@/tests/specs/syntheticDicom'; +import { + readUltrasoundRegions, + unitToMm, + US_UNIT_CENTIMETERS, +} from '../ultrasoundRegion'; + +const u16LE = (value: number) => { + const bytes = new Uint8Array(2); + new DataView(bytes.buffer).setUint16(0, value, true); + return bytes; +}; + +const f64LE = (value: number) => { + const bytes = new Uint8Array(8); + new DataView(bytes.buffer).setFloat64(0, value, true); + return bytes; +}; + +const wellFormedItem = [ + rawElement(0x0018, 0x6024, 'US', u16LE(US_UNIT_CENTIMETERS)), + rawElement(0x0018, 0x6026, 'US', u16LE(US_UNIT_CENTIMETERS)), + rawElement(0x0018, 0x602c, 'FD', f64LE(0.05)), + rawElement(0x0018, 0x602e, 'FD', f64LE(0.1)), +]; + +const regions = (items: Uint8Array[][]) => + readUltrasoundRegions( + readDicomDataset( + syntheticSlice({ + extraElements: [ + rawElement( + 0x0018, + 0x6011, + 'SQ', + concatBytes(items.map((item) => sequenceItem(concatBytes(item)))) + ), + ], + }) + ) + ); + +describe('readUltrasoundRegions', () => { + it('decodes the first item of the sequence', () => { + expect(regions([wellFormedItem])).toEqual({ + region: { + physicalDeltaX: 0.05, + physicalDeltaY: 0.1, + physicalUnitsXDirection: US_UNIT_CENTIMETERS, + physicalUnitsYDirection: US_UNIT_CENTIMETERS, + }, + regionCount: 1, + }); + }); + + it('returns no region when the sequence is empty or absent', () => { + expect(regions([])).toEqual({ regionCount: 0 }); + expect(readUltrasoundRegions(readDicomDataset(syntheticSlice()))).toEqual({ + regionCount: 0, + }); + }); + + it('reports the count when a required field is missing', () => { + expect(regions([wellFormedItem.slice(0, -1)])).toEqual({ regionCount: 1 }); + }); + + it('decodes only the first item but reports the total count', () => { + expect(regions([wellFormedItem, []])).toEqual({ + ...regions([wellFormedItem]), + regionCount: 2, + }); + }); +}); + +describe('unitToMm', () => { + it('returns 10 for centimetres (code 3)', () => { + expect(unitToMm(US_UNIT_CENTIMETERS)).toBe(10); + }); + + it('returns null for non-spatial unit codes', () => { + [0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12].forEach((code) => { + expect(unitToMm(code)).toBeNull(); + }); + }); +}); diff --git a/src/core/streaming/dicom/dicomParser.ts b/packages/dicom/core/streaming/dicom/dicomParser.ts similarity index 65% rename from src/core/streaming/dicom/dicomParser.ts rename to packages/dicom/core/streaming/dicom/dicomParser.ts index 51502a4d3..39c4f81a4 100644 --- a/src/core/streaming/dicom/dicomParser.ts +++ b/packages/dicom/core/streaming/dicom/dicomParser.ts @@ -1,5 +1,10 @@ -import StreamingByteReader from '@/src/core/streaming/streamingByteReader.js'; -import { toAscii, asCoroutine } from '@/src/utils'; +import StreamingByteReader from '../streamingByteReader'; +import { toAscii, asCoroutine } from '../../utils'; +import { + PART_10_HEADER_LENGTH, + sniffDicomLayout, + type DicomLayout, +} from '../../metadata/dicomLayout'; // [Group, Element] type Tag = [number, number]; @@ -18,18 +23,31 @@ export type ElementTagCallback = ( element: number ) => string | null; -interface ParseOptions { +type ParseOptions = { peek?: boolean; littleEndian?: boolean; explicitVr?: boolean; + endPosition?: number; onDataElement?: DataElementCallback; -} +}; + +const assertReadBounds = ( + reader: StreamingByteReader, + end: number | undefined, + length: number +) => { + if (end !== undefined && reader.position + length > end) + throw new Error('Data element exceeds its enclosing sequence or item'); +}; // This is based on the DICOM standard as of 2023. All links may point to whatever is the current at the time of visiting. const UndefinedLength = 0xffffffff; +const isEncapsulatedValue = (vr: string, length: number) => + length === UndefinedLength && (vr === 'OB' || vr === 'OW'); export const ImplicitTransferSyntaxUID = '1.2.840.10008.1.2'; export const ExplicitVRBigEndianUID = '1.2.840.10008.1.2.2'; +const DeflatedExplicitVRLittleEndianUID = '1.2.840.10008.1.2.1.99'; const Tags = { TransferSyntaxUID: [0x0002, 0x0010] as Tag, @@ -103,21 +121,56 @@ function* readElementValue( reader: StreamingByteReader, vr: string, length: number, - { explicitVr = false, littleEndian = false } = {} + { explicitVr = false, littleEndian = false, endPosition }: ParseOptions = {} ): Generator { + assertReadBounds( + reader, + endPosition, + length === UndefinedLength ? 0 : length + ); // See examples: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html + // PS3.5 6.2.2: an undefined-length UN holds sequence items encoded + // in Implicit VR Little Endian, regardless of the enclosing syntax. + if (vr === 'UN' && length === UndefinedLength) { + return yield* readSequenceValue(reader, length, { + explicitVr: false, + littleEndian: true, + endPosition, + }); + } + if (vr === 'SQ') { return yield* readSequenceValue(reader, length, { explicitVr, littleEndian, + endPosition, }); } + if (isEncapsulatedValue(vr, length)) { + yield* readFragments(reader, { littleEndian, endPosition }); + return undefined; + } + if (length === UndefinedLength) throw new Error('cannot read a value of undefined length'); return yield* reader.read(length); } +/** Fragment lengths bound opaque pixels, which can contain delimiter bytes. */ +function* readFragments(reader: StreamingByteReader, opts: ParseOptions) { + for (;;) { + assertReadBounds(reader, opts.endPosition, 8); + const [group, element] = yield* readElementTag(reader, opts); + const length = yield* reader.readUint32(opts); + if (group === 0xfffe && element === 0xe0dd && length === 0) return; + if (!equalsToTag(Tags.Item)(group, element) || length === UndefinedLength) + throw new Error('Expected a defined-length encapsulated fragment'); + assertReadBounds(reader, opts.endPosition, length); + yield* reader.seek(length); + } +} + /** * Reads the data element at point. * @@ -129,8 +182,12 @@ function* readElementValue( * https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.1 * @param {*} reader */ -function* readDataElement(reader: StreamingByteReader, opts?: ParseOptions) { - const { littleEndian = false, explicitVr = false } = opts ?? {}; +function* readDataElement( + reader: StreamingByteReader, + opts: ParseOptions = {} +) { + const { littleEndian = false, explicitVr = false, endPosition } = opts; + assertReadBounds(reader, endPosition, 8); // read tag const [group, element] = yield* readElementTag(reader, { littleEndian }); let length = 0; @@ -165,6 +222,7 @@ function* readDataElement(reader: StreamingByteReader, opts?: ParseOptions) { data = yield* readElementValue(reader, vr, length, { littleEndian, explicitVr, + endPosition, }); } else { length = yield* reader.readUint32({ littleEndian }); @@ -184,6 +242,7 @@ function* readDataElement(reader: StreamingByteReader, opts?: ParseOptions) { data = yield* readElementValue(reader, vr, length, { littleEndian, explicitVr, + endPosition, }); } @@ -203,6 +262,7 @@ function* readDataElementsUntil( opts: ParseOptions ) { while (true) { + assertReadBounds(reader, opts.endPosition, 4); const [group, element] = yield* peekElementTag(reader, opts); if (untilFn(group, element)) { return; @@ -223,12 +283,40 @@ function* readFiniteDataElements( opts: ParseOptions ) { const endPosition = reader.position + byteLength; + assertReadBounds(reader, opts.endPosition, byteLength); while (reader.position < endPosition) { - const el = yield* readDataElement(reader, opts); + const el = yield* readDataElement(reader, { ...opts, endPosition }); opts.onDataElement?.(el); } } +function* readSequenceItem(reader: StreamingByteReader, opts: ParseOptions) { + const itemByteLength = yield* reader.readUint32(opts); + const itemDataset: DataElement[] = []; + const itemOptions = { + ...opts, + onDataElement: (el: DataElement) => itemDataset.push(el), + }; + if (itemByteLength !== UndefinedLength) { + yield* readFiniteDataElements(reader, itemByteLength, itemOptions); + } else { + yield* readDataElementsUntil( + reader, + equalsToTag(Tags.ItemDelimiter), + itemOptions + ); + assertReadBounds(reader, opts.endPosition, 8); + yield* reader.seek(8); + } + return itemDataset; +} + +function* finishSequence(reader: StreamingByteReader, end?: number) { + yield* reader.seek(4); + // The declared boundary wins over a premature delimiter in a finite SQ. + if (end !== undefined) yield* reader.seek(end - reader.position); +} + /** * The reader must be pointing to the start of the sequence's data, namely the first item or the sequence delimitation item. * @@ -238,56 +326,31 @@ function* readFiniteDataElements( function* readSequenceValue( reader: StreamingByteReader, byteLength: number, - { explicitVr = false, littleEndian = false } = {} + opts: ParseOptions ) { - const items = [] as Array; - const isUndefinedLength = byteLength === UndefinedLength; - const endPosition = isUndefinedLength ? 0 : reader.position + byteLength; - while (true) { - if (!isUndefinedLength && reader.position >= endPosition) { - return items; - } - - const [group, element] = yield* readElementTag(reader, { littleEndian }); + const items: DataElement[][] = []; + const endPosition = + byteLength === UndefinedLength ? undefined : reader.position + byteLength; + const itemOptions = { + ...opts, + endPosition: endPosition ?? opts.endPosition, + }; + while (endPosition === undefined || reader.position < endPosition) { + assertReadBounds(reader, itemOptions.endPosition, 8); + const [group, element] = yield* readElementTag(reader, opts); // Item tag // https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html#table_7.5-3 if (equalsToTag(Tags.Item)(group, element)) { - const itemDataset: DataElement[] = []; - const itemByteLength = yield* reader.readUint32({ littleEndian }); - - // length rules: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.html, heading 7.5.1 - if (itemByteLength !== UndefinedLength) { - yield* readFiniteDataElements(reader, itemByteLength, { - explicitVr, - littleEndian, - onDataElement(el) { - itemDataset.push(el); - }, - }); - } else { - // read until item delimitation tag - yield* readDataElementsUntil(reader, equalsToTag(Tags.ItemDelimiter), { - explicitVr, - littleEndian, - onDataElement(el) { - itemDataset.push(el); - }, - }); - // skip the item delimitation tag and the 4-byte zero length - yield* reader.seek(4 + 4); - } - - items.push(itemDataset); + items.push(yield* readSequenceItem(reader, itemOptions)); continue; } // Sequence Delimitation Item tag // "Otherwise, the Value Field has an Undefined Length and a Sequence Delimitation Item marks the end of the Value Field." // https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.2 - if (isUndefinedLength && group === 0xfffe && element === 0xe0dd) { - // skip the 4-byte zero length - yield* reader.seek(4); + if (group === 0xfffe && element === 0xe0dd) { + yield* finishSequence(reader, endPosition); return items; } @@ -297,6 +360,7 @@ function* readSequenceValue( )},${element.toString(16)})` ); } + return items; } // Per Part 10: "File Meta Information shall be encoded using the Explicit VR Little Endian Transfer Syntax" @@ -335,6 +399,11 @@ function* readFieldMetaInfo( } ); + // Compressed bytes can resemble meta elements. The complete reader will + // locate the end of group 2 and inflate the dataset before walking it. + if (transferSyntaxUid === DeflatedExplicitVRLittleEndianUID) + return { transferSyntaxUid }; + // read until end of file meta info group block, which is the first non 0x0002 grouped element. // "Values of all Tags (0002,xxxx) are reserved for use by this Standard and later versions of DICOM." // https://dicom.nema.org/medical/dicom/current/output/html/part10.html#table_7.1-1 @@ -352,25 +421,30 @@ function* readFieldMetaInfo( export type ReadDicomOptions = { stopAtElement?(group: number, element: number): boolean; onDataElement?: DataElementCallback; + /** Called once the opening bytes say how the file is laid out. */ + onLayout?(layout: DicomLayout): void; }; export function* readDicomUntilPixelData(opts?: ReadDicomOptions) { const reader = new StreamingByteReader(); - // preamble - yield* reader.seek(128); - - // prefix - const prefix = yield* reader.readAscii(4); - if (prefix !== 'DICM') { - throw new Error('Not DICOM'); - } - - const info = yield* readFieldMetaInfo(reader, { - onDataElement: opts?.onDataElement, - }); - const explicitVr = info.transferSyntaxUid !== ImplicitTransferSyntaxUID; - const littleEndian = info.transferSyntaxUid !== ExplicitVRBigEndianUID; + // Peeked rather than read: a file without the Part 10 preamble has its + // first element at byte 0. + const head = yield* reader.read(PART_10_HEADER_LENGTH, { peek: true }); + const layout = sniffDicomLayout(head); + opts?.onLayout?.(layout); + if (layout.preamble) yield* reader.seek(PART_10_HEADER_LENGTH); + + const transferSyntaxUid = layout.fileMeta + ? (yield* readFieldMetaInfo(reader, { + onDataElement: opts?.onDataElement, + })).transferSyntaxUid + : layout.transferSyntaxUid; + // A negative boundary asks the metadata loader to retain the complete file. + if (transferSyntaxUid === DeflatedExplicitVRLittleEndianUID) + return { position: -1, transferSyntaxUid }; + const explicitVr = transferSyntaxUid !== ImplicitTransferSyntaxUID; + const littleEndian = transferSyntaxUid !== ExplicitVRBigEndianUID; yield* readDataElementsUntil( reader, @@ -381,6 +455,7 @@ export function* readDicomUntilPixelData(opts?: ReadDicomOptions) { return { position: reader.position, + transferSyntaxUid, }; } diff --git a/packages/dicom/core/streaming/dicom/readDicomHeader.ts b/packages/dicom/core/streaming/dicom/readDicomHeader.ts new file mode 100644 index 000000000..3d86d772e --- /dev/null +++ b/packages/dicom/core/streaming/dicom/readDicomHeader.ts @@ -0,0 +1,159 @@ +import { createDicomParser, ExplicitVRBigEndianUID } from './dicomParser'; +import { + IMPLICIT_VR_LITTLE_ENDIAN, + type DicomLayout, +} from '../../metadata/dicomLayout'; +import { concatBytes, toAscii } from '../../utils'; + +/** `skip-radiotherapy` returns after the Modality tag for RT objects. */ +export type ImageImportPolicy = 'complete-header' | 'skip-radiotherapy'; + +/** Where the Pixel Data element and its value sit in the source. */ +export type PixelDataElement = Readonly<{ + /** Offset of the element's tag. */ + offset: number; + valueOffset: number; + /** Value length in bytes; null for an undefined length, as encapsulated pixels have. */ + length: number | null; +}>; + +const MODALITY = [0x0008, 0x0060] as const; +const PIXEL_DATA = [0x7fe0, 0x0010] as const; +/** Tag, VR, reserved bytes and a 32 bit length: the longest element head. */ +const PIXEL_DATA_HEAD_LENGTH = 12; +const UNDEFINED_LENGTH = 0xffffffff; +const LONG_FORM_VRS = new Set(['OB', 'OD', 'OF', 'OL', 'OV', 'OW', 'UN']); + +const isTag = ( + tag: readonly [number, number], + group: number, + element: number +) => group === tag[0] && element === tag[1]; + +/** + * Radiotherapy objects are dropped on their modality alone, so nothing past + * that element is read: a structure set carries megabytes of contours. + */ +const isRadiotherapy = (modality: string | undefined) => + modality?.startsWith('RT') ?? false; + +function headerParser(policy: ImageImportPolicy) { + const found = { + modality: undefined as string | undefined, + layout: null as DicomLayout | null, + atPixelData: false, + }; + const parse = createDicomParser({ + stopAtElement: (group, element) => { + found.atPixelData = isTag(PIXEL_DATA, group, element); + return ( + found.atPixelData || + (policy === 'skip-radiotherapy' && isRadiotherapy(found.modality)) + ); + }, + onLayout: (layout) => { + found.layout = layout; + }, + onDataElement: (el) => { + if ( + isTag(MODALITY, el.group, el.element) && + el.data instanceof Uint8Array + ) + found.modality = toAscii(el.data).trim(); + }, + }); + return { parse, found }; +} + +type Parse = ReturnType['parse']; + +/** + * Reads until the parser stops, plus `trailing` bytes past that point. A + * negative stop position asks for the complete file, as a deflated one needs. + */ +async function readUntilStop( + stream: ReadableStream, + parse: Parse, + trailing: () => number +) { + const received: Uint8Array[] = []; + let total = 0; + let stop: { position: number; transferSyntaxUid: string } | null = null; + const result = () => ({ + received, + end: stop && stop.position >= 0 ? stop.position : undefined, + transferSyntaxUid: stop?.transferSyntaxUid ?? null, + }); + const reader = stream.getReader(); + try { + for (;;) { + const { end } = result(); + if (end !== undefined && total >= end + trailing()) return result(); + const { done, value } = await reader.read(); + if (done) return result(); + received.push(value); + total += value.length; + const parsed: ReturnType | null = stop ? null : parse(value); + if (parsed?.done) stop = parsed.value; + } + } finally { + // Not awaited, so the cancel lands before the stream refills its queue. + reader.cancel().catch(() => {}); + } +} + +/** Parses the Pixel Data element head; null when it is cut short or unexpected. */ +function pixelDataElement( + head: Uint8Array, + offset: number, + transferSyntaxUid: string +): PixelDataElement | null { + if (head.length < 8) return null; + const view = new DataView(head.buffer, head.byteOffset, head.byteLength); + const littleEndian = transferSyntaxUid !== ExplicitVRBigEndianUID; + const element = (length: number, headLength: number) => ({ + offset, + valueOffset: offset + headLength, + length: length === UNDEFINED_LENGTH ? null : length, + }); + if (transferSyntaxUid === IMPLICIT_VR_LITTLE_ENDIAN) + return element(view.getUint32(4, littleEndian), 8); + if ( + head.length < PIXEL_DATA_HEAD_LENGTH || + !LONG_FORM_VRS.has(toAscii(head.subarray(4, 6))) + ) + return null; + return element(view.getUint32(8, littleEndian), PIXEL_DATA_HEAD_LENGTH); +} + +/** + * Reads a stream up to its Pixel Data element head and cancels it there, + * since a stream that reads ahead pulls pixel data a header never uses. An + * object with no Pixel Data, such as a structured report, is header to its + * last byte. + */ +export async function readDicomHeader( + stream: ReadableStream, + policy: ImageImportPolicy = 'complete-header' +) { + const { parse, found } = headerParser(policy); + const { received, end, transferSyntaxUid } = await readUntilStop( + stream, + parse, + () => (found.atPixelData ? PIXEL_DATA_HEAD_LENGTH : 0) + ); + const header = concatBytes(received, end); + const head = + found.atPixelData && end !== undefined + ? concatBytes(received).subarray(end, end + PIXEL_DATA_HEAD_LENGTH) + : null; + return { + header, + layout: found.layout, + transferSyntaxUid, + pixelData: + head && transferSyntaxUid + ? pixelDataElement(head, end!, transferSyntaxUid) + : null, + }; +} diff --git a/packages/dicom/core/streaming/dicom/ultrasoundRegion.ts b/packages/dicom/core/streaming/dicom/ultrasoundRegion.ts new file mode 100644 index 000000000..14a9d8885 --- /dev/null +++ b/packages/dicom/core/streaming/dicom/ultrasoundRegion.ts @@ -0,0 +1,60 @@ +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { sequenceItems } from '../../metadata/functionalGroups'; +import type { DicomDataset } from '../../metadata/dicomDataset'; +import { trimDicomPadding } from '../../utils'; +import { Tags } from '../../metadata/dicomTags'; + +// DICOM unit codes for PhysicalUnitsXDirection / YDirection. +// See DICOM PS3.3 C.8.5.5.1.15. The only spatial spacing code defined for +// this field is 3 (cm). Other codes (0=none, 1=percent, 2=dB, 4=seconds, +// 5=hertz, 6=dB/sec, 7=cm/sec, 8=cm², 9=cm²/sec, 10=cm³, 11=cm³/sec, +// 12=degrees) are time, frequency, velocity, area, volume, or angle, so +// they are not converted to a VTK image spacing. +export const US_UNIT_CENTIMETERS = 3; + +// Returns the multiplier that converts a physical-delta value in the given +// unit to millimetres, or null when the unit is not a spatial spacing. +export const unitToMm = (code: number): number | null => { + if (code === US_UNIT_CENTIMETERS) return 10; + return null; +}; + +export type UltrasoundRegion = { + physicalDeltaX: number; + physicalDeltaY: number; + physicalUnitsXDirection: number; + physicalUnitsYDirection: number; +}; + +// First-region spacing plus the total number of regions in the source +// SequenceOfUltrasoundRegions. Multi-region images (e.g. dual-pane B-mode + +// Doppler) cannot be fully represented with a single VTK image spacing, so +// we expose the count to let callers warn about partial support. +export type UltrasoundRegions = { + region?: UltrasoundRegion; + regionCount: number; +}; + +/** The structured header supplies regions in either transfer syntax. */ +export function readUltrasoundRegions( + metadata: DicomDataset +): UltrasoundRegions { + const items = sequenceItems( + metadata, + Tags.SequenceOfUltrasoundRegions.replace('|', '') + ); + const value = (tag: string) => { + const text = trimDicomPadding(getDatasetTag(items[0], tag) ?? ''); + return text ? Number(text) : NaN; + }; + const region = { + physicalDeltaX: value(Tags.PhysicalDeltaX), + physicalDeltaY: value(Tags.PhysicalDeltaY), + physicalUnitsXDirection: value(Tags.PhysicalUnitsXDirection), + physicalUnitsYDirection: value(Tags.PhysicalUnitsYDirection), + }; + return { + regionCount: items.length, + ...(Object.values(region).every(Number.isFinite) ? { region } : {}), + }; +} diff --git a/src/core/streaming/httpCodes.ts b/packages/dicom/core/streaming/httpCodes.ts similarity index 100% rename from src/core/streaming/httpCodes.ts rename to packages/dicom/core/streaming/httpCodes.ts diff --git a/packages/dicom/core/streaming/requestPool.ts b/packages/dicom/core/streaming/requestPool.ts new file mode 100644 index 000000000..896cd263d --- /dev/null +++ b/packages/dicom/core/streaming/requestPool.ts @@ -0,0 +1,110 @@ +import { Deferred, defer } from '../utils'; + +type FetchRequest = { + request: RequestInfo | URL; + init?: RequestInit; + deferred: Deferred; + controller: AbortController; + cleanup: () => void; +}; + +/** A FIFO request pool. Disposal aborts active fetches and rejects queued callers. */ +export class RequestPool { + private queue: FetchRequest[] = []; + private inflight = new Set(); + private disposed = false; + private lifetime = new AbortController(); + + constructor( + public readonly poolSize = 24, + private fetchFn: typeof fetch = (input, init) => + globalThis.fetch(input, init) + ) { + if (!Number.isInteger(poolSize) || poolSize < 1) + throw new Error('Request concurrency must be a positive integer'); + } + + get activeConnections() { + return this.inflight.size; + } + + fetch = (request: RequestInfo | URL, init?: RequestInit) => { + if (this.disposed) + return Promise.reject( + new DOMException('Request pool disposed', 'AbortError') + ); + const deferred = defer(); + const controller = new AbortController(); + const sourceSignal = + init?.signal ?? (request instanceof Request ? request.signal : undefined); + const abort = () => { + controller.abort(sourceSignal?.reason); + deferred.reject(sourceSignal?.reason); + this.queue = this.queue.filter((entry) => entry !== queued); + }; + const onDispose = () => controller.abort(this.lifetime.signal.reason); + const queued: FetchRequest = { + request, + init, + deferred, + controller, + cleanup: () => { + sourceSignal?.removeEventListener('abort', abort); + this.lifetime.signal.removeEventListener('abort', onDispose); + }, + }; + if (sourceSignal?.aborted) { + deferred.reject(sourceSignal.reason); + return deferred.promise; + } + sourceSignal?.addEventListener('abort', abort, { once: true }); + this.lifetime.signal.addEventListener('abort', onDispose, { once: true }); + controller.signal.addEventListener('abort', queued.cleanup, { once: true }); + this.queue.push(queued); + this.processQueue(); + return deferred.promise; + }; + + dispose() { + this.disposed = true; + const error = new DOMException('Request pool disposed', 'AbortError'); + this.lifetime.abort(error); + [...this.queue, ...this.inflight].forEach((request) => { + request.controller.abort(error); + request.deferred.reject(error); + request.cleanup(); + }); + this.queue = []; + } + + private processQueue() { + while ( + !this.disposed && + this.inflight.size < this.poolSize && + this.queue.length + ) { + this.startRequest(this.queue.shift()!); + } + } + + private async startRequest(request: FetchRequest) { + this.inflight.add(request); + try { + const fetchFn = this.fetchFn; + const response = await fetchFn(request.request, { + ...request.init, + signal: request.controller.signal, + }); + if (request.controller.signal.aborted) { + response.body?.cancel().catch(() => {}); + request.deferred.reject(request.controller.signal.reason); + } else request.deferred.resolve(response); + } catch (error) { + request.cleanup(); + request.deferred.reject(error); + } finally { + this.inflight.delete(request); + this.processQueue(); + } + } +} diff --git a/src/core/streaming/streamingByteReader.ts b/packages/dicom/core/streaming/streamingByteReader.ts similarity index 96% rename from src/core/streaming/streamingByteReader.ts rename to packages/dicom/core/streaming/streamingByteReader.ts index 902fd9f1c..41d606ad0 100644 --- a/src/core/streaming/streamingByteReader.ts +++ b/packages/dicom/core/streaming/streamingByteReader.ts @@ -1,5 +1,5 @@ -import ByteDeque from '@/src/core/streaming/byteDeque.js'; -import { toAscii } from '@/src/utils'; +import ByteDeque from './byteDeque'; +import { toAscii } from '../utils'; /** * StreamingByteReader diff --git a/packages/dicom/core/streaming/types.ts b/packages/dicom/core/streaming/types.ts new file mode 100644 index 000000000..863594a74 --- /dev/null +++ b/packages/dicom/core/streaming/types.ts @@ -0,0 +1,20 @@ +/** + * Init options for a Fetcher. + */ +export type FetcherInit = { + abortController?: AbortController; +}; + +/** + * A source of bytes that can be streamed from the start or taken whole. + */ +export type Fetcher = { + connect(): Promise; + getStream(): ReadableStream; + blob(): Promise; + close(): void; + connected: boolean; + size: number; + contentType?: string; + abortSignal?: AbortSignal; +}; diff --git a/packages/dicom/core/utils.ts b/packages/dicom/core/utils.ts new file mode 100644 index 000000000..304ef325a --- /dev/null +++ b/packages/dicom/core/utils.ts @@ -0,0 +1,77 @@ +export type Maybe = T | null | undefined; +export type Awaitable = T | Promise; +/** Boundary padding accepted by numeric readers, without changing the stored text. */ +export const trimDicomPadding = (value: string) => + value.replace(/^[\s\0]+|[\s\0]+$/g, ''); + +type PromiseResolveFunction = (value: T) => void; +type PromiseRejectFunction = (reason?: any) => void; +export type Deferred = { + promise: Promise; + resolve: PromiseResolveFunction; + reject: PromiseRejectFunction; +}; + +export function defer(): Deferred { + let innerResolve: PromiseResolveFunction | null = null; + let innerReject: PromiseRejectFunction | null = null; + + const resolve = (value: T) => { + if (innerResolve) innerResolve(value); + }; + const reject = (reason?: Error) => { + if (innerReject) innerReject(reason); + }; + + const promise = new Promise((res, rej) => { + innerResolve = res; + innerReject = rej; + }); + + return { promise, resolve, reject }; +} +export function concatBytes( + parts: readonly Uint8Array[], + length = parts.reduce((total, part) => total + part.length, 0) +) { + const out = new Uint8Array(length); + parts.reduce((offset, part) => { + if (offset >= length) return offset; + const slice = part.subarray(0, length - offset); + out.set(slice, offset); + return offset + slice.length; + }, 0); + return out; +} + +export function toAscii( + bytes: Uint8Array | Uint8ClampedArray, + { ignoreNulls = false } = {} +) { + const chars = []; + for (let i = 0; i < bytes.length; i++) { + if (!(ignoreNulls && bytes[i] === 0)) { + chars.push(String.fromCharCode(bytes[i])); + } + } + return chars.join(''); +} + +/** + * Wraps a generator as a coroutine. + * @param generator + * @param args + * @returns + */ +export function asCoroutine(gen: Generator) { + // run initial code + const result = gen.next(); + if (result.done) return () => result; + return (value: N): IteratorResult => gen.next(value); +} + +export const numberOr = (value: string | undefined, fallback: number) => { + const text = trimDicomPadding(value ?? ''); + const number = Number(text); + return text && Number.isFinite(number) ? number : fallback; +}; diff --git a/src/utils/__tests__/parseContentRangeHeader.spec.ts b/packages/dicom/core/utils/__tests__/parseContentRangeHeader.spec.ts similarity index 94% rename from src/utils/__tests__/parseContentRangeHeader.spec.ts rename to packages/dicom/core/utils/__tests__/parseContentRangeHeader.spec.ts index fe397107e..7f0837449 100644 --- a/src/utils/__tests__/parseContentRangeHeader.spec.ts +++ b/packages/dicom/core/utils/__tests__/parseContentRangeHeader.spec.ts @@ -1,4 +1,4 @@ -import { parseContentRangeHeader } from '@/src/utils/parseContentRangeHeader'; +import { parseContentRangeHeader } from '../parseContentRangeHeader'; import { describe, expect, it } from 'vitest'; describe('parseContentRangeHeader', () => { diff --git a/packages/dicom/core/utils/abort.ts b/packages/dicom/core/utils/abort.ts new file mode 100644 index 000000000..dc0859366 --- /dev/null +++ b/packages/dicom/core/utils/abort.ts @@ -0,0 +1,37 @@ +/** + * A controller that aborts as soon as any parent signal does, with its reason. + * `release` detaches it from long-lived parents once its work is done. + */ +export function linkedController(...signals: AbortSignal[]) { + const controller = new AbortController(); + const onAbort = (event: Event) => + controller.abort((event.target as AbortSignal).reason); + const release = () => + signals.forEach((signal) => signal.removeEventListener('abort', onAbort)); + const aborted = signals.find((signal) => signal.aborted); + if (aborted) controller.abort(aborted.reason); + else + signals.forEach((signal) => + signal.addEventListener('abort', onAbort, { once: true }) + ); + controller.signal.addEventListener('abort', release, { once: true }); + return { controller, release }; +} + +export const abortError = (message: string) => + new DOMException(message, 'AbortError'); + +export const isAbortError = (error: unknown) => + error instanceof Error && error.name === 'AbortError'; + +/** Settles with the signal's reason on abort, without stopping the work itself. */ +export function untilAborted(operation: Promise, signal: AbortSignal) { + return new Promise((resolve, reject) => { + const aborted = () => reject(signal.reason); + signal.addEventListener('abort', aborted, { once: true }); + operation + .then(resolve, reject) + .finally(() => signal.removeEventListener('abort', aborted)); + if (signal.aborted) aborted(); + }); +} diff --git a/src/utils/parseContentRangeHeader.ts b/packages/dicom/core/utils/parseContentRangeHeader.ts similarity index 100% rename from src/utils/parseContentRangeHeader.ts rename to packages/dicom/core/utils/parseContentRangeHeader.ts diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts new file mode 100644 index 000000000..4993e33f7 --- /dev/null +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from 'vitest'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { sliceDataset } from '../../collections/__tests__/sliceFixture'; +import { allocateVolume } from '../allocateVolume'; +import { allocated, pixelSlice, plannedUpdate } from './volumeFixture'; + +describe('allocateVolume', () => { + it('allocates an empty buffer placed by the planned stack', () => { + const members = [7, 5, 6].map((z) => pixelSlice(z)); + + const volume = allocated(members); + + expect(volume.members).toEqual([members[1], members[2], members[0]]); + expect(volume.dimensions).toEqual([4, 4, 3]); + expect(volume.components).toBe(1); + expect(volume.origin).toEqual([0, 0, 5]); + expect(volume.spacing).toEqual([0.5, 0.5, 1]); + expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); + expect(volume.reconstruction.slots).toEqual([0, 1, 2]); + expect(volume.data).toBeInstanceOf(Uint16Array); + expect(volume.data).toHaveLength(48); + expect([...volume.loaded]).toEqual([0, 0, 0]); + expect(volume.spatialMetadata.axes.map((axis) => axis.status)).toEqual([ + 'declared', + 'declared', + 'derived', + ]); + expect(Object.isFrozen(volume)).toBe(true); + }); + + it.each([ + [{ '0028|0103': '1' }, Int16Array], + [{ '0028|1053': '0.5' }, Float32Array], + [{ '0028|0101': '8' }, Uint8Array], + ])('chooses the buffer type for pixel tags %j', (tags, type) => { + const volume = allocated([ + pixelSlice(0, { tags }), + pixelSlice(1, { tags }), + ]); + expect(volume.data).toBeInstanceOf(type); + }); + + it('keeps an irregular stack in order unless the policy rejects it', () => { + const members = [0, 1, 3].map((z) => pixelSlice(z)); + + expect(allocated(members).dimensions[2]).toBe(3); + expect(() => + allocated(members, undefined, { irregularGeometry: 'reject' }) + ).toThrow(/irregular/); + }); + + it('uses the planned spacing and slice mapping without reconstructing it', () => { + const update = plannedUpdate([pixelSlice(1), pixelSlice(19)]); + const reconstruction = { + kind: 'regular' as const, + sliceSpacing: 9, + slots: [0, 2], + }; + + const result = allocateVolume({ + ...update, + collection: { ...update.collection, reconstruction }, + }); + + expect(result).toMatchObject({ + kind: 'volume', + volume: { dimensions: [4, 4, 3], spacing: [0.5, 0.5, 9] }, + }); + }); + + it('rejects a plan whose first slice slot is not zero', () => { + const update = plannedUpdate([pixelSlice(10), pixelSlice(20)]); + const reconstruction = { + kind: 'regular' as const, + sliceSpacing: 10, + slots: [1, 2], + }; + + expect(() => + allocateVolume({ + ...update, + collection: { ...update.collection, reconstruction }, + }) + ).toThrow('slice slot'); + }); + + it.each(['SEG', 'SEG\u0000'])( + 'reports SEG modality %j as a segmentation outcome instead of allocating it', + (modality) => { + const seg = instanceFor(sliceDataset({ modality })); + + const result = allocateVolume(plannedUpdate([seg])); + + expect(result).toMatchObject({ kind: 'segmentation', members: [seg] }); + } + ); + + it('applies the first ultrasound region as display spacing', () => { + const { dataset, source } = pixelSlice(0, { modality: 'US' }); + const ultrasound = { + ...instanceFor(dataset, source), + ultrasoundRegions: { + regionCount: 1, + region: { + physicalDeltaX: 0.01, + physicalDeltaY: 0.02, + physicalUnitsXDirection: 3, + physicalUnitsYDirection: 3, + }, + }, + }; + + const volume = allocated([ultrasound]); + + expect(volume.spacing[0]).toBeCloseTo(0.1); + expect(volume.spacing[1]).toBeCloseTo(0.2); + expect(volume.warnings).toEqual([]); + }); +}); diff --git a/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts b/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts new file mode 100644 index 000000000..fcf33005d --- /dev/null +++ b/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts @@ -0,0 +1,563 @@ +import { describe, expect, it } from 'vitest'; +import type { DicomDataset } from '../../metadata/dicomDataset'; +import { + readGeometryFacts, + readInstanceFacts, +} from '../../collections/instanceFacts'; +import { + planDicomCollections, + IRREGULAR_VOLUME_WARNING, + REPEATED_POSITIONS_WARNING, + UNREADABLE_FRAME_GEOMETRY_WARNING, + type DicomCollection, +} from '../../collections/planDicomCollections'; +import type { Reconstruction } from '../../collections/reconstructVolume'; +import { + emptyRegistry, + registerInstances, +} from '../../collections/instanceRegistry'; +import { getFrameTag } from '../../metadata/functionalGroups'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { createDicomRuntime } from '../../runtime/createDicomRuntime'; +import { fromBlob } from '../../source/byteSource'; +import { + allocateVolume, + type Volume, + type VolumeAllocation, +} from '../allocateVolume'; +import { loadVolume } from '../loadVolume'; +import type { IrregularGeometryPolicy } from '../volumeLayout'; +import { datasetFromTags } from '../../../../../tests/dicomDataset'; + +const tags = (values: Record) => + datasetFromTags(Object.entries(values)); + +function sequence(tag: string, items: DicomDataset[]) { + return { + tag, + group: parseInt(tag.slice(0, 4), 16), + element: parseInt(tag.slice(4), 16), + vr: 'SQ', + values: { kind: 'sequence' as const, items }, + }; +} + +const groups = (items: Array>): DicomDataset => ({ + specificCharacterSet: null, + elements: items, +}); + +function enhanced( + shared: DicomDataset, + frames: DicomDataset[], + root: Record = {} +): DicomDataset { + const header = tags({ + '00280010': '2', + '00280011': '2', + '00280008': String(frames.length), + '00280101': '16', + ...root, + }); + return { + ...header, + elements: [ + ...header.elements, + sequence('52009229', [shared]), + sequence('52009230', frames), + ], + }; +} + +const positioned = (position: string) => + groups([sequence('00209113', [tags({ '00200032': position })])]); + +const ONE_SLOT: Reconstruction = { + kind: 'regular', + sliceSpacing: null, + slots: [0], +}; + +const asVolume = (allocation: VolumeAllocation) => { + if (allocation.kind !== 'volume') throw new Error('Expected a volume'); + return allocation.volume; +}; + +/** Allocates one instance against a supplied plan, as a planner would hand it. */ +const allocate = ( + metadata: DicomDataset, + policy: IrregularGeometryPolicy = 'preserve-order', + { orientation = null, reconstruction = ONE_SLOT } = {} as Partial< + Pick + > +) => + asVolume( + allocateVolume( + { + id: 'frames', + collection: { orientation, reconstruction } as DicomCollection, + members: [instanceFor(metadata)], + }, + { irregularGeometry: policy } + ) + ); + +const indexToWorld = (volume: Volume, index: number[]) => + [0, 1, 2].map( + (component) => + volume.origin[component] + + index.reduce( + (sum, step, axis) => + sum + + step * volume.spacing[axis] * volume.direction[axis * 3 + component], + 0 + ) + ); + +const ctShared = () => + groups([ + sequence('00289110', [tags({ '00280030': '.388672\\.388672' })]), + sequence('00209116', [tags({ '00200037': '-1\\0\\0\\0\\1\\0' })]), + sequence('00289145', [tags({ '00281052': '-1024', '00281053': '1' })]), + ]); + +describe('enhanced volume Functional Groups', () => { + it('places stored enhanced CT frames at their patient positions and preserves negative values', () => { + const metadata = enhanced(ctShared(), [ + positioned('99.5\\-301.5\\-159'), + positioned('99.5\\-301.5\\-149'), + ]); + const volume = allocate(metadata, 'reject'); + expect(volume.spacing).toEqual([0.388672, 0.388672, 10]); + expect(indexToWorld(volume, [0, 0, 0])).toEqual([99.5, -301.5, -159]); + expect(indexToWorld(volume, [0, 0, 1])).toEqual([99.5, -301.5, -149]); + const buffer = volume.data; + buffer[0] = -1024; + buffer[4] = 172; + expect([buffer[0], buffer[4]]).toEqual([-1024, 172]); + expect(buffer).toBeInstanceOf(Float32Array); + }); + + it('uses the storage direction for an oblique enhanced MR stack', () => { + const metadata = enhanced( + groups([ + sequence('00289110', [tags({ '00280030': '1\\1' })]), + sequence('00209116', [ + tags({ + '00200037': + '0\\0.9762960207\\-0.2164395526\\0\\-0.2164395526\\-0.9762960207', + }), + ]), + ]), + [ + positioned('-83.2177146\\-123.869376\\159.934076'), + positioned('-81.8877146\\-123.869376\\159.934076'), + ] + ); + const volume = allocate(metadata, 'reject'); + expect(volume.spacing[2]).toBeCloseTo(1.33, 8); + expect(indexToWorld(volume, [0, 0, 1])[0]).toBeCloseTo(-81.8877146, 7); + expect(volume.direction[1]).toBeCloseTo(0.9762960207, 8); + expect(volume.direction[5]).toBeCloseTo(-0.9762960207, 8); + }); + + it('unions per-frame calibration and lets capable custom decoders preserve it', async () => { + const frames = [ + groups([ + sequence('00289145', [tags({ '00281053': '1', '00281052': '-1024' })]), + ]), + groups([ + sequence('00289145', [tags({ '00281053': '.5', '00281052': '-500' })]), + ]), + ]; + const metadata = enhanced(groups([]), frames); + const decoded = new Float64Array([ + -1024, -1023, -1022, -1021, -499.5, -499, -498.5, -498, + ]); + let suppliedMetadata: DicomDataset | undefined; + const runtime = createDicomRuntime({ + decodeConcurrency: 1, + decoder: async ({ instance }) => { + suppliedMetadata = instance.dataset; + return { size: [2, 2, 2], imageType: { components: 1 }, data: decoded }; + }, + }); + const instance = instanceFor(metadata, fromBlob(new Blob(['pixels']))); + const [update] = registerInstances(emptyRegistry, [instance]).updates; + const volume = asVolume(allocateVolume(update)); + for await (const loaded of loadVolume(volume, { + runtime, + signal: new AbortController().signal, + })) + expect(loaded).not.toHaveProperty('error'); + runtime.dispose(); + expect(suppliedMetadata).toBe(metadata); + expect(Array.from(volume.data)).toEqual(Array.from(decoded)); + }); + + it('accepts shared and per-frame calibration with equal numeric values', () => { + const metadata = enhanced( + groups([ + sequence('00289145', [tags({ '00281053': '.5', '00281052': '-1024' })]), + ]), + [ + groups([]), + groups([ + sequence('00289145', [ + tags({ + '00281053': '0.500\u0000', + '00281052': '-1024.0\u0000', + }), + ]), + ]), + ] + ); + const { data } = allocate(metadata); + expect(data).toBeInstanceOf(Float32Array); + data[0] = -1023.5; + expect(data[0]).toBe(-1023.5); + }); + + it.each([ + ['repeated-position', [0, 0, 2]], + ['uneven-slice-spacing', [0, 1, 3]], + ])( + 'honors the irregular geometry policy for %s frames', + (reason, positions) => { + const metadata = enhanced( + ctShared(), + positions.map((z) => positioned(`0\\0\\${z}`)) + ); + expect(() => allocate(metadata, 'reject')).toThrow(reason); + expect(allocate(metadata).dimensions).toEqual([2, 2, 3]); + } + ); + + it('rejects changing frame orientation instead of claiming a regular lattice', () => { + const second = positioned('0\\0\\1'); + second.elements.push( + sequence('00209116', [tags({ '00200037': '0\\1\\0\\1\\0\\0' })]) + ); + expect(() => + allocate(enhanced(ctShared(), [positioned('0\\0\\0'), second]), 'reject') + ).toThrow('unreadable-geometry'); + }); + + it('rejects changing pixel spacing and temporal frames under the regular geometry policy', () => { + const changedSpacing = positioned('0\\0\\1'); + changedSpacing.elements.push( + sequence('00289110', [tags({ '00280030': '2\\2' })]) + ); + expect(() => + allocate( + enhanced(ctShared(), [positioned('0\\0\\0'), changedSpacing]), + 'reject' + ) + ).toThrow('mixed-pixel-spacing'); + const temporal = [0, 1].map((index) => { + const frame = positioned(`0\\0\\${index}`); + frame.elements.push( + sequence('00209111', [tags({ '00209128': String(index + 1) })]) + ); + return frame; + }); + expect(() => allocate(enhanced(ctShared(), temporal), 'reject')).toThrow( + 'unreadable-geometry' + ); + }); + + it('reads OCT in-plane calibration without using optical depth of field as frame separation', () => { + const metadata = enhanced( + groups([ + sequence('00289110', [ + tags({ + '00280030': '.001955034\\.01174168\u0000', + '00180050': '.002', + }), + ]), + ]), + [groups([]), groups([])] + ); + expect(allocate(metadata).spacing).toEqual([0.01174168, 0.001955034, 1]); + }); + + it('reads exact macro paths without changing raw tags or importing referenced-image geometry', () => { + const metadata = enhanced(ctShared(), [positioned('1\\2\\3')], { + '00280030': '9\\9', + }); + metadata.elements.push( + sequence('00081140', [tags({ '00200037': '0\\1\\0\\0\\0\\1' })]) + ); + const before = JSON.stringify(metadata); + expect(readGeometryFacts(metadata)).toEqual({ + orientation: [-1, 0, 0, 0, 1, 0], + position: [1, 2, 3], + pixelSpacing: [0.388672, 0.388672], + }); + expect(getFrameTag(metadata, '00280030')).toBe('.388672\\.388672'); + expect(JSON.stringify(metadata)).toBe(before); + const rootOnly = tags({ '00280030': '2\\3' }); + rootOnly.elements.push( + sequence('00081140', [tags({ '00200037': '0\\1\\0\\0\\0\\1' })]) + ); + expect(readGeometryFacts(rootOnly).orientation).toBeNull(); + }); +}); + +describe('intra-instance frame planning', () => { + const collectionOf = (metadata: DicomDataset) => + planDicomCollections({ + seriesKey: 'frames', + instances: [readInstanceFacts(metadata)], + }).collections[0]; + + it.each([1, -1])( + 'preserves stored frame direction %s through registration and image allocation', + async (direction) => { + const positions = [0, 1, 2].map((index) => 10 + direction * index * 3); + const instance = instanceFor( + enhanced( + ctShared(), + positions.map((z) => positioned(`1\\2\\${z}`)) + ) + ); + const { updates } = registerInstances(emptyRegistry, [instance]); + const volume = asVolume(allocateVolume(updates[0])); + expect(volume.spacing[2]).toBe(3); + positions.forEach((z, index) => + expect(indexToWorld(volume, [0, 0, index])).toEqual([1, 2, z]) + ); + } + ); + + it('rejects shared-plane temporal frames under strict geometry validation', () => { + const shared = ctShared(); + shared.elements.push( + sequence('00209113', [tags({ '00200032': '10\\20\\30' })]) + ); + const metadata = enhanced( + shared, + [1, 2].map((time) => + groups([sequence('00209111', [tags({ '00209128': String(time) })])]) + ) + ); + const collection = collectionOf(metadata); + expect(collection.reconstruction).toMatchObject({ + kind: 'irregular', + slots: [0], + }); + expect(collection.warnings).toContain(UNREADABLE_FRAME_GEOMETRY_WARNING); + expect(() => allocate(metadata, 'reject', collection)).toThrow( + 'irregular DICOM geometry' + ); + }); + + it('keeps an unreadable frame geometry warning for a lone multiframe source', () => { + const metadata = enhanced( + ctShared(), + [1, 2].map((index) => + groups([sequence('00209111', [tags({ '00209057': String(index) })])]) + ) + ); + const collection = collectionOf(metadata); + expect(collection.reconstruction).toMatchObject({ + kind: 'irregular', + reason: 'unreadable-geometry', + slots: [0], + }); + expect(collection.warnings).toContain(UNREADABLE_FRAME_GEOMETRY_WARNING); + }); + + it.each([ + [[0, 1, 3], 'uneven-slice-spacing', IRREGULAR_VOLUME_WARNING], + [[0, 0, 2], 'repeated-position', REPEATED_POSITIONS_WARNING], + ] as const)( + 'reports intra-instance geometry %s while retaining one source slot', + async (positions, reason, warning) => { + const metadata = enhanced( + ctShared(), + positions.map((z) => positioned(`0\\0\\${z}`)) + ); + const collection = collectionOf(metadata); + expect(collection.reconstruction).toMatchObject({ + kind: 'irregular', + reason, + slots: [0], + }); + expect(collection.warnings).toContain(warning); + const volume = allocate(metadata, 'preserve-order', { + orientation: collection.orientation, + }); + expect(volume.reconstruction).toEqual(collection.reconstruction); + expect(volume.dimensions).toEqual([2, 2, 3]); + } + ); +}); + +function nmMetadata(overrides: Record = {}) { + const metadata = tags({ + '00080016': '1.2.840.10008.5.1.4.1.1.20', + '00080008': 'ORIGINAL\\PRIMARY\\RECON TOMO\\EMISSION', + '00280010': '2', + '00280011': '2', + '00280008': '3', + '00280101': '16', + '00280030': '4.7951998710632\\4.7951998710632', + '00180088': '-4.7951998710632', + '00540021': '1', + '00540081': '3', + '00540080': '1\\2\\3', + ...overrides, + }); + metadata.elements.push( + sequence('00540022', [ + tags({ + '00200032': '4\\5\\6', + '00200037': '1\\0\\0\\0\\1\\0', + }), + ]) + ); + metadata.elements.push({ + tag: '00280009', + group: 0x0028, + element: 0x0009, + vr: 'AT', + values: { + kind: 'attributeTag', + values: [{ group: 0x0054, element: 0x0080 }], + }, + }); + return metadata; +} + +describe('reconstructed NM spatial volumes', () => { + it.each(['00200032', '00200037', '00280030', '00180088'])( + 'displays NM frames when Type 2 geometry %s is empty', + (tag) => { + const metadata = nmMetadata(); + const detector = metadata.elements.find( + (element) => element.tag === '00540022' + )!.values; + const source = + (tag === '00200032' || tag === '00200037') && + detector.kind === 'sequence' + ? detector.items[0] + : metadata; + source.elements = source.elements.map((element) => + element.tag === tag ? tags({ [tag]: '' }).elements[0] : element + ); + const volume = allocate(metadata); + const { spatialMetadata } = volume; + expect(volume.dimensions).toEqual([2, 2, 3]); + if (tag === '00200032') { + expect(volume.origin).toEqual([0, 0, 0]); + expect(spatialMetadata.notes.join(' ')).toContain('zero origin'); + } else if (tag === '00200037') { + expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); + expect(spatialMetadata.notes.join(' ')).toContain('default axes'); + } else { + const axis = tag === '00280030' ? 0 : 2; + expect(volume.spacing[axis]).toBe(1); + expect(spatialMetadata.axes[axis].status).toBe('fallback'); + } + if (tag !== '00180088') expect(volume.spacing[2]).toBe(4.7951998710632); + } + ); + + it.each([-1, 1])( + 'uses the detector plane and signed NM slice progression %s', + (sign) => { + const volume = allocate( + nmMetadata({ '00180088': String(sign * 4.7951998710632) }), + 'reject' + ); + expect(volume.spacing).toEqual([ + 4.7951998710632, 4.7951998710632, 4.7951998710632, + ]); + expect(volume.origin).toEqual([4, 5, 6]); + expect(indexToWorld(volume, [0, 0, 2])[2]).toBeCloseTo( + 6 + sign * 2 * 4.7951998710632, + 10 + ); + } + ); + + it('retains one NM detector plane when Type 2 slice spacing is unknown', () => { + const metadata = nmMetadata({ + '00280008': '1', + '00540081': '1', + '00540080': '1', + '00180088': '', + }); + const volume = allocate(metadata, 'reject'); + expect(volume.origin).toEqual([4, 5, 6]); + expect(volume.spacing).toEqual([4.7951998710632, 4.7951998710632, 1]); + expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); + }); + + it('rejects a gated acquisition instead of treating time slots as additional slices', () => { + const metadata = nmMetadata({ + '00080008': 'ORIGINAL\\PRIMARY\\RECON GATED TOMO\\EMISSION', + '00280008': '264', + '00540081': '33', + '00540071': '8', + }); + expect(() => allocate(metadata)).toThrow( + 'Unsupported NM volume with multiple spatial/time dimensions' + ); + }); + + it.each(['1\\3\\2', '1\\2\\2', '1\\2'])( + 'rejects nonsequential NM frame ordering %s', + (indices) => { + expect(() => allocate(nmMetadata({ '00540080': indices }))).toThrow( + 'slice indices' + ); + } + ); + + it('rejects hidden nonspatial indices even when the frame count matches the slice count', () => { + expect(() => allocate(nmMetadata({ '00540070': '1\\1\\2' }))).toThrow( + 'multiple spatial/time dimensions' + ); + }); + + it('does not infer a spatial volume from multiple detectors or unrelated nested coordinates', () => { + expect(() => allocate(nmMetadata({ '00540021': '2' }))).toThrow( + 'detectors' + ); + const metadata = nmMetadata(); + metadata.elements = metadata.elements.filter( + (element) => element.tag !== '00540022' + ); + metadata.elements.push( + sequence('00081140', [ + tags({ + '00200032': '1\\2\\3', + '00200037': '1\\0\\0\\0\\1\\0', + }), + ]) + ); + expect(readGeometryFacts(metadata).position).toBeNull(); + expect(() => allocate(metadata)).toThrow('detectors'); + }); +}); + +it('does not report normal segment-major SEG frames as an irregular volume', () => { + const metadata = enhanced( + ctShared(), + [0, 1, 0, 1].map((z) => positioned('0\\0\\' + z)), + { '00080060': 'SEG' } + ); + const plan = planDicomCollections({ + seriesKey: 'seg', + instances: [readInstanceFacts(metadata)], + }); + expect(plan.collections[0].warnings).toEqual([]); +}); + +it('reports a missing NM NumberOfSlices without claiming temporal dimensions', () => { + const metadata = nmMetadata(); + metadata.elements = metadata.elements.filter((el) => el.tag !== '00540081'); + expect(() => allocate(metadata)).toThrow('without NumberOfSlices'); +}); diff --git a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts new file mode 100644 index 000000000..0f3808dac --- /dev/null +++ b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -0,0 +1,239 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { + createDicomRuntime, + type DicomRuntime, +} from '../../runtime/createDicomRuntime'; +import { readInstance } from '../../instance/readInstance'; +import { + fromBlob, + fromUrl, + type ByteRange, + type ByteSource, +} from '../../source/byteSource'; +import { loadVolume, type VolumeUpdate } from '../loadVolume'; +import { allocated } from './volumeFixture'; +import { hangingSource } from '../../source/__tests__/sourceFixtures'; +import { + nativePixelDicom, + patternWords, + type NativePixelOptions, +} from '@/tests/nativePixelDicom'; + +const runtimes: DicomRuntime[] = []; +afterEach(() => runtimes.splice(0).forEach((runtime) => runtime.dispose())); + +/** No decoder assets: anything not decoded natively fails loudly. */ +const nativeOnly = () => { + const runtime = createDicomRuntime({}); + runtimes.push(runtime); + return runtime; +}; + +const signal = () => new AbortController().signal; + +/** A source that records the range of every read it opens. */ +const recorded = (source: ByteSource) => { + const ranges: Array = []; + return { + ranges, + source: { + ...source, + read: (readSignal: AbortSignal, range?: ByteRange) => { + ranges.push(range); + return source.read(readSignal, range); + }, + } satisfies ByteSource, + }; +}; + +const blobOf = (bytes: Uint8Array) => + fromBlob(new Blob([bytes as Uint8Array])); + +const load = async ( + members: Awaited>[], + options: { readAhead?: number; abort?: AbortSignal } = {} +) => { + const volume = allocated(members); + const updates: VolumeUpdate[] = []; + for await (const update of loadVolume(volume, { + runtime: nativeOnly(), + signal: options.abort ?? signal(), + readAhead: options.readAhead, + })) + updates.push(update); + return { volume, updates }; +}; + +const FRAMES = 5; +const multiframe = (options: NativePixelOptions = {}) => { + const words = patternWords(FRAMES * 6, 16); + return { + words, + bytes: nativePixelDicom({ + rows: 2, + columns: 3, + frames: FRAMES, + words, + ...options, + }), + }; +}; + +describe('loadVolume with native frames', () => { + it('loads each frame of a multiframe instance from its own ranged read', async () => { + const { bytes, words } = multiframe(); + const { source, ranges } = recorded(blobOf(bytes)); + const instance = await readInstance(source, signal()); + + const { volume, updates } = await load([instance], { readAhead: 1 }); + + const start = instance.pixelData!.valueOffset; + expect(updates.map((update) => update.slot)).toEqual([0, 4, 2, 1, 3]); + expect(updates[2]).toEqual({ + slot: 2, + extent: [0, 2, 0, 1, 2, 2], + range: [ + [Math.min(...words.slice(12, 18)), Math.max(...words.slice(12, 18))], + ], + }); + expect(ranges).toEqual([ + undefined, + ...[0, 4, 2, 1, 3].map((frame) => ({ + start: start + frame * 12, + end: start + (frame + 1) * 12, + })), + ]); + expect(Array.from(volume.data)).toEqual(words); + }); + + it('reports the float32-rounded range a Float32 volume stores', async () => { + const { bytes, words } = multiframe({ rescale: [0.1, 0.3] }); + const instance = await readInstance(blobOf(bytes), signal()); + + const { volume, updates } = await load([instance]); + + const frame = words.slice(0, 6).map((stored) => stored * 0.1 + 0.3); + expect(volume.data).toBeInstanceOf(Float32Array); + expect(updates.find(({ slot }) => slot === 0)).toMatchObject({ + range: [ + [Math.fround(Math.min(...frame)), Math.fround(Math.max(...frame))], + ], + }); + expect(Array.from(volume.data.subarray(0, 6))).toEqual( + frame.map(Math.fround) + ); + }); + + it('reads a single-frame file from its Pixel Data value onwards', async () => { + const files = [1, 2, 3].map((instance) => + nativePixelDicom({ + instance, + position: [0, 0, instance], + rescale: [1, -1000], + bitsStored: 12, + }) + ); + const sources = files.map((bytes) => recorded(blobOf(bytes))); + const members = await Promise.all( + sources.map(({ source }) => readInstance(source, signal())) + ); + + const { volume, updates } = await load(members); + + expect(updates.map((update) => update.slot)).toEqual([1, 0, 2]); + sources.forEach(({ ranges }, index) => + expect(ranges[1]).toEqual({ + start: members[index].pixelData!.valueOffset, + end: members[index].pixelData!.valueOffset + 30, + }) + ); + expect(volume.loaded).toEqual(new Uint8Array([1, 1, 1])); + expect(volume.data).toBeInstanceOf(Int16Array); + }); + + it.each([ + [true, 1 + FRAMES], + [false, 3], + ])( + 'reads frames from a server that honours Range (%s) in %i requests', + async (honoured, requests) => { + const { bytes, words } = multiframe(); + const asked: Array = []; + const fetchFn: typeof fetch = async (_url, init) => { + const range = new Headers(init?.headers).get('Range'); + asked.push(range); + const [, from, to] = /bytes=(\d+)-(\d+)/.exec(range ?? '') ?? []; + return honoured && from + ? new Response(bytes.slice(Number(from), Number(to) + 1), { + status: 206, + }) + : new Response(bytes.slice()); + }; + const instance = await readInstance( + fromUrl('https://example.test/frames.dcm', { fetch: fetchFn }), + signal() + ); + + const { volume } = await load([instance]); + + expect(asked).toHaveLength(requests); + expect(Array.from(volume.data)).toEqual(words); + } + ); + + it('fails every slice of an instance it cannot decode, without reading pixels', async () => { + const { bytes } = multiframe({ + transferSyntaxUid: '1.2.840.10008.1.2.4.102', + }); + const { source, ranges } = recorded(blobOf(bytes)); + const instance = await readInstance(source, signal()); + + const { updates } = await load([instance]); + + expect(updates).toEqual([ + { + slot: 0, + extent: [0, 2, 0, 1, 0, FRAMES - 1], + error: expect.objectContaining({ + message: expect.stringMatching(/MPEG-4 .* has no decoder/), + }), + }, + ]); + expect(ranges).toEqual([undefined]); + }); + + it('hands a declined instance to the whole-instance decoder', async () => { + const { bytes } = multiframe({ photometric: 'MONOCHROME1' }); + const instance = await readInstance(blobOf(bytes), signal()); + + const { updates } = await load([instance]); + + expect(updates).toEqual([ + { + slot: 0, + extent: [0, 2, 0, 1, 0, FRAMES - 1], + error: new Error('Provide DICOM decoder assets or a decoder'), + }, + ]); + }); + + it('stops frame reads and yields nothing once aborted', async () => { + const { bytes } = multiframe(); + const hanging = hangingSource(); + const blob = blobOf(bytes); + const source: ByteSource = { + read: (readSignal, range) => + range ? hanging.source.read(readSignal, range) : blob.read(readSignal), + }; + const instance = await readInstance(source, signal()); + const controller = new AbortController(); + + const loading = load([instance], { abort: controller.signal }); + await hanging.pulled; + const reason = new DOMException('closed', 'AbortError'); + controller.abort(reason); + + expect((await loading).updates).toEqual([]); + expect(await hanging.cancelled).toBe(reason); + }); +}); diff --git a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts new file mode 100644 index 000000000..134685fa4 --- /dev/null +++ b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -0,0 +1,265 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { + createDicomRuntime, + type DicomRuntime, + type PixelDecoder, +} from '../../runtime/createDicomRuntime'; +import { defer } from '../../utils'; +import { hangingSource } from '../../source/__tests__/sourceFixtures'; +import { loadedRange, type Volume } from '../allocateVolume'; +import type { ByteSource } from '../../source/byteSource'; +import { + loadVolume, + type LoadVolumeOptions, + type VolumeUpdate, +} from '../loadVolume'; +import { + allocated, + pixelSlice, + sliceValues, + valueDecoder, +} from './volumeFixture'; + +const runtimes: DicomRuntime[] = []; +afterEach(() => runtimes.splice(0).forEach((runtime) => runtime.dispose())); + +const runtimeWith = (decoder: PixelDecoder, decodeConcurrency = 1) => { + const runtime = createDicomRuntime({ decoder, decodeConcurrency }); + runtimes.push(runtime); + return runtime; +}; + +const collect = async (updates: AsyncIterable) => { + const all: VolumeUpdate[] = []; + for await (const update of updates) all.push(update); + return all; +}; + +const loadAll = ( + volume: Volume, + runtime: DicomRuntime, + options: Pick = {} +) => + collect( + loadVolume(volume, { + runtime, + signal: new AbortController().signal, + ...options, + }) + ); + +/** Slices whose sources report each read as it starts, in order. */ +const recordedStack = (count: number) => { + const reads: number[] = []; + const started: Array<() => void> = []; + const readStarted = (wanted: number) => + new Promise((resolve) => { + if (reads.length >= wanted) resolve(); + else started.push(() => reads.length >= wanted && resolve()); + }); + const members = Array.from({ length: count }, (_, z) => { + const instance = pixelSlice(z); + const source: ByteSource = { + read: (signal, range) => { + reads.push(z); + started.forEach((check) => check()); + return instance.source.read(signal, range); + }, + }; + return { ...instance, source }; + }); + return { volume: allocated(members), reads, readStarted }; +}; + +const stack = (count: number) => recordedStack(count).volume; + +describe('loadVolume', () => { + it('fills every slice, the middle first and then coarse to fine', async () => { + const decoded: number[] = []; + const { volume, reads } = recordedStack(5); + + const updates = await loadAll(volume, runtimeWith(valueDecoder(decoded)), { + readAhead: 1, + }); + + expect(reads).toEqual([2, 0, 4, 1, 3]); + expect(decoded).toEqual([2, 0, 4, 1, 3]); + expect(updates.map((update) => update.slot)).toEqual(decoded); + expect(updates[0]).toEqual({ + slot: 2, + extent: [0, 3, 0, 3, 2, 2], + range: [[2, 2]], + }); + expect(sliceValues(volume)).toEqual([0, 1, 2, 3, 4]); + expect(loadedRange(volume)).toEqual([[0, 4]]); + }); + + it('reports a failed slice and keeps loading the rest', async () => { + const decode = valueDecoder(); + const decoder: PixelDecoder = async (request, signal) => { + const image = await decode(request, signal); + if (image.data[0] === 1) throw new Error('corrupt pixel data'); + if (image.data[0] === 3) return { ...image, size: [2, 8, 1] }; + return image; + }; + const volume = stack(5); + + const updates = await loadAll(volume, runtimeWith(decoder)); + + const errors = updates.flatMap((update) => + 'error' in update ? [[update.slot, update.error.message]] : [] + ); + expect(errors).toEqual([ + [1, 'corrupt pixel data'], + [3, expect.stringMatching(/does not fit the volume/)], + ]); + expect(sliceValues(volume)).toEqual([0, null, 2, null, 4]); + }); + + it('reorders reads around a focus that moves while a slice decodes', async () => { + const decoded: number[] = []; + const decode = valueDecoder(decoded); + const resume = defer(); + const decoder: PixelDecoder = async (request, signal) => { + const image = await decode(request, signal); + if (decoded.length === 1) await resume.promise; + return image; + }; + let focus = 4; + const { volume, reads, readStarted } = recordedStack(9); + + const loading = loadAll(volume, runtimeWith(decoder), { + focus: () => focus, + readAhead: 1, + }); + // Slice 4 is decoding and the one read allowed ahead has begun. + await readStarted(2); + focus = 7; + resume.resolve(); + await loading; + + expect(reads).toEqual([4, 0, 7, 3, 5, 1, 6, 8, 2]); + expect(decoded).toEqual(reads); + }); + + it('reads ahead of a busy decoder, holding at most readAhead undecoded', async () => { + const readAhead = 3; + const decodesStarted: number[] = []; + const decode = valueDecoder(); + const { volume, reads, readStarted } = recordedStack(8); + let mostOutstanding = 0; + const ahead = readStarted(1 + readAhead); + const decoder: PixelDecoder = async (request, signal) => { + decodesStarted.push(0); + mostOutstanding = Math.max( + mostOutstanding, + reads.length - decodesStarted.length + ); + // The first decode waits until the reads behind it have all started. + if (decodesStarted.length === 1) await ahead; + return decode(request, signal); + }; + + const updates = await loadAll(volume, runtimeWith(decoder), { readAhead }); + + expect(updates).toHaveLength(8); + expect(reads).toHaveLength(8); + expect(mostOutstanding).toBeLessThanOrEqual(readAhead); + }); + + it('reports a failed read and keeps loading the rest', async () => { + const failing: ByteSource = { + read: () => + new ReadableStream({ + pull: (controller) => controller.error(new Error('connection reset')), + }), + }; + const volume = allocated([ + pixelSlice(0), + { ...pixelSlice(1), source: failing }, + pixelSlice(2), + ]); + + const updates = await loadAll(volume, runtimeWith(valueDecoder())); + + expect( + updates.flatMap((update) => + 'error' in update ? [[update.slot, update.error.message]] : [] + ) + ).toEqual([[1, 'connection reset']]); + expect(sliceValues(volume)).toEqual([0, null, 2]); + }); + + it('stops reading and yields nothing more once aborted', async () => { + const decoded: number[] = []; + const [below, above] = [hangingSource(), hangingSource()]; + const volume = allocated([ + { ...pixelSlice(0), source: below.source }, + pixelSlice(1), + { ...pixelSlice(2), source: above.source }, + ]); + const controller = new AbortController(); + const updates = loadVolume(volume, { + runtime: runtimeWith(valueDecoder(decoded), 2), + signal: controller.signal, + })[Symbol.asyncIterator](); + + const first = await updates.next(); + await Promise.all([below.pulled, above.pulled]); + const reason = new DOMException('closed', 'AbortError'); + controller.abort(reason); + + expect(first.value).toMatchObject({ slot: 1 }); + expect(await updates.next()).toEqual({ done: true, value: undefined }); + expect(await below.cancelled).toBe(reason); + expect(await above.cancelled).toBe(reason); + expect(decoded).toEqual([1]); + expect(sliceValues(volume)).toEqual([null, 1, null]); + }); + + it('ends when the runtime is disposed during a decode', async () => { + const started = defer(); + const decoder: PixelDecoder = () => { + started.resolve(); + return new Promise(() => {}); + }; + const runtime = runtimeWith(decoder); + + const loading = loadAll(stack(2), runtime); + await started.promise; + runtime.dispose(); + + expect(await loading).toEqual([]); + }); + + it('carries decoded slices into a grown volume without decoding them again', async () => { + const decoded: number[] = []; + const runtime = runtimeWith(valueDecoder(decoded)); + const [first, middle, last] = [0, 1, 2].map((z) => pixelSlice(z)); + const sparse = allocated([first, last]); + await loadAll(sparse, runtime); + + const grown = allocated([first, middle, last], sparse); + expect(sliceValues(grown)).toEqual([0, null, 2]); + decoded.length = 0; + await loadAll(grown, runtime); + expect(decoded).toEqual([1]); + + decoded.length = 0; + expect(await loadAll(grown, runtime)).toEqual([]); + expect(decoded).toEqual([]); + }); + + it('copies nothing into a volume whose buffer type changed', async () => { + const runtime = runtimeWith(valueDecoder()); + const [first, last] = [0, 2].map((z) => pixelSlice(z)); + const unsigned = allocated([first, last]); + await loadAll(unsigned, runtime); + + const signed = pixelSlice(1, { tags: { '0028|0103': '1' } }); + const grown = allocated([first, signed, last], unsigned); + + expect(grown.data).toBeInstanceOf(Float32Array); + expect(sliceValues(grown)).toEqual([null, null, null]); + }); +}); diff --git a/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts b/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts new file mode 100644 index 000000000..cd64f65f1 --- /dev/null +++ b/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import { assertSamplesRepresentable } from '../pixelValidation'; + +const intoFloat32 = + (min: number, max: number, rescaleSlope: number, rescaleIntercept = 0) => + () => + assertSamplesRepresentable( + new Float64Array([min, max]), + { min, max }, + new Float32Array(1), + { where: 'File 1.2.3', rescales: [{ rescaleSlope, rescaleIntercept }] } + ); + +describe('assertSamplesRepresentable into a Float32 volume', () => { + it('accepts integers float32 holds exactly', () => { + expect(intoFloat32(-(2 ** 24), 2 ** 24, 1, -1024)).not.toThrow(); + }); + + it('rejects integers float32 would round', () => { + expect(intoFloat32(0, 2 ** 24 + 1, 1)).toThrow(/Float32Array/); + }); + + it('accepts fractional values whose stored steps float32 keeps apart', () => { + expect(intoFloat32(-0.25, 4095 * 0.5 - 0.25, 0.5, -0.25)).not.toThrow(); + }); + + it('rejects fractional values float32 would merge with their neighbours', () => { + expect(intoFloat32(0, 2 ** 23, 0.5, 0.25)).toThrow(/rescale slope of 0.5/); + }); + + it('judges every frame calibration of an instance', () => { + expect(() => + assertSamplesRepresentable( + new Float64Array([0, 2 ** 22]), + { min: 0, max: 2 ** 22 }, + new Float32Array(1), + { + where: 'File 1.2.3', + rescales: [ + { rescaleSlope: 1, rescaleIntercept: 0 }, + { rescaleSlope: 0.25, rescaleIntercept: 0.5 }, + ], + } + ) + ).toThrow(/rescale slope of 0.25/); + }); +}); diff --git a/packages/dicom/core/volume/__tests__/slotOrder.spec.ts b/packages/dicom/core/volume/__tests__/slotOrder.spec.ts new file mode 100644 index 000000000..6c0006fe8 --- /dev/null +++ b/packages/dicom/core/volume/__tests__/slotOrder.spec.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; +import { pickNextSlot } from '../slotOrder'; + +const range = (count: number) => Array.from({ length: count }, (_, i) => i); + +/** Picks until nothing is pending, as a loader with one decode slot would. */ +const drain = (pending: number[], focus: number) => { + const left = new Set(pending); + const order: number[] = []; + for (;;) { + const next = pickNextSlot(left, focus); + if (next === undefined) return order; + order.push(next); + left.delete(next); + } +}; + +describe('pickNextSlot', () => { + it('takes the focus, then halving strides outward from it', () => { + expect(drain(range(17), 8)).toEqual([ + 8, 0, 16, 4, 12, 6, 10, 2, 14, 7, 9, 5, 11, 3, 13, 1, 15, + ]); + }); + + it('samples coarsely around a focus near one end', () => { + expect(drain(range(10), 1)).toEqual([1, 9, 5, 3, 7, 0, 2, 4, 6, 8]); + }); + + it('keeps the stride pattern around a focus that is already loaded', () => { + expect(drain([0, 2, 4, 6, 7, 9], 3)).toEqual([7, 9, 2, 4, 0, 6]); + }); + + it('does not depend on the order of the pending slots', () => { + const pending = range(33); + const reversed = [...pending].reverse(); + expect(drain(reversed, 20)).toEqual(drain(pending, 20)); + }); + + it('is total: nothing pending, fractional and non-finite focus', () => { + expect(pickNextSlot([], 3)).toBeUndefined(); + expect(pickNextSlot([0, 5, 9], 4.6)).toBe(5); + expect(pickNextSlot([3, 2], Number.NaN)).toBe(2); + }); +}); diff --git a/packages/dicom/core/volume/__tests__/volumeFixture.ts b/packages/dicom/core/volume/__tests__/volumeFixture.ts new file mode 100644 index 000000000..22242a29e --- /dev/null +++ b/packages/dicom/core/volume/__tests__/volumeFixture.ts @@ -0,0 +1,69 @@ +import { + emptyRegistry, + registerInstances, +} from '../../collections/instanceRegistry'; +import { + sliceDataset, + type SliceOptions, +} from '../../collections/__tests__/sliceFixture'; +import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import type { Instance } from '../../instance/readInstance'; +import type { PixelDecoder } from '../../runtime/createDicomRuntime'; +import { fromBlob } from '../../source/byteSource'; +import { + allocateVolume, + type AllocateVolumeOptions, + type Volume, +} from '../allocateVolume'; + +export const PIXELS_PER_SLICE = 16; + +const PIXEL_TAGS = { + '0028|0101': '16', + '0028|0103': '0', + '0028|0030': '0.5\\0.5', +}; + +/** A 4x4 slice at z = value whose source bytes spell its pixel value. */ +export const pixelSlice = (value: number, options: SliceOptions = {}) => + instanceFor( + sliceDataset({ + sop: `pixel-${value}`, + z: value, + ...options, + tags: { ...PIXEL_TAGS, ...options.tags }, + }), + fromBlob(new Blob([String(value)])) + ); + +export const plannedUpdate = (members: Instance[]) => + registerInstances(emptyRegistry, members).updates[0]; + +export function allocated( + members: Instance[], + previous?: Volume, + options: AllocateVolumeOptions = {} +) { + const result = allocateVolume(plannedUpdate(members), options, previous); + if (result.kind !== 'volume') throw new Error(`Allocated ${result.kind}`); + return result.volume; +} + +/** Decodes a source written by `pixelSlice`, recording each value it decodes. */ +export const valueDecoder = + (decoded: number[] = []): PixelDecoder => + async ({ bytes }) => { + const value = Number(new TextDecoder().decode(bytes)); + decoded.push(value); + return { + size: [4, 4, 1], + data: new Uint16Array(PIXELS_PER_SLICE).fill(value), + imageType: { components: 1 }, + }; + }; + +/** The first sample of every slice, or null where none is loaded yet. */ +export const sliceValues = (volume: Volume) => + Array.from(volume.loaded, (isLoaded, slice) => + isLoaded ? volume.data[slice * PIXELS_PER_SLICE] : null + ); diff --git a/src/utils/__tests__/allocateImageFromChunks.spec.ts b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts similarity index 58% rename from src/utils/__tests__/allocateImageFromChunks.spec.ts rename to packages/dicom/core/volume/__tests__/volumeLayout.spec.ts index 3ecb3b4e0..03fb0b984 100644 --- a/src/utils/__tests__/allocateImageFromChunks.spec.ts +++ b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts @@ -1,7 +1,12 @@ -import type { Chunk } from '@/src/core/streaming/chunk'; -import { Tags } from '@/src/core/dicomTags'; +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, it, expect } from 'vitest'; +import { + readGeometryFacts, + sliceNormalOf, +} from '../../collections/instanceFacts'; +import { reconstructVolume } from '../../collections/reconstructVolume'; +import { Tags } from '../../metadata/dicomTags'; import { - allocateImageFromChunks, getPixelFormat, getRescaledValueRange, getBufferValueRange, @@ -10,10 +15,10 @@ import { getVolumeBufferType, samplesAreIntegral, valuesFitBuffer, -} from '@/src/utils/allocateImageFromChunks'; -import { describe, it, expect } from 'vitest'; +} from '../pixelFormat'; +import { volumeLayout, type VolumeSource } from '../volumeLayout'; -function chunk(overrides: Record = {}) { +function volumeSource(overrides: Record = {}): VolumeSource { const metadata = { [Tags.SOPInstanceUID]: '1.2.3', [Tags.ImagePositionPatient]: '0\\0\\0', @@ -25,13 +30,11 @@ function chunk(overrides: Record = {}) { [Tags.SamplesPerPixel]: '1', ...overrides, }; - return { - metadata: Object.entries(metadata), - } as unknown as Chunk; + return { dataset: datasetFromTags(Object.entries(metadata)) }; } -function positionedChunk(z: number, overrides: Record = {}) { - return chunk({ +function positionedSource(z: number, overrides: Record = {}) { + return volumeSource({ [Tags.ImagePositionPatient]: `0\\0\\${z}`, ...overrides, }); @@ -51,7 +54,7 @@ describe('getTypedArrayForDataRange', () => { // Builds a format from exactly the tags given, with no defaults filled in, so // each test states the whole instance it is describing. function format(tags: Record) { - return getPixelFormat(Object.entries(tags)); + return getPixelFormat(datasetFromTags(Object.entries(tags))); } const UNSIGNED_16 = format({ @@ -162,18 +165,18 @@ describe('getVolumeBufferType', () => { getVolumeBufferType([ format({ [Tags.BitsStored]: '16', [Tags.RescaleIntercept]: '-1024' }), ]) - ).toBe(Int32Array); + ).toBe(Float32Array); }); it('throws when BitsStored is missing', () => { expect(() => getVolumeBufferType([format({})])).toThrow(); }); - it('matches the Float64 output observed in the public DSC perfusion series', () => { - expect(getVolumeBufferType([PUBLIC_DSC])).toBe(Float64Array); + it('keeps the public DSC perfusion series in float32, whose spacing stays below its slope', () => { + expect(getVolumeBufferType([PUBLIC_DSC])).toBe(Float32Array); }); - it('uses Float64 when fractional rescale has integral endpoints', () => { + it('uses Float32 when fractional rescale has integral endpoints', () => { expect( getVolumeBufferType([ format({ @@ -182,9 +185,79 @@ describe('getVolumeBufferType', () => { [Tags.RescaleIntercept]: '0', }), ]) - ).toBe(Float64Array); + ).toBe(Float32Array); + }); + + // 65535 * 256 + 256 is exactly 2^24, the last integer float32 counts to. + it.each([ + ['256', Float32Array], + ['257', Uint32Array], + ])( + 'keeps integers in float32 only up to 2^24 (intercept %s)', + (intercept, type) => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '16', + [Tags.RescaleSlope]: '256', + [Tags.RescaleIntercept]: intercept, + }), + ]) + ).toBe(type); + } + ); + + it('keeps signed integers beyond 2^24 in Int32', () => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '1', + [Tags.RescaleSlope]: '513', + }), + ]) + ).toBe(Int32Array); }); + // Values reach 2^23 + 1.5 + slope, so float32's spacing there is just above + // 1 + 1.788e-7: one slope keeps steps apart and the other merges them. + it.each([ + ['1.0000002', Float32Array], + ['1.0000001', Float64Array], + ])( + 'uses Float32 for fractional slope %s only while steps stay apart', + (slope, type) => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '1', + [Tags.RescaleSlope]: slope, + [Tags.RescaleIntercept]: '8388608.5', + }), + ]) + ).toBe(type); + } + ); + + it.each([ + ['24', Float32Array], + ['25', Float64Array], + ])( + 'stores at most 24 bits of fractional rescale in Float32 (Bits Stored %s)', + (bitsStored, type) => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: bitsStored, + [Tags.PixelRepresentation]: '1', + [Tags.RescaleSlope]: '0.5', + [Tags.RescaleIntercept]: '0.25', + }), + ]) + ).toBe(type); + } + ); + it('uses Float64 when an integral modality range exceeds 32 bits', () => { expect( getVolumeBufferType([ @@ -223,7 +296,7 @@ describe('getVolumeBufferType', () => { it('chooses one type that represents every instance in the volume', () => { expect(getVolumeBufferType([UNSIGNED_8, UNSIGNED_16])).toBe(Uint16Array); - expect(getVolumeBufferType([UNSIGNED_16, PUBLIC_DSC])).toBe(Float64Array); + expect(getVolumeBufferType([UNSIGNED_16, PUBLIC_DSC])).toBe(Float32Array); }); }); @@ -341,77 +414,201 @@ describe('samplesAreIntegral', () => { }); }); -describe('allocateImageFromChunks', () => { +describe('volumeLayout', () => { it.each([ ['0.0104\\0', [1, 0.0104, 1]], ['0.0104\\NaN', [1, 0.0104, 1]], ['0.0104', [0.0104, 0.0104, 1]], ['0.5', [0.5, 0.5, 1]], ['0', [1, 1, 1]], + ['-0.5', [1, 1, 1]], ['NaN', [1, 1, 1]], + ['Infinity', [1, 1, 1]], ['0\\0.046875', [0.046875, 1, 1]], ['NaN\\0.046875', [0.046875, 1, 1]], ['0\\0', [1, 1, 1]], ])( 'preserves valid axes independently for PixelSpacing %s', (value, expected) => { - const image = allocateImageFromChunks([ - chunk({ [Tags.PixelSpacing]: value as string }), - ]); + const image = layoutOf( + [volumeSource({ [Tags.PixelSpacing]: value as string })], + [1, 0, 0, 0, 1, 0] + ); expect(image.getSpacing()).toEqual(expected); - image.delete(); } ); - it('allocates for the modality range of every chunk', () => { - const image = allocateImageFromChunks([ - positionedChunk(0), - positionedChunk(1, { - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '0', - [Tags.RescaleSlope]: PUBLIC_DSC_SLOPE, - [Tags.RescaleIntercept]: '0', - }), - ]); - const data = image.getPointData().getScalars().getData(); - - expect(data).toBeInstanceOf(Float64Array); - expect(data).toHaveLength(3 * 4 * 2); + it('allocates for the modality range of every member', () => { + const image = layoutOf( + [ + positionedSource(0), + positionedSource(1, { + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', + [Tags.RescaleSlope]: PUBLIC_DSC_SLOPE, + [Tags.RescaleIntercept]: '0', + }), + ], + [1, 0, 0, 0, 1, 0] + ); + expect(image.bufferType).toBe(Float32Array); + expect(image.getDimensions()).toEqual([4, 3, 2]); }); it('matches ITK spacing order for single-slice images with SpacingBetweenSlices', () => { - const image = allocateImageFromChunks([ - chunk({ - [Tags.PixelSpacing]: '2.5\\0.75', - [Tags.SpacingBetweenSlices]: '7.25', - }), - ]); + const image = layoutOf( + [ + volumeSource({ + [Tags.PixelSpacing]: '2.5\\0.75', + [Tags.SpacingBetweenSlices]: '7.25', + }), + ], + [1, 0, 0, 0, 1, 0] + ); expect(Array.from(image.getSpacing())).toEqual([0.75, 2.5, 7.25]); }); it('uses declared inter-frame spacing for a multi-frame volume', () => { - const image = allocateImageFromChunks([ - chunk({ - [Tags.NumberOfFrames]: '32', - [Tags.PixelSpacing]: '0.0104\\0.046875', - [Tags.SpacingBetweenSlices]: '0.1875', - }), - ]); + const image = layoutOf( + [ + volumeSource({ + [Tags.NumberOfFrames]: '32', + [Tags.PixelSpacing]: '0.0104\\0.046875', + [Tags.SpacingBetweenSlices]: '0.1875', + }), + ], + [1, 0, 0, 0, 1, 0] + ); expect(Array.from(image.getDimensions())).toEqual([4, 3, 32]); expect(Array.from(image.getSpacing())).toEqual([0.046875, 0.0104, 0.1875]); }); - it('keeps deriving multi-slice Z spacing from ImagePositionPatient distance', () => { - const image = allocateImageFromChunks([ - positionedChunk(0, { - [Tags.PixelSpacing]: '2.5\\0.75', - [Tags.SpacingBetweenSlices]: '19', - }), - positionedChunk(9), - positionedChunk(18), - ]); + it('takes the multi-slice Z spacing from an even stack of positions', () => { + const image = layoutOf( + [ + positionedSource(0, { + [Tags.PixelSpacing]: '2.5\\0.75', + [Tags.SpacingBetweenSlices]: '19', + }), + positionedSource(9), + positionedSource(18), + ], + [1, 0, 0, 0, 1, 0] + ); expect(Array.from(image.getSpacing())).toEqual([0.75, 2.5, 9]); }); + + // Two 4mm runs with a hole between them, as the bilateral sagittal slabs of + // idcSeriesFixtures.ts are. Endpoint distance over slice count would call + // that a 17.33mm lattice, which describes neither run. + it('does not fit an irregular stack to a lattice its slices never sit on', () => { + const image = layoutOf( + [0, 4, 8, 48, 52].map((z) => positionedSource(z)), + [1, 0, 0, 0, 1, 0] + ); + + expect(image.getSpacing()[2]).toBeCloseTo(4, 12); + }); + + it('orients the image along the validated slice normal', () => { + const image = layoutOf( + [volumeSource({ [Tags.ImageOrientationPatient]: '0\\1\\0\\0\\0\\-1' })], + [0, 1, 0, 0, 0, -1] + ); + + expect(Array.from(image.getDirection())).toEqual([ + 0, 1, 0, 0, 0, -1, -1, 0, 0, + ]); + }); + + it('keeps the identity direction for an orientation that spans no plane', () => { + const image = layoutOf( + [volumeSource({ [Tags.ImageOrientationPatient]: '1\\0\\0\\1\\0\\0' })], + null + ); + + expect(Array.from(image.getDirection())).toEqual([ + 1, 0, 0, 0, 1, 0, 0, 0, 1, + ]); + }); + + it('leaves the Z spacing alone when no position can be read', () => { + const image = layoutOf( + [ + volumeSource({ [Tags.ImagePositionPatient]: '' }), + volumeSource({ [Tags.ImagePositionPatient]: '' }), + ], + [1, 0, 0, 0, 1, 0] + ); + + expect(image.getSpacing()[2]).toBe(1); + }); + + it('takes the declared SpacingBetweenSlices when no position can be read', () => { + const image = layoutOf( + [ + volumeSource({ + [Tags.ImagePositionPatient]: '', + [Tags.SpacingBetweenSlices]: '2.5', + }), + volumeSource({ [Tags.ImagePositionPatient]: '' }), + ], + [1, 0, 0, 0, 1, 0] + ); + + expect(image.getSpacing()[2]).toBe(2.5); + }); + + it('takes the declared SpacingBetweenSlices for a multi-frame instance', () => { + const image = layoutOf( + [ + volumeSource({ + [Tags.NumberOfFrames]: '4', + [Tags.SpacingBetweenSlices]: '1.5', + }), + ], + [1, 0, 0, 0, 1, 0] + ); + + expect(Array.from(image.getDimensions())).toEqual([4, 3, 4]); + expect(image.getSpacing()[2]).toBe(1.5); + }); + + // A tilted gantry leans every slice plane sideways of the last, so no lattice + // holds them; the extent the table stepped over is kept all the same. + it('steps a tilted gantry stack by the distance its slices advance', () => { + const theta = Math.PI / 9; + const tilted = [1, 0, 0, 0, Math.cos(theta), Math.sin(theta)]; + + const image = layoutOf( + [0, 3, 6, 9].map((z) => + positionedSource(z, { + [Tags.ImageOrientationPatient]: tilted.join('\\'), + }) + ), + tilted + ); + + expect(image.getSpacing()[2]).toBeCloseTo(3, 12); + expect(image.getDirection()[5]).toBeCloseTo(Math.sin(theta), 12); + }); }); + +const IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +/** Plans the members' stack as the collection planner would, then lays it out. */ +function layoutOf(sources: VolumeSource[], orientation: number[] | null) { + const reconstruction = reconstructVolume( + sources.map((item) => readGeometryFacts(item.dataset)), + sliceNormalOf(orientation) + ); + const layout = volumeLayout(sources, orientation, reconstruction); + return { + bufferType: layout.bufferType, + getDimensions: () => [layout.columns, layout.rows, layout.slices], + getSpacing: () => layout.spatialMetadata.axes.map((axis) => axis.value), + getDirection: () => layout.direction ?? IDENTITY, + }; +} diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts new file mode 100644 index 000000000..49f17d1bf --- /dev/null +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -0,0 +1,179 @@ +import type { Instance } from '../instance/readInstance'; +import type { InstanceCollectionUpdate } from '../collections/instanceRegistry'; +import type { DicomCollection } from '../collections/planDicomCollections'; +import type { Reconstruction } from '../collections/reconstructVolume'; +import type { SpatialMetadata } from '../metadata/spatialMetadata'; +import type { VolumeBuffer } from './pixelFormat'; +import { + planVolumeAllocation, + type IrregularGeometryPolicy, +} from './volumeLayout'; + +type Vector3 = readonly [number, number, number]; + +/** + * One buffer plus the geometry that places it. Everything is immutable except + * `data` and `loaded`, which only `loadVolume` writes. + */ +export type Volume = Readonly<{ + id: string; + collection: DicomCollection; + /** Planned order; `reconstruction.slots[i]` is member i's first slice. */ + members: readonly Instance[]; + reconstruction: Reconstruction; + /** Columns, rows, slices. */ + dimensions: Vector3; + components: number; + origin: Vector3; + /** Row-major 3x3: row direction, column direction, slice direction. */ + direction: readonly number[]; + spacing: Vector3; + spatialMetadata: SpatialMetadata; + /** Allocation warnings as [title, details]. */ + warnings: ReadonlyArray; + data: VolumeBuffer; + /** 1 where a slice holds decoded pixels, indexed by slice. */ + loaded: Uint8Array; +}>; + +/** SEG pixels are labels that a segmentation reader turns into its own image. */ +export type SegmentationAllocation = { + kind: 'segmentation'; + id: string; + members: readonly Instance[]; + reconstruction: Reconstruction; +}; + +export type VolumeAllocation = + | { kind: 'volume'; volume: Volume } + | SegmentationAllocation; + +export type AllocateVolumeOptions = { + irregularGeometry?: IrregularGeometryPolicy; +}; + +const IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +/** The slices one member fills: one per file, or every frame of a lone instance. */ +export const memberSlices = (volume: Volume, member: number) => + volume.members.length > 1 + ? [volume.reconstruction.slots[member]] + : Array.from({ length: volume.dimensions[2] }, (_, slice) => slice); + +export const memberLoaded = (volume: Volume, member: number) => + memberSlices(volume, member).every((slice) => volume.loaded[slice] === 1); + +export const sliceLength = (volume: Volume) => + volume.dimensions[0] * volume.dimensions[1] * volume.components; + +const samePixelShape = (volume: Volume, previous: Volume) => + volume.data.constructor === previous.data.constructor && + volume.dimensions[0] === previous.dimensions[0] && + volume.dimensions[1] === previous.dimensions[1] && + volume.components === previous.components; + +function copyMember( + volume: Volume, + member: number, + previous: Volume, + from: number +) { + const source = memberSlices(previous, from); + const target = memberSlices(volume, member); + if (source.length !== target.length || !memberLoaded(previous, from)) return; + const length = sliceLength(volume); + source.forEach((slice, index) => { + const start = slice * length; + volume.data.set( + previous.data.subarray(start, start + length), + target[index] * length + ); + volume.loaded[target[index]] = 1; + }); +} + +// Decoded slices follow their instance, whose slot may have moved. +function copyDecoded(volume: Volume, previous: Volume) { + if (!samePixelShape(volume, previous)) return; + const previousIndex = new Map( + previous.members.map((member, index) => [member, index]) + ); + volume.members.forEach((member, index) => { + const from = previousIndex.get(member); + if (from !== undefined) copyMember(volume, index, previous, from); + }); +} + +/** + * Allocates the volume a planned collection fills. With `previous`, slices + * already decoded there are copied across, so growth never decodes again. + */ +export function allocateVolume( + update: Pick, + options: AllocateVolumeOptions = {}, + previous?: Volume +): VolumeAllocation { + const { id, collection, members } = update; + const planned = planVolumeAllocation( + members, + collection.orientation, + collection.reconstruction, + options.irregularGeometry ?? 'preserve-order' + ); + const { reconstruction } = planned; + if (planned.kind === 'segmentation') + return { kind: 'segmentation', id, members, reconstruction }; + const { layout } = planned; + const { columns, rows, slices, samplesPerPixel } = layout; + const volume: Volume = Object.freeze({ + id, + collection, + members: Object.freeze([...members]), + reconstruction, + dimensions: [columns, rows, slices] as const, + components: samplesPerPixel, + origin: (layout.origin ?? [0, 0, 0]) as unknown as Vector3, + direction: layout.direction ?? IDENTITY, + spacing: layout.spatialMetadata.axes.map( + (axis) => axis.value + ) as unknown as Vector3, + spatialMetadata: layout.spatialMetadata, + warnings: planned.warnings, + data: new layout.bufferType(columns * rows * slices * samplesPerPixel), + loaded: new Uint8Array(slices), + }); + if (previous) copyDecoded(volume, previous); + return { kind: 'volume', volume }; +} + +/** Per-component [min, max] over the loaded slices; empty when none are. */ +export function loadedRange(volume: Volume) { + const length = sliceLength(volume); + const ranges: Array<[number, number]> = []; + volume.loaded.forEach((isLoaded, slice) => { + if (!isLoaded) return; + const samples = volume.data.subarray(slice * length, (slice + 1) * length); + componentRanges(samples, volume.components).forEach(([min, max], index) => { + const current = ranges[index] ?? [min, max]; + ranges[index] = [Math.min(current[0], min), Math.max(current[1], max)]; + }); + }); + return ranges; +} + +/** Per-component [min, max] of interleaved samples, ignoring NaN. */ +export function componentRanges( + samples: ArrayLike, + components: number +) { + return Array.from({ length: components }, (_, component) => { + let min = Infinity; + let max = -Infinity; + for (let index = component; index < samples.length; index += components) { + const value = samples[index]; + if (value < min) min = value; + if (value > max) max = value; + } + return [min, max] as [number, number]; + }); +} diff --git a/packages/dicom/core/volume/loadVolume.ts b/packages/dicom/core/volume/loadVolume.ts new file mode 100644 index 000000000..d5b7a7a73 --- /dev/null +++ b/packages/dicom/core/volume/loadVolume.ts @@ -0,0 +1,454 @@ +import type { DecodedDicomImage } from '../runtime/decoder'; +import type { DicomRuntime } from '../runtime/createDicomRuntime'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; +import { abortError, linkedController } from '../utils/abort'; +import { + readBytes, + type ByteRange, + type ByteSource, +} from '../source/byteSource'; +import { + planDecode, + type DecodePlan, + type DecoderTable, +} from '../pixels/decoderTable'; +import { + instancePixelFormats, + type VolumeBufferConstructor, +} from './pixelFormat'; +import { + componentRanges, + memberLoaded, + memberSlices, + sliceLength, + type Volume, +} from './allocateVolume'; +import { + assertChunkFitsSlot, + assertSamplesRepresentable, + assertSingleFramePerFile, + type DecodedChunkImage, +} from './pixelValidation'; +import { pickNextSlot } from './slotOrder'; + +/** [xMin, xMax, yMin, yMax, zMin, zMax], inclusive, as vtk.js extents are. */ +export type Extent = [number, number, number, number, number, number]; + +/** + * A decoded unit, or a failed one. A failure's extent spans the slices it + * leaves unloaded; slices inside it that loaded earlier stay loaded. + */ +export type VolumeUpdate = + | { slot: number; extent: Extent; range: Array<[number, number]> } + | { slot: number; extent: Extent; error: Error }; + +export type LoadVolumeOptions = { + runtime: Pick< + DicomRuntime, + 'decode' | 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' + >; + signal: AbortSignal; + /** Read before every read and decode; defaults to the middle member's slot. */ + focus?: () => number; + /** + * Units being read or read but not yet decoding, which bounds both + * concurrent reads and undecoded bytes held. Defaults to the runtime's + * read concurrency. + */ + readAhead?: number; +}; + +const ensureError = (error: unknown) => + error instanceof Error ? error : new Error(String(error)); + +const sliceExtent = (volume: Volume, slices: readonly number[]): Extent => [ + 0, + volume.dimensions[0] - 1, + 0, + volume.dimensions[1] - 1, + Math.min(...slices), + Math.max(...slices), +]; + +const memberName = (volume: Volume, member: number) => { + const sop = getDatasetTag( + volume.members[member].dataset, + Tags.SOPInstanceUID + ); + return `File ${sop ?? 'without SOP Instance UID'} (member ${member})`; +}; + +function assertMemberFits( + volume: Volume, + member: number, + image: DecodedChunkImage +) { + const { dimensions, components, members } = volume; + const where = memberName(volume, member); + assertSingleFramePerFile(image.size[2], members.length, where); + assertChunkFitsSlot( + image, + { + dims: [...dimensions], + componentCount: components, + count: members.length, + }, + where + ); +} + +type Rescale = { rescaleSlope: number; rescaleIntercept: number }; + +function assertRepresentable( + volume: Volume, + { + samples, + range, + }: { samples: ArrayLike; range: Array<[number, number]> }, + where: string, + rescales: readonly Rescale[] +) { + assertSamplesRepresentable( + samples, + { + min: Math.min(...range.map(([min]) => min)), + max: Math.max(...range.map(([, max]) => max)), + }, + volume.data, + { where, rescales } + ); +} + +/** A Float32 volume holds rounded values, so the range it reports is rounded too. */ +const storedRange = (volume: Volume, range: Array<[number, number]>) => + volume.data instanceof Float32Array + ? range.map(([min, max]): [number, number] => [ + Math.fround(min), + Math.fround(max), + ]) + : range; + +function writeMember(volume: Volume, member: number, image: DecodedDicomImage) { + assertMemberFits(volume, member, image); + const range = componentRanges(image.data, volume.components); + assertRepresentable( + volume, + { samples: image.data, range }, + memberName(volume, member), + instancePixelFormats(volume.members[member].dataset) + ); + const slices = memberSlices(volume, member); + volume.data.set(image.data, sliceLength(volume) * slices[0]); + slices.forEach((slice) => { + volume.loaded[slice] = 1; + }); + return { + slot: slices[0], + extent: sliceExtent(volume, slices), + range: storedRange(volume, range), + }; +} + +type FramePlan = Extract; + +function writeFrame( + volume: Volume, + unit: FrameUnit, + plan: FramePlan, + bytes: Uint8Array +) { + const { samples, range } = plan.decode( + bytes, + plan.format, + volume.data.constructor as VolumeBufferConstructor + ); + const where = `${memberName(volume, unit.member)}, frame ${unit.frame}`; + assertRepresentable(volume, { samples, range }, where, [plan.format]); + volume.data.set(samples, sliceLength(volume) * unit.slot); + volume.loaded[unit.slot] = 1; + return { + slot: unit.slot, + extent: sliceExtent(volume, [unit.slot]), + range: storedRange(volume, range), + }; +} + +type WholeUnit = Readonly<{ kind: 'instance'; slot: number; member: number }>; +type FrameUnit = Readonly<{ + kind: 'frame'; + slot: number; + member: number; + frame: number; + range: ByteRange; +}>; +type Unit = WholeUnit | FrameUnit; + +/** + * Units still to load and failures known from headers alone. An indexable + * instance contributes a unit per frame; any other one is a single unit. + */ +function planUnits( + volume: Volume, + decoders: DecoderTable +): { units: Unit[]; plans: DecodePlan[]; failures: VolumeUpdate[] } { + const units: Unit[] = []; + const failures: VolumeUpdate[] = []; + const plans = volume.members.map((instance, member) => { + const plan = planDecode(decoders, instance); + const slices = memberSlices(volume, member); + const fail = (error: Error) => + failures.push({ + slot: slices[0], + extent: sliceExtent(volume, slices), + error, + }); + if (memberLoaded(volume, member)) return plan; + if (plan.kind === 'unsupported') fail(plan.error); + else if (plan.kind === 'whole-instance') + units.push({ kind: 'instance', slot: slices[0], member }); + else { + try { + const { rows, columns, samplesPerPixel } = plan.format; + const frames = plan.index.frames.length; + assertMemberFits(volume, member, { + size: [columns, rows, frames], + data: { length: columns * rows * frames * samplesPerPixel }, + imageType: { components: samplesPerPixel }, + }); + plan.index.frames.forEach((range, frame) => { + const slot = slices[frame]; + if (!volume.loaded[slot]) + units.push({ kind: 'frame', slot, member, frame, range }); + }); + } catch (error) { + fail(ensureError(error)); + } + } + return plan; + }); + return { units, plans, failures }; +} + +/** The first slice of the middle member, the default focus. */ +export const middleSlot = (volume: Volume) => + memberSlices(volume, Math.floor(volume.members.length / 2))[0]; + +/** Wakes every waiter on any change; checks and waits happen in one turn. */ +function changes() { + const waiters: Array<() => void> = []; + return { + notify: () => waiters.splice(0).forEach((wake) => wake()), + next: () => + new Promise((resolve) => { + waiters.push(resolve); + }), + }; +} + +type Lanes = { + volume: Volume; + runtime: LoadVolumeOptions['runtime']; + stopped: AbortSignal; + focus: () => number; +}; + +const rangeSupport = (source: ByteSource) => + source.rangeSupport?.() ?? 'honoured'; + +function createLanes({ volume, runtime, stopped, focus }: Lanes) { + const { units, plans, failures } = planUnits(volume, runtime.decoders); + const unitAt = new Map(units.map((unit) => [unit.slot, unit])); + const framesOf = (member: number) => + units.filter((unit) => unit.kind === 'frame' && unit.member === member); + const claimed = new Set(); + /** Multiframe members whose source has not yet shown it honours ranges. */ + const probing = new Set(); + const fetched = new Map(); + const updates: VolumeUpdate[] = [...failures]; + const changed = changes(); + let reading = 0; + let readers = 0; + stopped.addEventListener('abort', changed.notify, { once: true }); + + const loaded = (unit: Unit) => + unit.kind === 'frame' + ? volume.loaded[unit.slot] === 1 + : memberLoaded(volume, unit.member); + const failure = (slots: number[], error: unknown): VolumeUpdate => ({ + slot: Math.min(...slots), + extent: sliceExtent( + volume, + slots.flatMap((slot) => { + const unit = unitAt.get(slot)!; + return unit.kind === 'frame' + ? [slot] + : memberSlices(volume, unit.member); + }) + ), + error: ensureError(error), + }); + const unclaimed = () => + units + .filter( + (unit) => + !claimed.has(unit.slot) && !probing.has(unit.member) && !loaded(unit) + ) + .map((unit) => unit.slot); + + // A server that ignores Range would resend the file for every frame, so + // such a member's remaining frames come from one read of its pixel data. + const pending = (unit: FrameUnit) => + rangeSupport(volume.members[unit.member].source) === 'ignored' + ? framesOf(unit.member).filter( + (other) => + other === unit || (!claimed.has(other.slot) && !loaded(other)) + ) + : [unit]; + + const readFrames = async (frames: Unit[]) => { + const ranges = frames.map((unit) => (unit as FrameUnit).range); + const start = Math.min(...ranges.map((range) => range.start)); + const end = Math.max(...ranges.map((range) => range.end!)); + const bytes = await readBytes( + volume.members[frames[0].member].source, + stopped, + { start, end } + ); + ranges.forEach((range, index) => + fetched.set( + frames[index].slot, + bytes.subarray(range.start - start, range.end! - start) + ) + ); + }; + + const read = async (unit: Unit) => { + const { source } = volume.members[unit.member]; + const frames = unit.kind === 'frame' ? pending(unit) : [unit]; + frames.forEach((each) => claimed.add(each.slot)); + const plan = plans[unit.member]; + const probe = + plan.kind === 'frames' && + plan.index.frames.length > 1 && + rangeSupport(source) === 'unknown'; + if (probe) probing.add(unit.member); + reading += 1; + try { + if (unit.kind === 'frame') await readFrames(frames); + else fetched.set(unit.slot, await readBytes(source, stopped)); + } catch (error) { + if (!stopped.aborted) + updates.push( + failure( + frames.map((each) => each.slot), + error + ) + ); + } finally { + if (probe) probing.delete(unit.member); + reading -= 1; + changed.notify(); + } + }; + const decode = async (slot: number, bytes: Uint8Array) => { + const unit = unitAt.get(slot)!; + if (unit.kind === 'frame') { + stopped.throwIfAborted(); + return writeFrame(volume, unit, plans[unit.member] as FramePlan, bytes); + } + const instance = volume.members[unit.member]; + const image = await runtime.decode({ instance, bytes }, stopped); + stopped.throwIfAborted(); + return writeMember(volume, unit.member, image); + }; + const settle = async (slot: number, bytes: Uint8Array) => { + try { + updates.push(await decode(slot, bytes)); + } catch (error) { + if (!stopped.aborted) updates.push(failure([slot], error)); + } + }; + + const reader = async (readAhead: number) => { + while (!stopped.aborted) { + if (reading + fetched.size >= readAhead) await changed.next(); + else { + const slot = pickNextSlot(unclaimed(), focus()); + if (slot !== undefined) await read(unitAt.get(slot)!); + else if (probing.size === 0) return; + else await changed.next(); + } + } + }; + + const decoder = async () => { + while (!stopped.aborted) { + const slot = pickNextSlot(fetched.keys(), focus()); + if (slot !== undefined) { + const bytes = fetched.get(slot)!; + fetched.delete(slot); + changed.notify(); + await settle(slot, bytes); + changed.notify(); + } else if (readers === 0) return; + else await changed.next(); + } + }; + + const start = (readAhead: number) => { + readers = readAhead; + Array.from({ length: readAhead }).forEach(() => + reader(readAhead).finally(() => { + readers -= 1; + changed.notify(); + }) + ); + return Promise.all( + Array.from({ length: runtime.decodeConcurrency }, decoder) + ); + }; + + return { start, updates, changed }; +} + +/** + * Decodes the slices not yet loaded, the focused slot first and then coarse + * to fine, writing each into the volume's buffer. An uncompressed instance + * loads frame by frame from ranged reads; any other one is read and decoded + * whole. Reads run ahead of decoding in the same order. A failed unit yields + * an error update and loading goes on. Aborting `signal`, disposing the runtime or leaving the loop stops reads + * and decodes; the iteration then returns rather than throwing, and yields + * nothing more. + */ +export async function* loadVolume( + volume: Volume, + { + runtime, + signal, + focus = () => middleSlot(volume), + readAhead = runtime.readConcurrency, + }: LoadVolumeOptions +): AsyncGenerator { + if (!Number.isInteger(readAhead) || readAhead < 1) + throw new Error('Read ahead must be a positive integer'); + const { controller, release } = linkedController(signal, runtime.signal); + const stopped = controller.signal; + const lanes = createLanes({ volume, runtime, stopped, focus }); + let finished = false; + lanes.start(readAhead).finally(() => { + finished = true; + lanes.changed.notify(); + }); + try { + for (;;) { + const next = stopped.aborted ? undefined : lanes.updates.shift(); + if (next) yield next; + else if (stopped.aborted || finished) return; + else await lanes.changed.next(); + } + } finally { + controller.abort(abortError('DICOM volume loading stopped')); + release(); + } +} diff --git a/packages/dicom/core/volume/nmGeometry.ts b/packages/dicom/core/volume/nmGeometry.ts new file mode 100644 index 000000000..a4bf6ee0f --- /dev/null +++ b/packages/dicom/core/volume/nmGeometry.ts @@ -0,0 +1,25 @@ +import { DicomDataset } from '../metadata/dicomDataset'; +import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; +import { type Reconstruction } from '../collections/reconstructVolume'; +import { readNmReconstruction } from '../metadata/nmReconstruction'; + +export function nmGeometry(metadata: DicomDataset) { + const nm = readNmReconstruction(metadata); + if (!nm) return null; + if ('error' in nm) throw new Error(nm.error); + const geometry = readGeometryFacts(metadata); + const normal = sliceNormalOf(geometry.orientation); + const step = nm.sliceSpacing || 1; + const direction = normal?.map((value) => value * Math.sign(step)) ?? null; + const reconstruction: Reconstruction = { + kind: 'regular', + sliceSpacing: nm.sliceSpacing ? Math.abs(nm.sliceSpacing) : null, + slots: [0], + }; + return { + ...geometry, + direction, + reconstruction, + sliceSpacingSource: 'SpacingBetweenSlices', + }; +} diff --git a/packages/dicom/core/volume/pixelFormat.ts b/packages/dicom/core/volume/pixelFormat.ts new file mode 100644 index 000000000..c37447cf2 --- /dev/null +++ b/packages/dicom/core/volume/pixelFormat.ts @@ -0,0 +1,251 @@ +import type { DicomDataset } from '../metadata/dicomDataset'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { getFrameTag } from '../metadata/functionalGroups'; +import { readModalityRescale } from '../metadata/modalityRescale'; +import { numberOr } from '../utils'; + +const BitsStoredTag = '00280101'; +const PixelRepresentationTag = '00280103'; +const NumberOfFramesTag = '00280008'; + +function getBitStorageSize(num: number, signed: boolean) { + const addSignedBit = signed ? 1 : 0; + const val = num < 0 ? -num : num + 1; // range shift for log2 + const nbits = Math.ceil(Math.log2(val) + addSignedBit); + // round up to a word size + return 2 ** Math.ceil(Math.log2(nbits)); +} + +type IntegerArrayConstructor = + | typeof Int8Array + | typeof Uint8Array + | typeof Int16Array + | typeof Uint16Array + | typeof Int32Array + | typeof Uint32Array; + +export type VolumeBufferConstructor = + | IntegerArrayConstructor + | typeof Float32Array + | typeof Float64Array; +export type VolumeBuffer = InstanceType; + +const TYPED_ARRAY_VALUE_RANGES = new Map< + IntegerArrayConstructor, + { min: number; max: number } +>([ + [Int8Array, { min: -(2 ** 7), max: 2 ** 7 - 1 }], + [Uint8Array, { min: 0, max: 2 ** 8 - 1 }], + [Int16Array, { min: -(2 ** 15), max: 2 ** 15 - 1 }], + [Uint16Array, { min: 0, max: 2 ** 16 - 1 }], + [Int32Array, { min: -(2 ** 31), max: 2 ** 31 - 1 }], + [Uint32Array, { min: 0, max: 2 ** 32 - 1 }], +]); + +/** + * The values a buffer of the given element type can hold without wrapping. + * Undefined for element types the allocator never produces, floats included. + */ +export function getTypedArrayValueRange(ctor: unknown) { + return TYPED_ARRAY_VALUE_RANGES.get(ctor as IntegerArrayConstructor); +} + +/** + * The values `buffer` can hold without wrapping, or undefined if its element + * type has no fixed integer range to enforce. + */ +export function getBufferValueRange(buffer: ArrayBufferView) { + return getTypedArrayValueRange(buffer.constructor); +} + +/** + * Whether a decoded value range is representable in `buffer`'s element type. + * A buffer with no enforceable range accepts everything. + */ +export function valuesFitBuffer( + range: { min: number; max: number }, + buffer: ArrayBufferView +) { + const bufferRange = getBufferValueRange(buffer); + if (!bufferRange) return true; + return range.min >= bufferRange.min && range.max <= bufferRange.max; +} + +/** + * Whether every sample is a whole number, which an integer-element buffer + * needs. Integer typed arrays hold nothing else, so only float or plain + * arrays are scanned. A buffer with no integer range accepts everything. + */ +export function samplesAreIntegral( + values: ArrayLike, + buffer: ArrayBufferView +) { + if (!getBufferValueRange(buffer)) return true; + if ( + ArrayBuffer.isView(values) && + !(values instanceof Float32Array) && + !(values instanceof Float64Array) + ) { + return true; + } + return Array.prototype.every.call(values, (value: number) => + Number.isInteger(value) + ); +} + +export function getTypedArrayForDataRange(min: number, max: number) { + if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max)) + throw new Error('Input must be integers'); + + const isSigned = min < 0; + const nbits = getBitStorageSize( + Math.abs(min) > Math.abs(max) ? min : max, + isSigned + ); + + if (nbits <= 8) return isSigned ? Int8Array : Uint8Array; + if (nbits <= 16) return isSigned ? Int16Array : Uint16Array; + if (nbits <= 32) return isSigned ? Int32Array : Uint32Array; + + throw new Error(`Cannot handle ${nbits}-bit sized ranges`); +} + +/** + * The tags that decide what values an instance decodes to. + * + * A bitsStored of 0 means the tag was absent or unparseable. It is not a DICOM + * default: BitsStored is Type 1, so a conforming instance always carries one. + */ +export function getPixelFormat( + metadata: DicomDataset | null | undefined, + frameIndex = 0 +) { + const valueOf = (tag: string) => getFrameTag(metadata, tag, frameIndex); + return { + bitsStored: numberOr(valueOf(BitsStoredTag), 0), + pixelRepresentation: numberOr(valueOf(PixelRepresentationTag), 0), + ...readModalityRescale(metadata, frameIndex), + }; +} + +type PixelFormat = ReturnType; + +/** + * The values an instance can decode to. ITK/GDCM applies RescaleSlope and + * RescaleIntercept while decoding, so this is the range after rescaling. + * + * Null when BitsStored is missing, since nothing can be derived without it. + */ +export function getRescaledValueRange(format: PixelFormat) { + const { bitsStored, pixelRepresentation, rescaleSlope, rescaleIntercept } = + format; + if (!Number.isInteger(bitsStored) || bitsStored <= 0) return null; + + const isSigned = pixelRepresentation === 1; + const storedMin = isSigned ? -(2 ** (bitsStored - 1)) : 0; + const storedMax = 2 ** (bitsStored - (isSigned ? 1 : 0)) - 1; + const a = storedMin * rescaleSlope + rescaleIntercept; + const b = storedMax * rescaleSlope + rescaleIntercept; + + return { min: Math.min(a, b), max: Math.max(a, b) }; +} + +const FLOAT32_EXACT_INTEGER = 2 ** 24; +const FLOAT32_RELATIVE_STEP = 2 ** -23; +const FLOAT32_MAX_BITS_STORED = 24; + +const magnitude = ({ min, max }: { min: number; max: number }) => + Math.max(Math.abs(min), Math.abs(max)); + +const isIntegralRescale = (format: { + rescaleSlope: number; + rescaleIntercept: number; +}) => + Number.isInteger(format.rescaleSlope) && + Number.isInteger(format.rescaleIntercept); + +/** Float32 holds every integer up to 2^24 exactly. */ +const float32KeepsIntegers = (range: { min: number; max: number }) => + magnitude(range) <= FLOAT32_EXACT_INTEGER; + +/** Float32's spacing near `range` stays below one stored step of `slope`. */ +const float32KeepsSteps = ( + range: { min: number; max: number }, + slope: number +) => slope !== 0 && magnitude(range) * FLOAT32_RELATIVE_STEP < Math.abs(slope); + +/** + * Whether a float32 buffer holds `range` as the rescale requires: integral + * values exactly, fractional ones with adjacent stored steps kept apart. + */ +export const float32Holds = ( + range: { min: number; max: number }, + format: { rescaleSlope: number; rescaleIntercept: number } +) => + isIntegralRescale(format) + ? float32KeepsIntegers(range) + : float32KeepsSteps(range, format.rescaleSlope); + +type UsableFormat = { + format: PixelFormat; + range: { min: number; max: number }; +}; + +function fractionalBufferType(usable: UsableFormat[]) { + return usable.every( + ({ format, range }) => + format.bitsStored <= FLOAT32_MAX_BITS_STORED && + float32KeepsSteps(range, format.rescaleSlope) + ) + ? Float32Array + : Float64Array; +} + +function integralBufferType(usable: UsableFormat[]): VolumeBufferConstructor { + if ( + usable.some( + ({ range }) => + !Number.isSafeInteger(range.min) || !Number.isSafeInteger(range.max) + ) + ) + return Float64Array; + const min = Math.min(...usable.map(({ range }) => range.min)); + const max = Math.max(...usable.map(({ range }) => range.max)); + const exceedsSigned32 = min < 0 && (min < -(2 ** 31) || max > 2 ** 31 - 1); + const exceedsUnsigned32 = min >= 0 && max > 2 ** 32 - 1; + if (exceedsSigned32 || exceedsUnsigned32) return Float64Array; + const type = getTypedArrayForDataRange(min, max); + const wide = type === Int32Array || type === Uint32Array; + return wide && float32KeepsIntegers({ min, max }) ? Float32Array : type; +} + +/** + * The element type a volume allocated from instances of these formats holds. + * + * An instance whose tags give no finite range is left out of the union and + * judged on its decoded values by the containment guard instead. + */ +export function getVolumeBufferType( + formats: PixelFormat[] +): VolumeBufferConstructor { + const usable = formats.flatMap((format) => { + const range = getRescaledValueRange(format); + return range && Number.isFinite(range.min) && Number.isFinite(range.max) + ? [{ format, range }] + : []; + }); + if (usable.length === 0) + throw new Error('No instance declares a finite modality rescale range'); + + // vtk.js uploads only 8/16-bit integer and float32 buffers without converting the whole volume. + return usable.some(({ format }) => !isIntegralRescale(format)) + ? fractionalBufferType(usable) + : integralBufferType(usable); +} + +/** One format per frame, since enhanced instances calibrate frames separately. */ +export const instancePixelFormats = (dataset: DicomDataset) => + Array.from( + { length: numberOr(getDatasetTag(dataset, NumberOfFramesTag), 1) }, + (_, index) => getPixelFormat(dataset, index) + ); diff --git a/packages/dicom/core/volume/pixelValidation.ts b/packages/dicom/core/volume/pixelValidation.ts new file mode 100644 index 000000000..ea972203c --- /dev/null +++ b/packages/dicom/core/volume/pixelValidation.ts @@ -0,0 +1,115 @@ +import { + float32Holds, + getBufferValueRange, + valuesFitBuffer, + samplesAreIntegral, +} from './pixelFormat'; + +/** What a whole-instance decode returns, before it is written into a volume. */ +export type DecodedChunkImage = { + size: number[]; + data: { length: number } | null | undefined; + imageType: { components: number }; +}; + +export function assertSamplesRepresentable( + decoded: ArrayLike, + range: { min: number; max: number }, + buffer: ArrayBufferView, + { + where, + rescales, + }: { + where: string; + /** Every frame calibration the samples went through. */ + rescales: ReadonlyArray<{ rescaleSlope: number; rescaleIntercept: number }>; + } +) { + const unheld = + buffer instanceof Float32Array + ? rescales.find((rescale) => !float32Holds(range, rescale)) + : undefined; + if (unheld) { + throw new Error( + `${where} has pixel values the volume it belongs to cannot represent. ` + + `Its pixel values run from ${range.min} to ${range.max} with a rescale slope of ${unheld.rescaleSlope}, ` + + `but the volume's buffer is Float32Array, which would merge or round values of that size. ` + + `Every file in a volume must decode to values its buffer can hold without conversion.` + ); + } + if (!valuesFitBuffer(range, buffer)) { + const bufferRange = getBufferValueRange(buffer)!; + throw new Error( + `${where} has pixel values the volume it belongs to cannot represent. ` + + `Its pixel values run from ${range.min} to ${range.max}, but the volume's buffer is ` + + `${buffer.constructor.name}, holding values from ${bufferRange.min} to ${bufferRange.max}. ` + + `Every file in a volume must decode to values its buffer can hold without conversion.` + ); + } + if (!samplesAreIntegral(decoded, buffer)) { + throw new Error( + `${where} has fractional pixel values the volume it belongs to cannot represent. ` + + `Its pixel values run from ${range.min} to ${range.max}, but the volume's buffer is ` + + `${buffer.constructor.name}, which holds only whole numbers. ` + + `Every file in a volume must decode to values its buffer can hold without conversion.` + ); + } +} + +export function assertSingleFramePerFile( + frames: number, + count: number, + where: string +) { + if (frames > 1 && count > 1) { + // we're trying to load multiple chunks where individual chunks have multiple frames + throw new Error( + `Loading a single volume from multiple DICOM files where individual files contain multiple frames is not supported. ` + + `${where} contains ${frames} frames.` + ); + } +} + +// Each chunk gets a fixed slot: one frame per chunk in a multi-file volume, +// or the whole volume when a single multi-frame chunk fills it. A decoded +// chunk has to fill its slot exactly. +export function assertChunkFitsSlot( + image: DecodedChunkImage, + volume: { dims: number[]; componentCount: number; count: number }, + where: string +) { + const { dims, componentCount, count } = volume; + const multiFile = count > 1; + const framesPerChunk = multiFile ? 1 : dims[2]; + const [chunkWidth, chunkHeight] = image.size; + const chunkFrames = image.size[2] ?? 1; + const chunkComponents = image.imageType.components; + assertSampleCount(image, where); + if ( + chunkWidth !== dims[0] || + chunkHeight !== dims[1] || + chunkFrames !== framesPerChunk || + chunkComponents !== componentCount + ) { + // A lone chunk defines the volume it fails to fit, so advice about + // agreeing with the other files only makes sense for a multi-file volume. + const advice = multiFile + ? ' Every file in a volume must have the same Rows, Columns, and SamplesPerPixel.' + : ''; + throw new Error( + `${where} does not fit the volume it belongs to. ` + + `It decoded to ${chunkWidth}x${chunkHeight}x${chunkFrames} with ${chunkComponents} component(s), ` + + `but the volume has room for ${dims[0]}x${dims[1]}x${framesPerChunk} with ${componentCount} component(s).` + + advice + ); + } +} + +function assertSampleCount(image: DecodedChunkImage, where: string) { + const [width, height, frames = 1] = image.size; + const expected = width * height * frames * image.imageType.components; + if (image.data?.length !== expected) + throw new Error( + `${where} decoded ${image.data?.length ?? 0} samples; expected ${expected}` + ); +} diff --git a/packages/dicom/core/volume/slotOrder.ts b/packages/dicom/core/volume/slotOrder.ts new file mode 100644 index 000000000..f22b04df8 --- /dev/null +++ b/packages/dicom/core/volume/slotOrder.ts @@ -0,0 +1,27 @@ +// The largest power of two dividing the offset; offset zero outranks all. +const coarseness = (offset: number) => + offset === 0 ? Infinity : offset & -offset; + +const precedes = (left: number, right: number, focus: number) => { + const leftOffset = Math.abs(left - focus); + const rightOffset = Math.abs(right - focus); + const byCoarseness = coarseness(rightOffset) - coarseness(leftOffset); + if (byCoarseness !== 0 && !Number.isNaN(byCoarseness)) + return byCoarseness < 0; + if (leftOffset !== rightOffset) return leftOffset < rightOffset; + return left < right; +}; + +/** + * The slot to load next: the focus first, then outward at halving strides, + * so a partly loaded volume samples its whole extent evenly. Ties go to the + * nearer slot, then the lower one. Undefined when nothing is pending. + */ +export function pickNextSlot(pending: Iterable, focus: number) { + const center = Number.isFinite(focus) ? Math.round(focus) : 0; + let best: number | undefined; + for (const slot of pending) { + if (best === undefined || precedes(slot, best, center)) best = slot; + } + return best; +} diff --git a/packages/dicom/core/volume/ultrasoundSpacing.ts b/packages/dicom/core/volume/ultrasoundSpacing.ts new file mode 100644 index 000000000..cea2f8e0e --- /dev/null +++ b/packages/dicom/core/volume/ultrasoundSpacing.ts @@ -0,0 +1,85 @@ +import { getDatasetModality } from '../metadata/datasetAccess'; +import { unitToMm } from '../streaming/dicom/ultrasoundRegion'; +import { + physicalSpacing, + type SpatialMetadata, +} from '../metadata/spatialMetadata'; +import type { VolumeSource } from './volumeLayout'; + +const isUsableSpacing = (value: number) => + Number.isFinite(value) && value !== 0; + +const regionNotes = (count: number) => + count > 1 + ? [ + 'Multiple ultrasound regions are present; only the first region supplies the display spacing.', + ] + : []; + +/** The display spacing is `axes[n].value` of the returned metadata. */ +export function applyUltrasoundSpacing( + spatialMetadata: SpatialMetadata, + sources: readonly VolumeSource[], + warn: (title: string, details: string) => void +): SpatialMetadata { + if (getDatasetModality(sources[0].dataset) !== 'US') return spatialMetadata; + + // Ultrasound DICOMs are typically a single multi-frame instance, so the + // first region table applies to the whole image. + const regions = sources[0]?.ultrasoundRegions; + if (!regions?.region) return spatialMetadata; + + warnMultipleRegions(regions.regionCount); + + const { region } = regions; + const notes = [...spatialMetadata.notes, ...regionNotes(regions.regionCount)]; + const xFactor = unitToMm(region.physicalUnitsXDirection); + const yFactor = unitToMm(region.physicalUnitsYDirection); + // All-or-nothing: if either axis lacks a spatial unit (e.g. one axis is + // cm and the other is seconds, or unitless) the metadata can't be trusted + // as a 2D physical spacing, so leave the default 1mm fallback in place. + if (xFactor === null || yFactor === null) { + console.warn( + `Ultrasound spacing not applied: PhysicalUnitsXDirection=${region.physicalUnitsXDirection}, PhysicalUnitsYDirection=${region.physicalUnitsYDirection}; only code 3 (cm) is converted to mm.` + ); + notes.push( + 'The first ultrasound region does not declare two spatial axes; its calibration is not applied.' + ); + return { ...spatialMetadata, notes }; + } + + const spacingX = region.physicalDeltaX * xFactor; + const spacingY = region.physicalDeltaY * yFactor; + if (!isUsableSpacing(spacingX) || !isUsableSpacing(spacingY)) { + warn( + 'Invalid ultrasound calibration', + `The ultrasound region declares PhysicalDeltaX=${region.physicalDeltaX} and PhysicalDeltaY=${region.physicalDeltaY}. Measurements use the image pixel spacing instead.` + ); + notes.push( + 'The first ultrasound region has unusable physical deltas; its calibration is not applied.' + ); + return { ...spatialMetadata, notes }; + } + + notes.push( + 'Ultrasound physical spacing applies within the calibrated region, not necessarily the entire image.' + ); + return { + ...spatialMetadata, + axes: [ + physicalSpacing(spacingX, 'Ultrasound region (cm converted to mm)'), + physicalSpacing(spacingY, 'Ultrasound region (cm converted to mm)'), + spatialMetadata.axes[2], + ], + notes, + }; +} + +function warnMultipleRegions(count: number) { + // vtkImageData has one global spacing even when the acquisition contains + // regions with different physical calibration. + if (count > 1) + console.warn( + `Ultrasound image has ${count} regions; only the first region's physical spacing is applied. Multi-region (e.g. dual-pane B-mode + Doppler) ultrasound is not fully supported.` + ); +} diff --git a/packages/dicom/core/volume/volumeLayout.ts b/packages/dicom/core/volume/volumeLayout.ts new file mode 100644 index 000000000..1d449444d --- /dev/null +++ b/packages/dicom/core/volume/volumeLayout.ts @@ -0,0 +1,269 @@ +import type { DicomDataset } from '../metadata/dicomDataset'; +import { getDatasetTag, getDatasetModality } from '../metadata/datasetAccess'; +import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; +import { + reconstructInstances, + type Reconstruction, +} from '../collections/reconstructVolume'; +import { multiframeGeometry } from '../collections/multiframeGeometry'; +import { readDatasetDetails } from '../collections/datasetDetails'; +import { + declaredSpacing, + physicalSpacing, + readPixelSpacing, + type SpatialMetadata, +} from '../metadata/spatialMetadata'; +import { getFrameTag } from '../metadata/functionalGroups'; +import type { UltrasoundRegions } from '../streaming/dicom/ultrasoundRegion'; +import { numberOr } from '../utils'; +import { nmGeometry } from './nmGeometry'; +import { getVolumeBufferType, instancePixelFormats } from './pixelFormat'; +import { applyUltrasoundSpacing } from './ultrasoundSpacing'; + +const SpacingBetweenSlicesTag = '00180088'; +const RowsTag = '00280010'; +const ColumnsTag = '00280011'; +const SamplesPerPixelTag = '00280002'; +const NumberOfFrames = '00280008'; + +/** What allocation reads from one member: its header and ultrasound regions. */ +export type VolumeSource = { + dataset: DicomDataset; + ultrasoundRegions?: UltrasoundRegions | null; +}; + +/** Preserve acquisition order and its fallback spacing, or require a regular lattice. */ +export type IrregularGeometryPolicy = 'preserve-order' | 'reject'; + +const isPositiveFiniteNumber = (value: number) => + Number.isFinite(value) && value > 0; + +const frameCountOf = (dataset: DicomDataset) => + numberOr(getDatasetTag(dataset, NumberOfFrames), 1); + +function assertRegularGeometry( + reconstruction: Reconstruction, + policy: IrregularGeometryPolicy +) { + if (reconstruction.kind === 'irregular' && policy === 'reject') + throw new Error( + `Cannot allocate irregular DICOM geometry: ${reconstruction.reason}` + ); +} + +const instanceGeometry = (dataset: DicomDataset, count: number) => { + const nm = nmGeometry(dataset); + if (nm) return nm; + if (count < 2) return null; + // SEG planning does not judge segment-major frames as one spatial stack. + if (getDatasetModality(dataset) === 'SEG') + return multiframeGeometry(dataset, count); + return readDatasetDetails(dataset).frameGeometry; +}; + +function allocationDirection( + orientation: number[] | null, + frameDirection?: number[] | null +) { + const normal = frameDirection ?? sliceNormalOf(orientation); + return orientation && normal ? [...orientation, ...normal] : null; +} + +function allocationGeometry( + sources: readonly VolumeSource[], + orientation: number[] | null, + reconstruction: Reconstruction, + policy: IrregularGeometryPolicy +) { + const { dataset } = sources[0]; + const frames = + sources.length === 1 + ? instanceGeometry(dataset, frameCountOf(dataset)) + : null; + const geometry = frames ?? readGeometryFacts(dataset); + const plan = frames?.reconstruction ?? reconstruction; + assertRegularGeometry(plan, policy); + const effectiveOrientation = orientation ?? geometry.orientation; + return { + ...geometry, + reconstruction: plan, + sliceSpacingSource: frames?.sliceSpacingSource ?? 'ImagePositionPatient', + direction: allocationDirection(effectiveOrientation, frames?.direction), + }; +} + +function assertSliceSlots(slots: number[], count: number) { + if ( + slots.length !== count || + new Set(slots).size !== count || + slots.some((slot) => !Number.isSafeInteger(slot) || slot < 0) || + (count > 0 && slots[0] !== 0) + ) + throw new Error( + 'Reconstruction must map each chunk to one distinct nonnegative slice slot, starting at zero' + ); +} + +function allocationShape( + sources: readonly VolumeSource[], + reconstruction: Reconstruction +) { + const valueOf = (tag: string) => getDatasetTag(sources[0].dataset, tag); + const numberOfFrames = numberOr(valueOf(NumberOfFrames), 1); + if (numberOfFrames > 1 && sources.length > 1) + throw new Error( + 'First chunk in a group of chunks (size > 1) is a multi-frame chunk' + ); + return { + rows: numberOr(valueOf(RowsTag), 0), + columns: numberOr(valueOf(ColumnsTag), 0), + samplesPerPixel: numberOr(valueOf(SamplesPerPixelTag), 1), + slices: + sources.length > 1 + ? Math.max(...reconstruction.slots) + 1 + : numberOfFrames, + }; +} + +function allocationNotes( + sources: readonly VolumeSource[], + geometry: ReturnType +) { + const notes = []; + if (!geometry.position) + notes.push( + 'Patient position is unavailable; the display uses a zero origin.' + ); + if (!geometry.direction) + notes.push( + 'Patient orientation is unavailable; the display uses default axes.' + ); + if ( + sources.length > 1 && + sources.some((source) => + readPixelSpacing(source.dataset).some( + (axis) => axis.status === 'fallback' + ) + ) + ) + notes.push( + 'Some slices lack usable PixelSpacing; the displayed in-plane grid uses the first slice.' + ); + return notes; +} + +function allocationCalibration(metadata: DicomDataset) { + const type = getDatasetTag(metadata, '00280A02')?.trim(); + const description = getDatasetTag(metadata, '00280A04')?.trim(); + return type || description ? { calibration: { type, description } } : {}; +} + +function allocationSpatialMetadata( + sources: readonly VolumeSource[], + geometry: ReturnType +): SpatialMetadata { + const metadata = sources[0].dataset; + const { reconstruction, sliceSpacingSource } = geometry; + const sliceSpacing = reconstruction.sliceSpacing ?? 0; + const z = isPositiveFiniteNumber(sliceSpacing) + ? physicalSpacing( + sliceSpacing, + sliceSpacingSource, + sliceSpacingSource === 'ImagePositionPatient' ? 'derived' : 'declared' + ) + : declaredSpacing( + getFrameTag(metadata, SpacingBetweenSlicesTag), + 'SpacingBetweenSlices' + ); + return { + axes: [...readPixelSpacing(metadata), z], + reconstruction: { + kind: reconstruction.kind, + ...(reconstruction.kind === 'irregular' + ? { reason: reconstruction.reason } + : {}), + }, + notes: allocationNotes(sources, geometry), + ...allocationCalibration(metadata), + }; +} + +/** + * Shape, placement and element type of the volume these ordered members fill. + * `origin` and `direction` are null where the headers cannot place the image. + */ +export function volumeLayout( + sources: readonly VolumeSource[], + orientation: number[] | null, + reconstruction: Reconstruction, + irregularGeometry: IrregularGeometryPolicy = 'preserve-order' +) { + if (sources.length === 0) + throw new Error('Cannot allocate an image from zero chunks'); + assertRegularGeometry(reconstruction, irregularGeometry); + assertSliceSlots(reconstruction.slots, sources.length); + const shape = allocationShape(sources, reconstruction); + const geometry = allocationGeometry( + sources, + orientation, + reconstruction, + irregularGeometry + ); + return { + ...shape, + origin: geometry.position, + direction: geometry.direction, + spatialMetadata: allocationSpatialMetadata(sources, geometry), + bufferType: getVolumeBufferType( + sources.flatMap((source) => instancePixelFormats(source.dataset)) + ), + }; +} + +export type VolumeLayout = ReturnType; + +const reconstructionFor = ( + sources: readonly VolumeSource[], + orientation: number[] | null, + supplied: Reconstruction | undefined +) => { + const needsFrameGeometry = + sources.length === 1 && frameCountOf(sources[0].dataset) > 1; + return supplied && !needsFrameGeometry + ? supplied + : reconstructInstances( + sources.map((source) => readDatasetDetails(source.dataset).facts), + sliceNormalOf(orientation), + supplied + ); +}; + +/** + * Plans an allocation for planned members. SEG yields no layout, since its + * pixels are labels that a segmentation reader turns into its own image. + */ +export function planVolumeAllocation( + sources: readonly VolumeSource[], + orientation: number[] | null, + supplied: Reconstruction | undefined, + policy: IrregularGeometryPolicy +) { + if (sources.length === 0) + throw new Error('Cannot allocate an image from zero chunks'); + const reconstruction = reconstructionFor(sources, orientation, supplied); + const warnings: Array<[string, string]> = []; + if (getDatasetModality(sources[0].dataset) === 'SEG') + return { kind: 'segmentation' as const, reconstruction, warnings }; + const layout = volumeLayout(sources, orientation, reconstruction, policy); + const spatialMetadata = applyUltrasoundSpacing( + layout.spatialMetadata, + sources, + (...warning) => warnings.push(warning) + ); + return { + kind: 'volume' as const, + reconstruction, + layout: { ...layout, spatialMetadata }, + warnings, + }; +} diff --git a/packages/dicom/package.json b/packages/dicom/package.json new file mode 100644 index 000000000..601a90293 --- /dev/null +++ b/packages/dicom/package.json @@ -0,0 +1,38 @@ +{ + "name": "@volview/dicom", + "version": "0.0.0", + "private": true, + "type": "module", + "files": [ + "dist", + "core", + "vtk" + ], + "exports": { + "./core/*": { + "types": "./dist/core/*.d.ts", + "import": "./dist/core/*.js" + }, + "./vtk/*": { + "types": "./dist/vtk/*.d.ts", + "import": "./dist/vtk/*.js" + }, + "./assets/*": "./dist/assets/*" + }, + "dependencies": { + "@itk-wasm/image-io": "1.6.1", + "comlink": "^4.4.2", + "dcmjs": "^0.52.0", + "gl-matrix": "3.4.3", + "itk-wasm": "^1.0.0-b.199", + "mitt": "^3.0.1" + }, + "peerDependencies": { + "@kitware/vtk.js": "^38.0.0" + }, + "peerDependenciesMeta": { + "@kitware/vtk.js": { + "optional": true + } + } +} diff --git a/packages/dicom/scripts/build.mjs b/packages/dicom/scripts/build.mjs new file mode 100644 index 000000000..ce251206e --- /dev/null +++ b/packages/dicom/scripts/build.mjs @@ -0,0 +1,95 @@ +import { execFileSync } from 'node:child_process'; +import { cp, mkdir, readFile, readdir } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { dirname, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'vite'; + +const packageRoot = fileURLToPath(new URL('..', import.meta.url)); +const root = resolve(packageRoot, '../..'); +const require = createRequire(import.meta.url); +const outDir = resolve(packageRoot, process.argv[2] ?? 'dist'); +const manifest = JSON.parse( + await readFile(resolve(packageRoot, 'package.json'), 'utf8') +); +const dependencies = Object.keys({ + ...manifest.dependencies, + ...manifest.peerDependencies, +}); +const external = (id) => + dependencies.some((name) => id === name || id.startsWith(`${name}/`)); + +async function sourceFiles(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + const files = await Promise.all( + entries.map((entry) => { + const file = resolve(directory, entry.name); + if (entry.isDirectory()) + return entry.name === '__tests__' ? [] : sourceFiles(file); + return entry.name.endsWith('.ts') && !/\.(d|worker)\.ts$/.test(entry.name) + ? [file] + : []; + }) + ); + return files.flat(); +} + +const sources = ( + await Promise.all( + ['core', 'vtk'].map((dir) => sourceFiles(resolve(packageRoot, dir))) + ) +).flat(); + +await build({ + configFile: false, + root: packageRoot, + publicDir: false, + base: './', + build: { + outDir, + emptyOutDir: true, + sourcemap: true, + lib: { + entry: Object.fromEntries( + sources.map((file) => [ + relative(packageRoot, file) + .replaceAll('\\', '/') + .replace(/\.ts$/, ''), + file, + ]) + ), + formats: ['es'], + fileName: (_format, entry) => `${entry}.js`, + }, + rollupOptions: { external }, + }, + worker: { format: 'es' }, +}); +execFileSync( + process.execPath, + [ + require.resolve('typescript/bin/tsc'), + '-p', + 'packages/dicom/tsconfig.build.json', + '--outDir', + outDir, + ], + { cwd: root, stdio: 'inherit' } +); + +const moduleRoot = (name) => resolve(dirname(require.resolve(name)), '..'); +const assets = resolve(outDir, 'assets'); +await mkdir(resolve(assets, 'image-io'), { recursive: true }); +await cp( + resolve( + moduleRoot('itk-wasm'), + 'dist/pipeline/web-workers/bundles/itk-wasm-pipeline.min.worker.js' + ), + resolve(assets, 'itk-wasm-pipeline.min.worker.js') +); +const pipelines = resolve(moduleRoot('@itk-wasm/image-io'), 'dist/pipelines'); +for (const name of await readdir(pipelines)) { + if (/^gdcm-read-image\.(js|wasm|wasm\.zst)$/.test(name)) { + await cp(resolve(pipelines, name), resolve(assets, 'image-io', name)); + } +} diff --git a/packages/dicom/scripts/check-consumers.mjs b/packages/dicom/scripts/check-consumers.mjs new file mode 100644 index 000000000..31a0411c2 --- /dev/null +++ b/packages/dicom/scripts/check-consumers.mjs @@ -0,0 +1,97 @@ +import { execFileSync } from 'node:child_process'; +import { cp, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { tmpdir } from 'node:os'; +import { resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { build } from 'vite'; + +const root = resolve(fileURLToPath(new URL('../../..', import.meta.url))); +const packageRoot = resolve(root, 'packages/dicom'); +const fixture = resolve(root, 'tests/fixtures/dicom-consumer'); +const require = createRequire(import.meta.url); + +const forbiddenModule = (id, kind) => { + const path = id.replaceAll('\\', '/'); + return ( + path.startsWith(`${root.replaceAll('\\', '/')}/src/`) || + /\/node_modules\/(vue|pinia|@vue\/|@vueuse\/)/.test(path) || + (kind === 'core' && path.includes('/node_modules/@kitware/vtk.js/')) + ); +}; + +export async function buildConsumer( + kind, + outDir, + packageDist = resolve(packageRoot, 'dist') +) { + await build({ + configFile: false, + root: fixture, + publicDir: false, + base: './', + resolve: { + alias: { + '@volview/dicom': packageDist, + }, + }, + plugins: [ + { + name: 'independent-dicom-consumer', + generateBundle() { + for (const id of this.getModuleIds()) { + if (forbiddenModule(id, kind)) + this.error(`Unexpected ${kind} consumer dependency: ${id}`); + } + }, + }, + ], + build: { + outDir, + emptyOutDir: true, + rollupOptions: { input: resolve(fixture, `${kind}.html`) }, + }, + worker: { format: 'es' }, + }); + await cp(resolve(packageDist, 'assets'), resolve(outDir, 'assets'), { + recursive: true, + }); +} + +async function checkDeclarations(directory) { + const config = { + extends: resolve(root, 'tsconfig.json'), + compilerOptions: { + baseUrl: root, + types: ['node'], + typeRoots: [resolve(root, 'node_modules/@types')], + paths: { + '@volview/dicom/core/*': ['packages/dicom/dist/core/*'], + '@volview/dicom/vtk/*': ['packages/dicom/dist/vtk/*'], + }, + }, + include: [`${fixture}/*.ts`], + exclude: [], + }; + const configPath = resolve(directory, 'tsconfig.json'); + await writeFile(configPath, JSON.stringify(config)); + execFileSync( + process.execPath, + [require.resolve('typescript/bin/tsc'), '-p', configPath], + { cwd: root, stdio: 'inherit' } + ); +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(resolve(process.argv[1])).href +) { + const directory = await mkdtemp(resolve(tmpdir(), 'dicom-consumers-')); + try { + await checkDeclarations(directory); + for (const kind of ['core', 'vtk']) + await buildConsumer(kind, resolve(directory, kind)); + } finally { + await rm(directory, { recursive: true, force: true }); + } +} diff --git a/packages/dicom/tsconfig.build.json b/packages/dicom/tsconfig.build.json new file mode 100644 index 000000000..0a535382c --- /dev/null +++ b/packages/dicom/tsconfig.build.json @@ -0,0 +1,23 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": false, + "allowImportingTsExtensions": true, + "emitDeclarationOnly": true, + "declaration": true, + "declarationMap": true, + "outDir": "./dist", + "rootDir": ".", + "types": [], + "baseUrl": ".", + "paths": {} + }, + "include": [ + "core/**/*.ts", + "vtk/**/*.ts" + ], + "exclude": [ + "**/__tests__/**", + "dist" + ] +} diff --git a/packages/dicom/vtk/__tests__/volumeImage.spec.ts b/packages/dicom/vtk/__tests__/volumeImage.spec.ts new file mode 100644 index 000000000..0b2eff89e --- /dev/null +++ b/packages/dicom/vtk/__tests__/volumeImage.spec.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from 'vitest'; +import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; +import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; +import { createDicomRuntime } from '../../core/runtime/createDicomRuntime'; +import { loadVolume } from '../../core/volume/loadVolume'; +import { + allocated, + pixelSlice, + valueDecoder, +} from '../../core/volume/__tests__/volumeFixture'; +import type { Volume } from '../../core/volume/allocateVolume'; +import { + applyVolumeUpdate, + sliceThumbnail, + toVtkImageData, +} from '../volumeImage'; + +const stack = (values: number[], previous?: Volume) => + allocated( + values.map((z) => pixelSlice(z)), + previous + ); + +const rangeOf = (image: vtkImageData) => [ + ...image.getPointData().getScalars().getRange(0), +]; + +/** Loads one slice at a time, recording the scalar range after each update. */ +async function loadRanges(volume: Volume) { + const image = toVtkImageData(volume); + const runtime = createDicomRuntime({ + decoder: valueDecoder(), + decodeConcurrency: 1, + }); + const ranges: number[][] = []; + for await (const update of loadVolume(volume, { + runtime, + signal: new AbortController().signal, + readAhead: 1, + })) { + applyVolumeUpdate(image, update); + ranges.push(rangeOf(image)); + } + runtime.dispose(); + return { image, ranges }; +} + +describe('vtk volume adapter', () => { + it('wraps the volume buffer and geometry without copying', () => { + const volume = stack([0, 1, 2]); + + const image = toVtkImageData(volume); + + expect(image.getPointData().getScalars().getData()).toBe(volume.data); + expect(image.getDimensions()).toEqual([4, 4, 3]); + expect(image.getSpacing()).toEqual([0.5, 0.5, 1]); + expect(image.getOrigin()).toEqual([0, 0, 0]); + expect(Array.from(image.getDirection())).toEqual([...volume.direction]); + image.delete(); + }); + + it('starts from a placeholder range until a slice decodes, then widens it', async () => { + const volume = stack([0, 1, 2, 3, 4]); + const empty = toVtkImageData(volume); + expect(rangeOf(empty)).toEqual([0, 255]); + empty.delete(); + + const { image, ranges } = await loadRanges(volume); + + expect(ranges).toEqual([ + [2, 2], + [0, 2], + [0, 4], + [0, 4], + [0, 4], + ]); + image.delete(); + }); + + it('replaces the placeholder even when every slice loaded before the first update applies', async () => { + const volume = stack([300, 301, 302]); + const image = toVtkImageData(volume); + const runtime = createDicomRuntime({ decoder: valueDecoder() }); + const updates = []; + for await (const update of loadVolume(volume, { + runtime, + signal: new AbortController().signal, + })) + updates.push(update); + runtime.dispose(); + + updates.forEach((update) => applyVolumeUpdate(image, update)); + + expect(rangeOf(image)).toEqual([300, 302]); + image.delete(); + }); + + it('starts a grown volume from the range of the slices it carried over', async () => { + const [one, three] = [pixelSlice(1), pixelSlice(3)]; + const sparse = allocated([one, three]); + (await loadRanges(sparse)).image.delete(); + + const image = toVtkImageData( + allocated([one, pixelSlice(2), three], sparse) + ); + + expect(rangeOf(image)).toEqual([1, 3]); + image.delete(); + }); + + it('shows green and blue pixels of an RGB slice as luminance', () => { + const image = vtkImageData.newInstance(); + image.setDimensions(3, 1, 1); + image.getPointData().setScalars( + vtkDataArray.newInstance({ + numberOfComponents: 3, + values: new Uint8Array([0, 0, 0, 0, 255, 0, 0, 0, 255]), + }) + ); + + expect(Array.from(sliceThumbnail(image, 0).data)).toEqual([0, 255, 50]); + image.delete(); + }); +}); diff --git a/packages/dicom/vtk/thumbnail.ts b/packages/dicom/vtk/thumbnail.ts new file mode 100644 index 000000000..5aa48b7ea --- /dev/null +++ b/packages/dicom/vtk/thumbnail.ts @@ -0,0 +1,99 @@ +/** An 8 bit greyscale slice, small enough to encode as a thumbnail. */ +export type ThumbnailSlice = { + width: number; + height: number; + data: Uint8Array; +}; + +export type SliceToThumbnailInput = { + data: ArrayLike; + width: number; + height: number; + // Samples per pixel; RGB samples are converted to luminance. + components?: number; + // The window mapped onto 0..255. + range: readonly [number, number]; + maxSize?: number; +}; + +export const THUMBNAIL_MAX_SIZE = 256; + +const BYTE_MAX = 255; + +const thumbnailSample = ( + data: ArrayLike, + offset: number, + components: number +) => + components >= 3 + ? 0.299 * data[offset] + 0.587 * data[offset + 1] + 0.114 * data[offset + 2] + : data[offset]; + +export function thumbnailRange(data: ArrayLike, components: number) { + let low = Infinity; + let high = -Infinity; + for (let offset = 0; offset < data.length; offset += components) { + const sample = thumbnailSample(data, offset, components); + if (!Number.isFinite(sample)) continue; + low = Math.min(low, sample); + high = Math.max(high, sample); + } + return [low, high] as const; +} + +/** Downsamples one slice and casts it to 8 bit greyscale. */ +export function sliceToThumbnail({ + data, + width, + height, + components = 1, + range, + maxSize = THUMBNAIL_MAX_SIZE, +}: SliceToThumbnailInput): ThumbnailSlice { + const [low, high] = range; + const span = high - low; + + // One integer stride on both axes, so the aspect ratio survives. + const stride = Math.max(1, Math.ceil(Math.max(width, height) / maxSize)); + const thumbWidth = Math.ceil(width / stride); + const thumbHeight = Math.ceil(height / stride); + + const toByte = (sample: number) => { + if (!Number.isFinite(sample) || span <= 0) return 0; + const scaled = Math.round(((sample - low) / span) * BYTE_MAX); + return Math.min(BYTE_MAX, Math.max(0, scaled)); + }; + + const thumbData = Uint8Array.from( + { length: thumbWidth * thumbHeight }, + (_, index) => { + const column = (index % thumbWidth) * stride; + const row = Math.floor(index / thumbWidth) * stride; + return toByte( + thumbnailSample(data, (row * width + column) * components, components) + ); + } + ); + + return { width: thumbWidth, height: thumbHeight, data: thumbData }; +} + +/** Encodes a thumbnail slice as a PNG data URI. */ +export function encodeThumbnailToUri(slice: ThumbnailSlice) { + const { width, height, data } = slice; + const image = new ImageData(width, height); + const pixels = new Uint32Array(image.data.buffer); + // ABGR order. + data.forEach((byte, index) => { + pixels[index] = (BYTE_MAX << 24) | (byte << 16) | (byte << 8) | byte; + }); + + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext('2d'); + if (!context) return ''; + + context.putImageData(image, 0, 0); + return canvas.toDataURL('image/png'); +} diff --git a/packages/dicom/vtk/volumeImage.ts b/packages/dicom/vtk/volumeImage.ts new file mode 100644 index 000000000..e4f8d2526 --- /dev/null +++ b/packages/dicom/vtk/volumeImage.ts @@ -0,0 +1,74 @@ +import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; +import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; +import type { Vector3 } from '@kitware/vtk.js/types'; +import type { mat3 } from 'gl-matrix'; +import { loadedRange, type Volume } from '../core/volume/allocateVolume'; +import type { VolumeUpdate } from '../core/volume/loadVolume'; +import { sliceToThumbnail, thumbnailRange } from './thumbnail'; + +// Volume rendering needs a range before the first slice decodes. +const PLACEHOLDER_RANGE = { min: 0, max: 255 }; +const placeholders = new WeakSet(); + +/** Wraps the volume's buffer in a vtkImageData; the two share memory. */ +export function toVtkImageData(volume: Volume) { + const { dimensions, components } = volume; + const image = vtkImageData.newInstance(); + image.setDimensions([...dimensions]); + image.setOrigin([...volume.origin] as Vector3); + image.setSpacing([...volume.spacing]); + image.setDirection(volume.direction as mat3); + const scalars = vtkDataArray.newInstance({ + numberOfComponents: components, + values: volume.data, + }); + image.getPointData().setScalars(scalars); + const ranges = loadedRange(volume); + if (ranges.length === 0) { + scalars.setRange(PLACEHOLDER_RANGE, 0); + placeholders.add(scalars); + } + ranges.forEach(([min, max], component) => + scalars.setRange({ min, max }, component) + ); + return image; +} + +/** Widens the scalar range by a decoded slice and marks the image modified. */ +export function applyVolumeUpdate(image: vtkImageData, update: VolumeUpdate) { + if ('error' in update) return; + const scalars = image.getPointData().getScalars(); + // Slices may load faster than updates are applied, so the placeholder is + // tracked rather than inferred from the loaded count. + const replace = placeholders.delete(scalars); + update.range.forEach(([min, max], component) => { + const [low, high] = replace + ? [min, max] + : (scalars.getRange(component) as [number, number]); + scalars.setRange( + { min: Math.min(low, min), max: Math.max(high, max) }, + component + ); + }); + scalars.modified(); + image.modified(); +} + +/** An 8 bit thumbnail of one loaded slice, windowed to the loaded range. */ +export function sliceThumbnail(image: vtkImageData, slice: number) { + const scalars = image.getPointData().getScalars(); + const components = scalars.getNumberOfComponents(); + const [width, height] = image.getDimensions(); + const samplesPerSlice = width * height * components; + const data = scalars.getData(); + return sliceToThumbnail({ + data: data.subarray(slice * samplesPerSlice, (slice + 1) * samplesPerSlice), + width, + height, + components, + range: + components >= 3 + ? thumbnailRange(data, components) + : (scalars.getRange(0) as [number, number]), + }); +} diff --git a/scripts/checks/complexity.mjs b/scripts/checks/complexity.mjs index 977054074..758e00cad 100755 --- a/scripts/checks/complexity.mjs +++ b/scripts/checks/complexity.mjs @@ -11,7 +11,7 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import { git, materialize, stagedContext } from './git.mjs'; import { limits as LIMITS } from './config.mjs'; -const SOURCE = /^src\/.*\.(ts|js|vue)$/; +const SOURCE = /^(src|packages\/dicom)\/.*\.(ts|js|vue)$/; const EXCLUDED = /(__tests__|\.(spec|test)\.|\.d\.ts$|emscripten-build)/; const { base, baseRef, changed: entries, worktree } = stagedContext(); diff --git a/src/components/ImageSpacingDetails.vue b/src/components/ImageSpacingDetails.vue new file mode 100644 index 000000000..05da6ab11 --- /dev/null +++ b/src/components/ImageSpacingDetails.vue @@ -0,0 +1,113 @@ + + + diff --git a/src/components/PatientStudyVolumeBrowser.vue b/src/components/PatientStudyVolumeBrowser.vue index 8f8453489..572d5d60c 100644 --- a/src/components/PatientStudyVolumeBrowser.vue +++ b/src/components/PatientStudyVolumeBrowser.vue @@ -1,5 +1,5 @@ + + diff --git a/tests/fixtures/dicom-consumer/composition.ts b/tests/fixtures/dicom-consumer/composition.ts new file mode 100644 index 000000000..4eddc15e9 --- /dev/null +++ b/tests/fixtures/dicom-consumer/composition.ts @@ -0,0 +1,117 @@ +import { + emptyRegistry, + registerInstances, +} from '@volview/dicom/core/collections/instanceRegistry'; +import { getDatasetTag } from '@volview/dicom/core/metadata/datasetAccess'; +import type { Instance } from '@volview/dicom/core/instance/readInstance'; +import corpus from '../../dicomCompositionCorpus.json'; +import { failed, never, report, runtime, sourceOf } from './shared'; +import { loadCollection } from './loadVolume'; +import { describeVolume } from './describeVolume'; + +let registry = emptyRegistry; +const loaded = new Map>>(); +const params = new URL(location.href).searchParams; +const selected = corpus.cases.find(({ id }) => id === params.get('case'))!; +const incremental = params.get('mode') === 'incremental'; + +const append = (parent: HTMLElement, name: string, value: string) => { + const output = document.createElement('output'); + output.dataset.field = name; + output.textContent = value; + parent.append(output); +}; + +async function readFixture(name: string) { + const url = new URL( + `./corpus-data/${encodeURIComponent(name)}`, + document.baseURI + ); + const input = + params.get('source') === 'file' + ? new File([await (await fetch(url)).blob()], name) + : url; + return runtime.readInstance(sourceOf(input), never); +} + +async function render(status: string) { + document.querySelector('main')!.replaceChildren(); + for (const { volume, image } of loaded.values()) { + const section = document.createElement('section'); + section.className = 'volume'; + const members = volume.members.map(({ dataset }) => + getDatasetTag(dataset, '00080018')!.trim() + ); + section.dataset.firstSop = members[0]; + append(section, 'members', members.join(', ')); + await describeVolume(image, (name, value) => append(section, name, value)); + document.querySelector('main')!.append(section); + } + report('status', status); +} + +async function register(instances: Instance[], status: string) { + const { state, updates, removed } = registerInstances(registry, instances); + registry = state; + removed.forEach((id) => { + loaded.get(id)?.image.delete(); + loaded.delete(id); + }); + for (const update of updates) { + const previous = loaded.get(update.id); + loaded.set( + update.id, + await loadCollection(update, { previous: previous?.volume }) + ); + previous?.image.delete(); + } + await render(status); +} + +async function run() { + // Interleave acquisitions/series and reverse their spatial order so neither + // input order nor adjacent file names can stand in for physical ordering. + const names = selected.volumes[0].files + .flatMap((_, index) => + selected.volumes.flatMap(({ files }) => + files[index] ? [files[index]] : [] + ) + ) + .reverse(); + const instances = await Promise.all(names.map(readFixture)); + const initial = instances.filter((_, inputIndex) => + selected.volumes.some(({ files }) => { + const spatialIndex = files.indexOf(names[inputIndex]); + return spatialIndex >= 0 && spatialIndex % 2 === 0; + }) + ); + if (!incremental) { + await register(instances, 'complete'); + return; + } + await register(initial, 'partial'); + const button = document.querySelector('#complete-import')!; + button.disabled = false; + button.addEventListener( + 'click', + () => { + button.disabled = true; + document.querySelector('#status')!.textContent = 'loading'; + const remaining = instances.filter( + (instance) => !initial.includes(instance) + ); + register([...remaining, initial[0], initial[1]], 'complete').catch( + failed + ); + }, + { once: true } + ); +} + +window.addEventListener( + 'pagehide', + () => loaded.forEach(({ image }) => image.delete()), + { once: true } +); + +run().catch(failed); diff --git a/tests/fixtures/dicom-consumer/compositionReference.py b/tests/fixtures/dicom-consumer/compositionReference.py new file mode 100644 index 000000000..7f24a81bf --- /dev/null +++ b/tests/fixtures/dicom-consumer/compositionReference.py @@ -0,0 +1,99 @@ +"""Check composed-volume expectations using pydicom and NumPy, independently of VolView. + +First download the fixtures with node tests/downloadDatasets.ts. This optional +reference check requires pydicom, NumPy and a JPEG Lossless plugin such as +pylibjpeg-libjpeg. It reads cached inputs and never creates binary fixtures. +""" +import argparse +import hashlib +import json +from pathlib import Path + +import numpy as np +import pydicom + + +def declared_range(ds): + bits = int(ds.BitsStored) + signed = int(ds.PixelRepresentation) == 1 + slope = float(ds.get('RescaleSlope', 1)) + intercept = float(ds.get('RescaleIntercept', 0)) + stored = (-(2 ** (bits - 1)), 2 ** (bits - 1) - 1) if signed else (0, 2 ** bits - 1) + return bits, slope, intercept, [value * slope + intercept for value in stored] + + +def stores_float32(items): + """VolView keeps a fractional rescale in float32 while adjacent stored steps stay apart.""" + declared = [declared_range(ds) for ds in items] + if all(slope.is_integer() and intercept.is_integer() for _, slope, intercept, _ in declared): + return False + return all( + bits <= 24 and slope != 0 and max(map(abs, ends)) * 2 ** -23 < abs(slope) + for bits, slope, intercept, ends in declared + ) + + +def reference(items): + first = items[0] + axes = np.array(first.ImageOrientationPatient, dtype=np.float64).reshape(2, 3) + axes /= np.linalg.norm(axes, axis=1)[:, None] + normal = np.cross(*axes) + ordered = sorted(items, key=lambda ds: np.dot(ds.ImagePositionPatient, normal)) + positions = np.array([ds.ImagePositionPatient for ds in ordered], dtype=np.float64) + projected = positions @ normal + gaps = np.diff(projected) + step = float(np.median(gaps)) + assert step > 0 and np.allclose(gaps, step, atol=1e-4, rtol=0) + assert np.allclose(positions, positions[0] + np.outer(projected - projected[0], normal), atol=1e-4, rtol=0) + assert len({str(ds.SeriesInstanceUID) for ds in ordered}) == 1 + assert len({str(ds.AcquisitionNumber) for ds in ordered}) == 1 + for ds in ordered: + assert int(ds.get('NumberOfFrames', 1)) == 1 + assert np.allclose(ds.ImageOrientationPatient, axes.ravel(), atol=1e-6, rtol=0) + assert np.allclose(ds.PixelSpacing, first.PixelSpacing, atol=1e-6, rtol=0) + pixels = np.stack([ + ds.pixel_array.astype(np.float64) * float(ds.get('RescaleSlope', 1)) + float(ds.get('RescaleIntercept', 0)) + for ds in ordered + ]).astype(' + + + + DICOM core consumer + + + +

DICOM core consumer

+
+
+ + + diff --git a/tests/fixtures/dicom-consumer/core.ts b/tests/fixtures/dicom-consumer/core.ts new file mode 100644 index 000000000..fbf2cfc99 --- /dev/null +++ b/tests/fixtures/dicom-consumer/core.ts @@ -0,0 +1,53 @@ +import { fromBlob, readBytes } from '@volview/dicom/core/source/byteSource'; +import { + assetUrls, + createRuntime, + describeMetadata, + failed, + loadInstance, + never, + report, + runtime, +} from './shared'; +import { fixtureBytes } from './fixtureData'; + +async function recoverWorker() { + const recovering = createRuntime({ + assets: assetUrls('./recovering-worker.js'), + decodeConcurrency: 1, + }); + const file = new File( + [fixtureBytes() as Uint8Array], + 'fixture.dcm' + ); + const instance = await recovering.readInstance(fromBlob(file), never); + // Decoding may transfer the bytes away, so each decode reads its own. Both + // are read before either decode starts, so the first call takes the lane + // whose worker fails. + const readCopy = () => readBytes(instance.source, never); + const decode = (bytes: Uint8Array) => + recovering.decode({ instance, bytes }, never); + const [firstBytes, queuedBytes] = await Promise.all([readCopy(), readCopy()]); + const first = decode(firstBytes).then( + () => report('first-error', 'unexpected success'), + (error: Error) => report('first-error', error.message) + ); + const queued = decode(queuedBytes); + const [, image] = await Promise.all([first, queued]); + report('queued-pixels', Array.from(image.data).join(', ')); + const retry = await decode(await readCopy()); + report('retry-pixels', Array.from(retry.data).join(', ')); + report('status', 'complete'); +} + +async function run() { + const instance = await loadInstance(); + describeMetadata(instance); + const bytes = await readBytes(instance.source, never); + const image = await runtime.decode({ instance, bytes }, never); + report('pixels', Array.from(image.data).join(', ')); + report('dimensions', image.size.join(', ')); + report('status', 'complete'); +} +const scenario = new URL(location.href).searchParams.get('scenario'); +(scenario === 'worker-recovery' ? recoverWorker() : run()).catch(failed); diff --git a/tests/fixtures/dicom-consumer/corpus.html b/tests/fixtures/dicom-consumer/corpus.html new file mode 100644 index 000000000..261355caa --- /dev/null +++ b/tests/fixtures/dicom-consumer/corpus.html @@ -0,0 +1,12 @@ + + + + + DICOM volume corpus consumer + + +

DICOM volume corpus consumer

+
+ + + diff --git a/tests/fixtures/dicom-consumer/corpus.ts b/tests/fixtures/dicom-consumer/corpus.ts new file mode 100644 index 000000000..d17f30546 --- /dev/null +++ b/tests/fixtures/dicom-consumer/corpus.ts @@ -0,0 +1,35 @@ +import { createRuntime, failed, never, report, sourceOf } from './shared'; +import { loadInstanceVolume } from './loadVolume'; +import { describeVolume } from './describeVolume'; + +const customDecoder = async () => ({ + size: [4, 4, 2], + imageType: { components: 1 }, + data: new Uint16Array([...Array(16).fill(2), ...Array(16).fill(4)]), +}); + +async function run() { + const params = new URL(location.href).searchParams; + const url = new URL( + `./corpus-data/${encodeURIComponent(params.get('name')!)}`, + document.baseURI + ); + const input = + params.get('source') === 'file' + ? new File([await (await fetch(url)).blob()], 'volume.dcm') + : url; + const runtime = createRuntime( + params.get('decoder') === 'custom' ? { decoder: customDecoder } : {} + ); + const instance = await runtime.readInstance(sourceOf(input), never); + const { volume, image } = await loadInstanceVolume(instance, { + runtime, + irregularGeometry: + params.get('policy') === 'reject' ? 'reject' : 'preserve-order', + }); + await describeVolume(image, report); + report('reconstruction', volume.reconstruction.kind); + report('status', 'complete'); +} + +run().catch(failed); diff --git a/tests/fixtures/dicom-consumer/describeVolume.ts b/tests/fixtures/dicom-consumer/describeVolume.ts new file mode 100644 index 000000000..cf4c9ddd4 --- /dev/null +++ b/tests/fixtures/dicom-consumer/describeVolume.ts @@ -0,0 +1,28 @@ +import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; + +/** Public consumer output used to check geometry and every calibrated voxel. */ +export async function describeVolume( + image: vtkImageData, + report: (name: string, value: string) => void +) { + const dimensions = image.getDimensions(); + const scalars = image.getPointData().getScalars(); + report('dimensions', dimensions.join(', ')); + report('spacing', image.getSpacing().join(', ')); + report('origin', image.getOrigin().join(', ')); + report('direction', Array.from(image.getDirection()).join(', ')); + report('range', scalars.getRange().join(', ')); + report('first-plane', image.indexToWorld([0, 0, 0]).join(', ')); + report( + 'last-plane', + image.indexToWorld([0, 0, dimensions[2] - 1]).join(', ') + ); + const pixels = Float64Array.from(scalars.getData()); + const digest = await crypto.subtle.digest('SHA-256', pixels.buffer); + report( + 'pixel-hash', + Array.from(new Uint8Array(digest), (value) => + value.toString(16).padStart(2, '0') + ).join('') + ); +} diff --git a/tests/fixtures/dicom-consumer/enhancedFixtures.ts b/tests/fixtures/dicom-consumer/enhancedFixtures.ts new file mode 100644 index 000000000..3b7631f1a --- /dev/null +++ b/tests/fixtures/dicom-consumer/enhancedFixtures.ts @@ -0,0 +1,100 @@ +import { + buildSyntheticDicom, + rawElement, + sequenceItem, +} from '../../specs/syntheticDicom'; + +const concatenate = (parts: Uint8Array[]) => { + const bytes = new Uint8Array( + parts.reduce((length, part) => length + part.length, 0) + ); + let offset = 0; + for (const part of parts) { + bytes.set(part, offset); + offset += part.length; + } + return bytes; +}; + +const text = (group: number, element: number, value: readonly number[]) => { + const string = value.join('\\'); + return rawElement( + group, + element, + 'DS', + new TextEncoder().encode(string.length % 2 ? `${string} ` : string) + ); +}; + +const sequence = (group: number, element: number, items: Uint8Array[]) => + rawElement(group, element, 'SQ', concatenate(items.map(sequenceItem))); + +const position = (value: readonly number[]) => + sequence(0x0020, 0x9113, [text(0x0020, 0x0032, value)]); + +const transformation = ([slope, intercept]: readonly [number, number]) => + sequence(0x0028, 0x9145, [ + concatenate([ + text(0x0028, 0x1052, [intercept]), + text(0x0028, 0x1053, [slope]), + ]), + ]); + +const temporalPosition = (value: number) => { + const bytes = new Uint8Array(4); + new DataView(bytes.buffer).setUint32(0, value, true); + return sequence(0x0020, 0x9111, [rawElement(0x0020, 0x9128, 'UL', bytes)]); +}; + +export type EnhancedFixtureOptions = { + pixelValues: number[]; + positions?: number[][]; + sharedPosition?: number[]; + temporalPositions?: number[]; + transforms?: Array; +}; + +/** Encoded spatial/temporal frames with geometry exclusively in Functional Groups. */ +export function enhancedFixtureBytes(options: EnhancedFixtureOptions) { + const { + pixelValues, + positions, + sharedPosition, + temporalPositions, + transforms, + } = options; + const shared = [ + sequence(0x0020, 0x9116, [text(0x0020, 0x0037, [1, 0, 0, 0, 1, 0])]), + sequence(0x0028, 0x9110, [text(0x0028, 0x0030, [1, 1])]), + ]; + if (sharedPosition) shared.unshift(position(sharedPosition)); + const frames = pixelValues.map((_, index) => + concatenate([ + ...(temporalPositions + ? [temporalPosition(temporalPositions[index])] + : []), + ...(sharedPosition + ? [] + : [position(positions?.[index] ?? [10, 20, 30 + index])]), + ...(transforms ? [transformation(transforms[index])] : []), + ]) + ); + return buildSyntheticDicom({ + studyUid: '1.2.826.0.1.3680043.10.999.50', + seriesUid: '1.2.826.0.1.3680043.10.999.51', + sopUid: '1.2.826.0.1.3680043.10.999.52', + sopClassUid: transforms + ? '1.2.840.10008.5.1.4.1.1.2.1' + : '1.2.840.10008.5.1.4.1.1.4.1', + modality: transforms ? 'CT' : 'MR', + instanceNumber: 1, + imagePositionPatient: null, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + rootGeometry: false, + framePixelValues: pixelValues, + extraElements: [ + sequence(0x5200, 0x9229, [concatenate(shared)]), + sequence(0x5200, 0x9230, frames), + ], + }); +} diff --git a/tests/fixtures/dicom-consumer/fixtureData.ts b/tests/fixtures/dicom-consumer/fixtureData.ts new file mode 100644 index 000000000..d5286eb49 --- /dev/null +++ b/tests/fixtures/dicom-consumer/fixtureData.ts @@ -0,0 +1,44 @@ +import { + buildSyntheticDicom, + stripFileMeta, + type SyntheticSliceOptions, +} from '../../specs/syntheticDicom'; + +export const fixtureBytes = (overrides: Partial = {}) => + buildSyntheticDicom({ + studyUid: '1.2.826.0.1.3680043.10.999.20', + seriesUid: '1.2.826.0.1.3680043.10.999.21', + sopUid: '1.2.826.0.1.3680043.10.999.22', + instanceNumber: 1, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [10, 20, 30], + pixelSpacing: [2, 3], + spacingBetweenSlices: 4, + pixelValue: 5, + rescaleSlope: 2, + rescaleIntercept: -20, + patientName: 'EXTRACTED^DICOM', + ...overrides, + }); + +/** Numeric text padding found in a legacy CT series. Binary values stay intact. */ +export function nullPaddedFixtureBytes( + overrides: Partial = {} +) { + const bytes = fixtureBytes(overrides); + const view = new DataView(bytes.buffer); + let offset = bytes.length - stripFileMeta(bytes).length; + while (offset < bytes.length) { + const vr = String.fromCharCode(bytes[offset + 4], bytes[offset + 5]); + const long = vr === 'OB' || vr === 'OW'; + const header = long ? 12 : 8; + const length = long + ? view.getUint32(offset + 8, true) + : view.getUint16(offset + 6, true); + const end = offset + header + length; + if ((vr === 'DS' || vr === 'IS') && bytes[end - 1] === 0x20) + bytes[end - 1] = 0; + offset = end; + } + return bytes; +} diff --git a/tests/fixtures/dicom-consumer/loadVolume.ts b/tests/fixtures/dicom-consumer/loadVolume.ts new file mode 100644 index 000000000..3c0a3a243 --- /dev/null +++ b/tests/fixtures/dicom-consumer/loadVolume.ts @@ -0,0 +1,45 @@ +import { + emptyRegistry, + registerInstances, + type InstanceCollectionUpdate, +} from '@volview/dicom/core/collections/instanceRegistry'; +import type { Instance } from '@volview/dicom/core/instance/readInstance'; +import { + allocateVolume, + type AllocateVolumeOptions, + type Volume, +} from '@volview/dicom/core/volume/allocateVolume'; +import { loadVolume } from '@volview/dicom/core/volume/loadVolume'; +import type { DicomRuntime } from '@volview/dicom/core/runtime/createDicomRuntime'; +import { + applyVolumeUpdate, + toVtkImageData, +} from '@volview/dicom/vtk/volumeImage'; +import { never, runtime as defaultRuntime } from './shared'; + +type LoadOptions = AllocateVolumeOptions & { + previous?: Volume; + runtime?: DicomRuntime; +}; + +/** Allocates a planned collection and decodes it the way a viewer would. */ +export async function loadCollection( + update: Pick, + { previous, runtime = defaultRuntime, ...options }: LoadOptions = {} +) { + const allocation = allocateVolume(update, options, previous); + if (allocation.kind !== 'volume') + throw new Error(`Expected a volume, got ${allocation.kind}`); + const { volume } = allocation; + const image = toVtkImageData(volume); + for await (const loaded of loadVolume(volume, { runtime, signal: never })) { + if ('error' in loaded) throw loaded.error; + applyVolumeUpdate(image, loaded); + } + return { volume, image }; +} + +export function loadInstanceVolume(instance: Instance, options?: LoadOptions) { + const [update] = registerInstances(emptyRegistry, [instance]).updates; + return loadCollection(update, options); +} diff --git a/tests/fixtures/dicom-consumer/parity.html b/tests/fixtures/dicom-consumer/parity.html new file mode 100644 index 000000000..611687a20 --- /dev/null +++ b/tests/fixtures/dicom-consumer/parity.html @@ -0,0 +1,12 @@ + + + + + DICOM native frame parity + + +

DICOM native frame parity

+
+ + + diff --git a/tests/fixtures/dicom-consumer/parity.ts b/tests/fixtures/dicom-consumer/parity.ts new file mode 100644 index 000000000..c423f9794 --- /dev/null +++ b/tests/fixtures/dicom-consumer/parity.ts @@ -0,0 +1,115 @@ +import { readBytes } from '@volview/dicom/core/source/byteSource'; +import type { Instance } from '@volview/dicom/core/instance/readInstance'; +import { + defaultDecoderTable, + planDecode, + type DecodePlan, +} from '@volview/dicom/core/pixels/decoderTable'; +import { + getVolumeBufferType, + instancePixelFormats, + type VolumeBufferConstructor, +} from '@volview/dicom/core/volume/pixelFormat'; +import { createRuntime, failed, never, report, sourceOf } from './shared'; + +// Decodes each listed instance through GDCM and, where the decoder table +// plans native frames, frame by frame from ranged reads, then reports the +// first sample where what each path writes into the volume differs. Integer +// GDCM output must also equal the native samples before any conversion. + +const runtime = createRuntime(); + +const firstMismatch = ( + expected: ArrayLike, + actual: ArrayLike +) => { + if (expected.length !== actual.length) + return `length ${expected.length} vs ${actual.length}`; + for (let index = 0; index < expected.length; index += 1) + if (!Object.is(expected[index], actual[index])) + return `sample ${index}: GDCM ${expected[index]}, native ${actual[index]}`; + return null; +}; + +const isFloat = (data: ArrayLike) => + data instanceof Float32Array || data instanceof Float64Array; + +async function decodeFrames( + instance: Instance, + plan: Extract, + Target: VolumeBufferConstructor +) { + const frames = await Promise.all( + plan.index.frames.map( + async (range) => + plan.decode( + await readBytes(instance.source, never, range), + plan.format, + Target + ).samples + ) + ); + const samples = new Target(frames.reduce((n, frame) => n + frame.length, 0)); + frames.reduce((offset, frame) => { + samples.set(frame, offset); + return offset + frame.length; + }, 0); + return samples; +} + +async function compare(name: string, source: string) { + const url = new URL( + `./corpus-data/${encodeURIComponent(name)}`, + document.baseURI + ); + const input = + source === 'file' ? new File([await (await fetch(url)).blob()], name) : url; + const instance = await runtime.readInstance(sourceOf(input), never); + const plan = planDecode(defaultDecoderTable, instance); + if (plan.kind !== 'frames') + return { + name, + plan: plan.kind, + reason: plan.kind === 'unsupported' ? plan.error.message : plan.reason, + }; + const gdcm = await runtime.decode( + { instance, bytes: await readBytes(instance.source, never) }, + never + ); + const Target = getVolumeBufferType(instancePixelFormats(instance.dataset)); + const native = await decodeFrames(instance, plan, Target); + return { + name, + plan: plan.kind, + volume: Target.name, + gdcm: gdcm.data.constructor.name, + native: native.constructor.name, + samples: native.length, + mismatch: firstMismatch(new Target(gdcm.data), native), + rawMismatch: isFloat(gdcm.data) ? null : firstMismatch(gdcm.data, native), + }; +} + +async function run() { + const params = new URL(location.href).searchParams; + const source = params.get('source') ?? 'http'; + const listed: string[] = await ( + await fetch(new URL('./corpus-data/parity-cases.json', document.baseURI)) + ).json(); + const names = listed.slice( + Number(params.get('from') ?? 0), + Number(params.get('to') ?? listed.length) + ); + const results = []; + for (const name of names) + results.push( + await compare(name, source).catch((error: Error) => ({ + name, + error: error.message, + })) + ); + report('report', JSON.stringify(results)); + report('status', 'complete'); +} + +run().catch(failed); diff --git a/tests/fixtures/dicom-consumer/server.mjs b/tests/fixtures/dicom-consumer/server.mjs new file mode 100644 index 000000000..43df13ab3 --- /dev/null +++ b/tests/fixtures/dicom-consumer/server.mjs @@ -0,0 +1,108 @@ +import { execFileSync } from 'node:child_process'; +import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { preview } from 'vite'; +import { buildConsumer } from '../../../packages/dicom/scripts/check-consumers.mjs'; + +const root = fileURLToPath(new URL('../../../', import.meta.url)); + +function serveDicom(bytes, request, response) { + const match = /^bytes=(\d+)-(\d*)/.exec(request.headers.range ?? ''); + const start = match ? Number(match[1]) : 0; + const end = match?.[2] + ? Math.min(bytes.length, Number(match[2]) + 1) + : bytes.length; + response.setHeader('Content-Type', 'application/dicom'); + response.setHeader('Accept-Ranges', 'bytes'); + response.setHeader('Content-Length', end - start); + if (match) { + response.statusCode = 206; + response.setHeader( + 'Content-Range', + `bytes ${start}-${end - 1}/${bytes.length}` + ); + } + response.end(bytes.subarray(start, end)); +} + +export async function startDicomConsumerFixtures( + bytes, + { kinds = ['core', 'vtk'], fixtures = {} } = {} +) { + await mkdir(resolve(root, '.tmp'), { recursive: true }); + const directory = await mkdtemp(resolve(root, '.tmp/dicom-browser-')); + const packageDist = resolve(directory, 'package'); + const servers = []; + /** @type {Record} */ + const urls = {}; + try { + execFileSync( + process.execPath, + ['packages/dicom/scripts/build.mjs', packageDist], + { + cwd: root, + stdio: 'inherit', + } + ); + for (const kind of kinds) { + const outDir = resolve(directory, kind); + await buildConsumer(kind, outDir, packageDist); + const pipelineWorker = await readFile( + resolve(outDir, 'assets/itk-wasm-pipeline.min.worker.js') + ); + let workerRequests = 0; + const server = await preview({ + configFile: false, + root, + build: { outDir }, + preview: { host: '127.0.0.1', port: 0 }, + plugins: [ + { + name: 'synthetic-dicom-source', + configurePreviewServer(instance) { + instance.middlewares.use( + '/recovering-worker.js', + (_request, response) => { + response.setHeader('Cache-Control', 'no-store'); + response.setHeader('Content-Type', 'text/javascript'); + if (workerRequests++ === 0) { + response.statusCode = 503; + response.end('temporary worker script failure'); + } else { + response.end(pipelineWorker); + } + } + ); + instance.middlewares.use('/fixture.dcm', (request, response) => { + serveDicom(bytes, request, response); + }); + instance.middlewares.use('/corpus-data', (request, response) => { + const name = decodeURIComponent(request.url?.slice(1) ?? ''); + if (!Object.hasOwn(fixtures, name)) { + response.statusCode = 404; + response.end(); + return; + } + serveDicom(fixtures[name], request, response); + }); + }, + }, + ], + }); + servers.push(server); + urls[kind] = `${server.resolvedUrls.local[0]}${kind}.html`; + } + } catch (error) { + await Promise.all(servers.map((server) => server.close())); + await rm(directory, { recursive: true, force: true }); + throw error; + } + return { + urls, + async close() { + await Promise.all(servers.map((server) => server.close())); + await rm(directory, { recursive: true, force: true }); + }, + }; +} diff --git a/tests/fixtures/dicom-consumer/shared.ts b/tests/fixtures/dicom-consumer/shared.ts new file mode 100644 index 000000000..054e63604 --- /dev/null +++ b/tests/fixtures/dicom-consumer/shared.ts @@ -0,0 +1,66 @@ +import { + createDicomRuntime, + type DicomRuntimeOptions, +} from '@volview/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, fromUrl } from '@volview/dicom/core/source/byteSource'; +import type { Instance } from '@volview/dicom/core/instance/readInstance'; +import { getDatasetTag } from '@volview/dicom/core/metadata/datasetAccess'; +import { readInstanceFacts } from '@volview/dicom/core/collections/instanceFacts'; +import { fixtureBytes } from './fixtureData'; + +export const assetUrls = ( + pipelineWorker = './assets/itk-wasm-pipeline.min.worker.js' +) => ({ + pipelineWorkerUrl: new URL(pipelineWorker, document.baseURI).href, + imageIOUrl: new URL('./assets/image-io', document.baseURI).href, +}); + +const runtimes: Array<{ dispose: () => void }> = []; + +export const createRuntime = (options: DicomRuntimeOptions = {}) => { + const runtime = createDicomRuntime({ assets: assetUrls(), ...options }); + runtimes.push(runtime); + return runtime; +}; + +export const runtime = createRuntime(); + +/** Pages never cancel; disposing the runtime stops everything on pagehide. */ +export const never = new AbortController().signal; + +export const sourceOf = (input: URL | File) => + input instanceof File + ? fromBlob(input) + : fromUrl(input, { fetch: runtime.fetch }); + +export function report(name: string, value: string) { + const output = document.createElement('output'); + output.id = name; + output.textContent = value; + document.querySelector('main')!.append(output); +} + +export async function loadInstance() { + const input = + new URL(location.href).searchParams.get('source') === 'http' + ? new URL('./fixture.dcm', document.baseURI) + : new File([fixtureBytes() as Uint8Array], 'fixture.dcm'); + return runtime.readInstance(sourceOf(input), never); +} + +export function describeMetadata({ dataset }: Instance) { + const facts = readInstanceFacts(dataset); + report('patient', getDatasetTag(dataset, '00100010')!.trim()); + report('position', facts.position!.join(', ')); + report('pixel-spacing', facts.pixelSpacing!.join(', ')); +} + +export function failed(error: unknown) { + report('error', error instanceof Error ? error.message : String(error)); +} + +window.addEventListener( + 'pagehide', + () => runtimes.forEach((owned) => owned.dispose()), + { once: true } +); diff --git a/tests/fixtures/dicom-consumer/vtk.html b/tests/fixtures/dicom-consumer/vtk.html new file mode 100644 index 000000000..8784b9e43 --- /dev/null +++ b/tests/fixtures/dicom-consumer/vtk.html @@ -0,0 +1,25 @@ + + + + + DICOM vtk consumer + + + +

DICOM vtk consumer

+
+
+ + + diff --git a/tests/fixtures/dicom-consumer/vtk.ts b/tests/fixtures/dicom-consumer/vtk.ts new file mode 100644 index 000000000..ff9da257b --- /dev/null +++ b/tests/fixtures/dicom-consumer/vtk.ts @@ -0,0 +1,46 @@ +import '@kitware/vtk.js/Rendering/Profiles/Volume'; +import vtkGenericRenderWindow from '@kitware/vtk.js/Rendering/Misc/GenericRenderWindow'; +import vtkImageMapper from '@kitware/vtk.js/Rendering/Core/ImageMapper'; +import vtkImageSlice from '@kitware/vtk.js/Rendering/Core/ImageSlice'; +import { describeMetadata, failed, loadInstance, report } from './shared'; +import { loadInstanceVolume } from './loadVolume'; + +async function run() { + const instance = await loadInstance(); + describeMetadata(instance); + const { image: data } = await loadInstanceVolume(instance); + + report('dimensions', data.getDimensions().join(', ')); + report('spacing', data.getSpacing().join(', ')); + report('origin', data.getOrigin().join(', ')); + report('range', data.getPointData().getScalars().getRange().join(', ')); + const view = vtkGenericRenderWindow.newInstance({ background: [0, 0, 0] }); + view.setContainer(document.querySelector('#viewport') as HTMLElement); + view.resize(); + const mapper = vtkImageMapper.newInstance(); + mapper.setInputData(data); + mapper.setKSlice(0); + const actor = vtkImageSlice.newInstance(); + actor.setMapper(mapper); + actor.getProperty().setColorWindow(20); + actor.getProperty().setColorLevel(-10); + const renderer = view.getRenderer(); + renderer.addActor(actor); + renderer.getActiveCamera().setParallelProjection(true); + renderer.resetCamera(); + renderer.resetCameraClippingRange(); + view.getRenderWindow().render(); + report('status', 'complete'); + + window.addEventListener( + 'pagehide', + () => { + view.delete(); + actor.delete(); + mapper.delete(); + data.delete(); + }, + { once: true } + ); +} +run().catch(failed); diff --git a/tests/fixtures/oct/dicom.ts b/tests/fixtures/oct/dicom.ts index 731fcf23d..6558f3ac4 100644 --- a/tests/fixtures/oct/dicom.ts +++ b/tests/fixtures/oct/dicom.ts @@ -64,7 +64,7 @@ const orientationSequence = (orientation: string) => export function enhancedFile( frames: Frame[], extraHeader: Uint8Array[] = [], - extraShared: Uint8Array[] = [] + orientation = '1\\0\\0\\0\\1\\0' ) { return new Blob([ concat([ @@ -77,8 +77,7 @@ export function enhancedFile( sequence('52009229', [ concat([ measureSequence('0.01\\0.02'), - orientationSequence('1\\0\\0\\0\\1\\0'), - ...extraShared, + orientationSequence(orientation), ]), ]), sequence( diff --git a/tests/nativePixelDicom.ts b/tests/nativePixelDicom.ts new file mode 100644 index 000000000..821f4849c --- /dev/null +++ b/tests/nativePixelDicom.ts @@ -0,0 +1,278 @@ +// Part 10 files with uncompressed Pixel Data in any native transfer syntax, +// for comparing frame decoders. Stored words are written as given, so high +// bits above Bits Stored can carry anything a test wants. + +import { concatBytes } from '@/packages/dicom/core/utils'; + +export const IMPLICIT_LE = '1.2.840.10008.1.2'; +export const EXPLICIT_LE = '1.2.840.10008.1.2.1'; +export const EXPLICIT_BE = '1.2.840.10008.1.2.2'; + +type Value = + | string + | readonly number[] + | Uint8Array + | ReadonlyArray; +export type DataElement = { tag: number; vr: string; value: Value }; + +const LONG_FORM = new Set([ + 'OB', + 'OD', + 'OF', + 'OL', + 'OV', + 'OW', + 'SQ', + 'UN', + 'UT', +]); +const NUMBER_WIDTH: Record = { + US: 2, + SS: 2, + UL: 4, + SL: 4, + FL: 4, + FD: 8, +}; + +type Encoding = { explicit: boolean; littleEndian: boolean }; + +const uint = (value: number, width: number, littleEndian: boolean) => { + const bytes = new Uint8Array(width); + const view = new DataView(bytes.buffer); + if (width === 2) view.setUint16(0, value, littleEndian); + else view.setUint32(0, value, littleEndian); + return bytes; +}; + +const numbers = (vr: string, values: number[], littleEndian: boolean) => { + const width = NUMBER_WIDTH[vr]; + const bytes = new Uint8Array(width * values.length); + const view = new DataView(bytes.buffer); + values.forEach((value, index) => { + const at = index * width; + if (vr === 'US') view.setUint16(at, value, littleEndian); + else if (vr === 'SS') view.setInt16(at, value, littleEndian); + else if (vr === 'UL') view.setUint32(at, value, littleEndian); + else if (vr === 'SL') view.setInt32(at, value, littleEndian); + else if (vr === 'FL') view.setFloat32(at, value, littleEndian); + else view.setFloat64(at, value, littleEndian); + }); + return bytes; +}; + +const tagBytes = (tag: number, littleEndian: boolean) => + concatBytes([ + uint(tag >>> 16, 2, littleEndian), + uint(tag & 0xffff, 2, littleEndian), + ]); + +function valueBytes(element: DataElement, encoding: Encoding): Uint8Array { + const { vr, value } = element; + if (typeof value === 'string') { + const pad = vr === 'UI' ? '\0' : ' '; + return new TextEncoder().encode(value.length % 2 ? value + pad : value); + } + if (value instanceof Uint8Array) + return value.length % 2 ? concatBytes([value, new Uint8Array(1)]) : value; + if (vr === 'SQ') + return concatBytes( + (value as DataElement[][]).map((item) => { + const body = encodeElements(item, encoding); + return concatBytes([ + tagBytes(0xfffee000, encoding.littleEndian), + uint(body.length, 4, encoding.littleEndian), + body, + ]); + }) + ); + return numbers(vr, value as number[], encoding.littleEndian); +} + +function encodeElement(element: DataElement, encoding: Encoding) { + const { littleEndian } = encoding; + const value = valueBytes(element, encoding); + const head = encoding.explicit + ? LONG_FORM.has(element.vr) + ? [ + new TextEncoder().encode(element.vr), + new Uint8Array(2), + uint(value.length, 4, littleEndian), + ] + : [ + new TextEncoder().encode(element.vr), + uint(value.length, 2, littleEndian), + ] + : [uint(value.length, 4, littleEndian)]; + return concatBytes([tagBytes(element.tag, littleEndian), ...head, value]); +} + +const encodeElements = (elements: DataElement[], encoding: Encoding) => + concatBytes( + [...elements] + .sort((a, b) => a.tag - b.tag) + .map((element) => encodeElement(element, encoding)) + ); + +/** Wraps a data set in a preamble and Explicit VR Little Endian file meta. */ +function part10( + dataset: DataElement[], + transferSyntaxUid: string, + sopClassUid: string, + sopInstanceUid: string +) { + const meta = encodeElements( + [ + { tag: 0x00020001, vr: 'OB', value: new Uint8Array([0, 1]) }, + { tag: 0x00020002, vr: 'UI', value: sopClassUid }, + { tag: 0x00020003, vr: 'UI', value: sopInstanceUid }, + { tag: 0x00020010, vr: 'UI', value: transferSyntaxUid }, + ], + { explicit: true, littleEndian: true } + ); + const groupLength = encodeElement( + { tag: 0x00020000, vr: 'UL', value: [meta.length] }, + { explicit: true, littleEndian: true } + ); + const encoding = { + explicit: transferSyntaxUid !== IMPLICIT_LE, + littleEndian: transferSyntaxUid !== EXPLICIT_BE, + }; + return concatBytes([ + new Uint8Array(128), + new TextEncoder().encode('DICM'), + groupLength, + meta, + encodeElements(dataset, encoding), + ]); +} + +export type NativePixelOptions = { + transferSyntaxUid?: string; + sopClassUid?: string; + modality?: string; + rows?: number; + columns?: number; + /** Written as Number of Frames when given. */ + frames?: number; + samplesPerPixel?: number; + photometric?: string; + planarConfiguration?: number; + bitsAllocated?: number; + bitsStored?: number; + highBit?: number; + pixelRepresentation?: number; + /** Stored words in file order, unsigned, frames one after another. */ + words?: ArrayLike; + rescale?: readonly [slope: number, intercept: number]; + /** One Pixel Value Transformation per frame, in Per-Frame Functional Groups. */ + frameRescales?: ReadonlyArray; + extra?: readonly DataElement[]; + /** Instance Number, which also seeds the default words and the SOP UID. */ + instance?: number; + position?: readonly [number, number, number]; +}; + +/** Every bit pattern a word can hold, spread deterministically over `count`. */ +export function patternWords(count: number, bitsAllocated: number, seed = 1) { + const span = 2 ** bitsAllocated; + let state = seed >>> 0 || 1; + return Array.from({ length: count }, (_, index) => { + // Endpoints first, so the extremes of every width are always covered. + if (index < 4) return [0, span - 1, span / 2, span / 2 - 1][index]; + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return bitsAllocated === 32 ? state : state % span; + }); +} + +const decimal = (value: number) => String(value); + +const frameRescaleGroups = ( + rescales: ReadonlyArray +): DataElement => ({ + tag: 0x52009230, + vr: 'SQ', + value: rescales.map(([slope, intercept]) => [ + { + tag: 0x00289145, + vr: 'SQ', + value: [ + [ + { tag: 0x00281052, vr: 'DS', value: decimal(intercept) }, + { tag: 0x00281053, vr: 'DS', value: decimal(slope) }, + { tag: 0x00281054, vr: 'LO', value: 'US' }, + ], + ], + }, + ]), +}); + +export function nativePixelDicom(options: NativePixelOptions = {}) { + const { + transferSyntaxUid = EXPLICIT_LE, + sopClassUid = '1.2.840.10008.5.1.4.1.1.2', + modality = 'CT', + rows = 5, + columns = 3, + frames, + samplesPerPixel = 1, + photometric = samplesPerPixel === 3 ? 'RGB' : 'MONOCHROME2', + planarConfiguration, + bitsAllocated = 16, + bitsStored = bitsAllocated, + highBit = bitsStored - 1, + pixelRepresentation = 0, + rescale, + frameRescales, + extra = [], + instance = 1, + position = [0, 0, 0], + } = options; + const count = rows * columns * samplesPerPixel * (frames ?? 1); + const words = options.words ?? patternWords(count, bitsAllocated, instance); + if (words.length !== count) + throw new Error(`Expected ${count} stored words, got ${words.length}`); + const littleEndian = transferSyntaxUid !== EXPLICIT_BE; + const width = bitsAllocated / 8; + const pixels = new Uint8Array(count * width); + const view = new DataView(pixels.buffer); + Array.from(words).forEach((word, index) => { + if (width === 1) pixels[index] = word; + else if (width === 2) view.setUint16(index * 2, word, littleEndian); + else view.setUint32(index * 4, word, littleEndian); + }); + const sopInstanceUid = `1.2.826.0.1.3680043.10.997.${instance}`; + const dataset: DataElement[] = [ + { tag: 0x00080016, vr: 'UI', value: sopClassUid }, + { tag: 0x00080018, vr: 'UI', value: sopInstanceUid }, + { tag: 0x00080060, vr: 'CS', value: modality }, + { tag: 0x00100010, vr: 'PN', value: 'NATIVE^PIXELS' }, + { tag: 0x0020000d, vr: 'UI', value: '1.2.826.0.1.3680043.10.997.1000' }, + { tag: 0x0020000e, vr: 'UI', value: '1.2.826.0.1.3680043.10.997.2000' }, + { tag: 0x00200013, vr: 'IS', value: String(instance) }, + { tag: 0x00200032, vr: 'DS', value: position.join('\\') }, + { tag: 0x00200037, vr: 'DS', value: '1\\0\\0\\0\\1\\0' }, + { tag: 0x00280002, vr: 'US', value: [samplesPerPixel] }, + { tag: 0x00280004, vr: 'CS', value: photometric }, + { tag: 0x00280010, vr: 'US', value: [rows] }, + { tag: 0x00280011, vr: 'US', value: [columns] }, + { tag: 0x00280030, vr: 'DS', value: '1\\1' }, + { tag: 0x00280100, vr: 'US', value: [bitsAllocated] }, + { tag: 0x00280101, vr: 'US', value: [bitsStored] }, + { tag: 0x00280102, vr: 'US', value: [highBit] }, + { tag: 0x00280103, vr: 'US', value: [pixelRepresentation] }, + { tag: 0x7fe00010, vr: bitsAllocated === 8 ? 'OB' : 'OW', value: pixels }, + ...extra, + ]; + if (frames !== undefined) + dataset.push({ tag: 0x00280008, vr: 'IS', value: String(frames) }); + if (planarConfiguration !== undefined) + dataset.push({ tag: 0x00280006, vr: 'US', value: [planarConfiguration] }); + if (rescale) + dataset.push( + { tag: 0x00281052, vr: 'DS', value: decimal(rescale[1]) }, + { tag: 0x00281053, vr: 'DS', value: decimal(rescale[0]) } + ); + if (frameRescales) dataset.push(frameRescaleGroups(frameRescales)); + return part10(dataset, transferSyntaxUid, sopClassUid, sopInstanceUid); +} diff --git a/tests/pageobjects/volview.page.ts b/tests/pageobjects/volview.page.ts index 5494eee30..37e58e26b 100644 --- a/tests/pageobjects/volview.page.ts +++ b/tests/pageobjects/volview.page.ts @@ -68,6 +68,69 @@ class VolViewPage extends Page { ); } + get volumeCards() { + return $$('.volume-card'); + } + + /** Slice counts of the volume cards, ascending. Each label carries "[N]". */ + async getVolumeCardSliceCounts() { + const cards = [...(await this.volumeCards)]; + const labels = await Promise.all(cards.map((card) => card.getText())); + return labels + .map((label) => Number(label.match(/\[(\d+)\]/)?.[1])) + .filter(Number.isFinite) + .sort((a, b) => a - b); + } + + async waitForVolumeCardSliceCounts(expected: number[]) { + await browser.waitUntil( + async () => { + const counts = await this.getVolumeCardSliceCounts(); + return ( + counts.length === expected.length && + counts.every((count, index) => count === expected[index]) + ); + }, + { + timeoutMsg: `expected volume cards holding ${expected.join( + ', ' + )} slices`, + } + ); + } + + /** + * Deletes the volume of the card at `index` of `getVolumeCardSliceCounts`, + * which orders by slice count rather than by the order the cards render in. + */ + async deleteVolumeCard(index: number) { + const counts = await this.getVolumeCardSliceCounts(); + const cards = [...(await this.volumeCards)]; + const labelled = await Promise.all( + cards.map(async (card) => ({ + card, + count: Number((await card.getText()).match(/\[(\d+)\]/)?.[1]), + })) + ); + const target = labelled.find(({ count }) => count === counts[index]); + if (!target) throw new Error(`no volume card holding ${counts[index]}`); + + const menu = target.card.$('button[data-testid="dataset-menu-button"]'); + await menu.waitForClickable(); + await menu.click(); + + const remove = await browser.waitUntil( + async () => { + const items = [...(await $$('.v-overlay-container .v-list-item'))]; + const texts = await Promise.all(items.map((item) => item.getText())); + return items[texts.findIndex((text) => text.trim() === 'Delete')]; + }, + { timeoutMsg: 'expected a Delete item in the dataset menu' } + ); + await remove.waitForClickable(); + await remove.click(); + } + get notifications() { return $('#notifications'); } @@ -302,10 +365,8 @@ class VolViewPage extends Page { return $$('div[data-testid="layer-opacity-slider"]'); } - async getVolumeRenderingSection() { - const pwfEditor = await $('div.pwf-editor'); - const exists = await pwfEditor.isExisting(); - return exists ? pwfEditor : null; + getVolumeRenderingSection() { + return $('div.pwf-editor'); } async getView3D() { diff --git a/tests/specs/annotationTestUtils.ts b/tests/specs/annotationTestUtils.ts index 0e16c44cf..678e7a60d 100644 --- a/tests/specs/annotationTestUtils.ts +++ b/tests/specs/annotationTestUtils.ts @@ -41,29 +41,26 @@ export const pressAtPointer = () => hoveringMouse().down().up().perform(true); export const rightPressAtPointer = () => hoveringMouse().down({ button: 2 }).up({ button: 2 }).perform(true); -/** - * Loads the minimal DICOM or a generated fixture and returns the axial view - * with the center of its canvas in page coordinates. - */ -export const setupTest = async (fileName?: string) => { - if (fileName) await openVolViewPage(fileName); - else await openUrls([MINIMAL_DICOM]); - - const views2D = await AppPage.getViews2D(); - const axialView = views2D[0]; - const canvas = await axialView.$('canvas'); +export const canvasCenter = async (view: ChainablePromiseElement) => { + const canvas = view.$('canvas'); const [location, size] = await Promise.all([ canvas.getLocation(), canvas.getSize(), ]); - return { - axialView, centerX: location.x + size.width / 2, centerY: location.y + size.height / 2, }; }; +/** Loads a dataset and returns its axial view and canvas center. */ +export const setupTest = async (fileName?: string) => { + if (fileName) await openVolViewPage(fileName); + else await openUrls([MINIMAL_DICOM]); + const axialView = (await AppPage.getViews2D())[0]; + return { axialView, ...(await canvasCenter(axialView)) }; +}; + export const drawSquare = async (cx: number, cy: number, half: number) => { await clickAt(cx - half, cy - half); await clickAt(cx + half, cy - half); diff --git a/tests/specs/crosshairs-multi-image.e2e.ts b/tests/specs/crosshairs-multi-image.e2e.ts index b7371720f..ebbec7007 100644 --- a/tests/specs/crosshairs-multi-image.e2e.ts +++ b/tests/specs/crosshairs-multi-image.e2e.ts @@ -1,5 +1,7 @@ -import { MRA_HEAD_NECK_DATASET, PROSTATEX_DATASET } from '../datasets'; -import { openUrls } from './utils'; +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { makeTempDir, writeManifestToFile } from './utils'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; import { volViewPage } from '../pageobjects/volview.page'; const IMAGE_DRAG_MEDIA_TYPE = 'application/x-volview-image-id'; @@ -8,6 +10,44 @@ const IMAGE_DRAG_MEDIA_TYPE = 'application/x-volview-image-id'; const FIRST_OTHER_SLOT = 2; const SECOND_OTHER_SLOT = 1; +const openImages = async () => { + const directory = makeTempDir('crosshairs-images'); + const studyUid = newUid(); + // Separate image bounds make an incorrectly shared crosshair clamp the other + // volume to an edge slice instead of leaving it at the middle slice. + const resources = [0, 100].flatMap((origin, series) => { + const seriesUid = newUid(); + return Array.from({ length: 16 }, (_, slice) => { + const filename = `${series}-${slice}.dcm`; + writeFileSync( + join(directory, filename), + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + instanceNumber: slice + 1, + seriesNumber: series + 1, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [origin, origin, origin + slice], + rows: 16, + cols: 16, + pixelValue: 20 + slice * 10, + }) + ); + return { url: `/tmp/crosshairs-images/${filename}` }; + }); + }); + await writeManifestToFile({ resources }, 'crosshairs-images.json'); + await volViewPage.open('?urls=[tmp/crosshairs-images.json]'); + await volViewPage.waitForViews(); + await volViewPage.waitForVolumeCardSliceCounts([16, 16]); +}; + +const expectSlotImage = (index: number, name: string) => + expect( + $$('.grid-item')[index].$('.view-annotations .annotation-cell') + ).toHaveText(name); + /** * Dispatches a real dragstart on a volume card so the app stamps the imageID * into the dataTransfer, then synthesizes the drop on a layout slot. @@ -74,15 +114,7 @@ const dragInSlot = async (index: number, dx: number, dy: number) => { describe('Crosshairs with two base images', () => { it('only slices the views showing the image it was dragged in', async () => { - await openUrls([PROSTATEX_DATASET, MRA_HEAD_NECK_DATASET]); - await volViewPage.waitForViews(); - await browser.waitUntil( - async () => (await $$('.volume-card').length) >= 2, - { - timeout: 30000, - timeoutMsg: 'Expected both volume cards to appear', - } - ); + await openImages(); await browser.waitUntil(async () => (await $$('.grid-item').length) === 4, { timeout: 10000, timeoutMsg: 'Expected the Four Up layout (4 slots)', @@ -96,18 +128,25 @@ describe('Crosshairs with two base images', () => { ) ); expect(otherCard).toBeGreaterThanOrEqual(0); + const otherName = await $$('.volume-card') + [otherCard].$('.series-desc') + .getText(); + const activeName = await $$('.grid-item')[0] + .$('.view-annotations .annotation-cell') + .getText(); + expect(activeName).not.toBe(''); + expect(otherName).not.toBe(activeName); + await expectSlotImage(SECOND_OTHER_SLOT, activeName); expect(await dropCardOnSlot(otherCard, FIRST_OTHER_SLOT)).toBe(true); - await browser.waitUntil( - async () => (await getSlices())[FIRST_OTHER_SLOT] != null, - { timeout: 15000, timeoutMsg: 'Expected the dropped image to render' } - ); + await expectSlotImage(FIRST_OTHER_SLOT, otherName); const crosshairsButton = await $('button span i[class~=mdi-crosshairs]'); await crosshairsButton.waitForClickable(); await crosshairsButton.click(); const before = await getSlices(); + expect(before.slice(0, 3)).toEqual([9, 9, 9]); // Drag the crosshair well off centre in a view of the other image. await dragInSlot(0, 60, 40); @@ -124,10 +163,10 @@ describe('Crosshairs with two base images', () => { // not a crosshair interaction, so the slot already showing it must not be // re-sliced to wherever the crosshair sits in the other image. expect(await dropCardOnSlot(otherCard, SECOND_OTHER_SLOT)).toBe(true); - await browser.waitUntil( - async () => (await getSlices())[SECOND_OTHER_SLOT] !== afterDrag[1], - { timeout: 15000, timeoutMsg: 'Expected the second slot to remount' } - ); + await expectSlotImage(SECOND_OTHER_SLOT, otherName); + await expect( + $$('.grid-item')[SECOND_OTHER_SLOT].$('.slice-label') + ).toHaveText('Slice: 9/16'); const afterRemount = await getSlices(); expect(afterRemount[FIRST_OTHER_SLOT]).toBe(before[FIRST_OTHER_SLOT]); diff --git a/tests/specs/dicom-archive-state.e2e.ts b/tests/specs/dicom-archive-state.e2e.ts new file mode 100644 index 000000000..38ef69e8c --- /dev/null +++ b/tests/specs/dicom-archive-state.e2e.ts @@ -0,0 +1,107 @@ +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import JSZip from 'jszip'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { volViewPage } from '../pageobjects/volview.page'; +import { + buildSyntheticDicom, + buildSyntheticCineDicom, + newUid, +} from './syntheticDicom'; +import { canvasCenter, clickAt } from './annotationTestUtils'; +import { advanceCineFrame, waitForFrame } from './cineTestUtils'; +import { openSegmentShapes } from './segmentationTestUtils'; +import { + dropFiles, + openVolViewPage, + SESSION_SAVE_TIMEOUT, + waitForFileExists, +} from './utils'; + +describe('DICOM archive state and independent clips', () => { + it('restores the ruler saved with two series from one archive', async () => { + const archive = new JSZip(); + const studyUid = newUid(); + for (const count of [2, 3]) { + const seriesUid = newUid(); + for (let index = 0; index < count; index++) { + archive.file( + count + '-slice-' + index + '.dcm', + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + instanceNumber: index + 1, + seriesNumber: count, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, index], + rows: 32, + cols: 32, + pixelValue: 100 + index, + }) + ); + } + } + const name = 'two-series-with-state.zip'; + writeFileSync( + join(TEMP_DIR, name), + await archive.generateAsync({ type: 'nodebuffer' }) + ); + await volViewPage.open('?urls=[tmp/' + name + ']'); + await volViewPage.waitForVolumeCardSliceCounts([2, 3]); + await volViewPage.waitForViews(); + + const view = (await volViewPage.getViews2D())[0]; + const { centerX: x, centerY: y } = await canvasCenter(view); + await volViewPage.selectTool('mdi-ruler'); + await clickAt(x - 30, y); + await clickAt(x + 30, y); + await openSegmentShapes(); + const rulerCount = () => + $$('[data-testid="segment-shape-row"] i.mdi-ruler').length; + await browser.waitUntil(async () => (await rulerCount()) === 1, { + timeoutMsg: 'Expected the placed ruler in the measurements list', + }); + + const saved = await volViewPage.saveSession(); + await waitForFileExists(join(TEMP_DIR, saved), SESSION_SAVE_TIMEOUT); + await openVolViewPage(saved); + await openSegmentShapes(); + await browser.waitUntil(async () => (await rulerCount()) === 1, { + timeoutMsg: 'Expected the restored archive dataset to retain its ruler', + }); + await $('button[data-testid="module-tab-Data"]').click(); + await volViewPage.waitForVolumeCardSliceCounts([2, 3]); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); + + it('plays two equal-shaped ultrasound clips sharing a series', async () => { + const studyUid = newUid(); + const seriesUid = newUid(); + const files = ['first-clip.dcm', 'second-clip.dcm'].map((name) => { + const file = join(TEMP_DIR, name); + writeFileSync( + file, + buildSyntheticCineDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + rows: 32, + cols: 32, + numberOfFrames: 3, + }) + ); + return file; + }); + await volViewPage.open(); + await $('#app-container').waitForDisplayed(); + await dropFiles(files); + await volViewPage.waitForVolumeCardSliceCounts([3, 3]); + await $('.play-controls').waitForDisplayed(); + await waitForFrame(1); + await volViewPage.focusFirst2DView(); + await advanceCineFrame(); + await waitForFrame(2); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); +}); diff --git a/tests/specs/dicom-dimension-mismatch.e2e.ts b/tests/specs/dicom-dimension-mismatch.e2e.ts index 016a503b8..0c6b40ca8 100644 --- a/tests/specs/dicom-dimension-mismatch.e2e.ts +++ b/tests/specs/dicom-dimension-mismatch.e2e.ts @@ -1,8 +1,7 @@ -// A DICOM series whose instances disagree on Rows/Columns still groups into a -// single volume, and that volume's buffer is sized from the first instance. -// An instance that does not fit has to be rejected with a message naming it, -// whether it is too big for its slot or too small to fill one, and the rest of -// the series has to reach a usable state anyway. +// A DICOM series whose instances disagree on Rows/Columns is two datasets, not +// one volume with a rejected slice: the collection planner splits on pixel +// geometry, so the scout lands in its own volume whether it arrives first or +// last, and neither volume reports an error. import * as path from 'path'; import * as fs from 'fs'; import { volViewPage } from '../pageobjects/volview.page'; @@ -11,20 +10,15 @@ import { makeTempDir, writeManifestToFile } from './utils'; const IMAGE_ORIENTATION_PATIENT = [1, 0, 0, 0, 1, 0] as const; const SLICE_COUNT = 5; -const MIDDLE_SLICE = 2; -const SMALL_ROWS = 4; -const SMALL_COLS = 6; -const BIG_ROWS = 8; -const BIG_COLS = 10; - -type Size = { rows: number; cols: number }; +const SERIES_ROWS = 4; +const SERIES_COLS = 6; +const SCOUT_ROWS = 8; +const SCOUT_COLS = 10; async function writeSeries( dirName: string, - series: Size, - outlier: Size, - outlierSlice: number, + scoutSlice: number, manifestName: string ) { const dir = makeTempDir(dirName); @@ -32,175 +26,81 @@ async function writeSeries( const studyUid = newUid(); const seriesUid = newUid(); const resources = []; - let outlierSopUid = ''; for (let i = 0; i < SLICE_COUNT; i++) { - const mismatched = i === outlierSlice; - const sopUid = newUid(); - if (mismatched) outlierSopUid = sopUid; - - const { rows, cols } = mismatched ? outlier : series; + const scout = i === scoutSlice; const filename = `slice-${i}.dcm`; fs.writeFileSync( path.join(dir, filename), buildSyntheticDicom({ studyUid, seriesUid, - sopUid, + sopUid: newUid(), instanceNumber: i + 1, imageOrientationPatient: IMAGE_ORIENTATION_PATIENT, imagePositionPatient: [0, 0, i], - rows, - cols, + rows: scout ? SCOUT_ROWS : SERIES_ROWS, + cols: scout ? SCOUT_COLS : SERIES_COLS, }) ); resources.push({ url: `tmp/${dirName}/${filename}`, name: filename }); } await writeManifestToFile({ resources }, manifestName); - - return outlierSopUid; } -// The slice count in the "Slice: n/total" overlay of the first 2D view. -async function getRenderedSliceCount() { - return browser.execute((selector: string) => { - const view = document.querySelector(selector); - const match = view?.textContent?.match(/Slice:\s*\d+\s*\/\s*(\d+)/); - return match ? parseInt(match[1], 10) : null; - }, 'div[data-testid~="vtk-two-view"]'); -} - -// A rejected chunk is terminal, so the views stop advertising progress even -// though part of the series never arrived. -async function waitForSeriesToSettle() { - await volViewPage.waitForViews(); +async function waitForVolumeCards(count: number) { await browser.waitUntil( - async () => (await getRenderedSliceCount()) === SLICE_COUNT, + async () => (await $$('.volume-card').length) === count, { - timeout: 30000, - timeoutMsg: `expected the 2D view to show a ${SLICE_COUNT} slice volume`, + timeoutMsg: `expected exactly ${count} volume cards`, } ); - await browser.waitUntil( - async () => (await $$('.loading-indicator').length) === 0, - { - timeout: 30000, - timeoutMsg: 'expected the views to stop showing a loading indicator', - } - ); -} - -async function readErrorDetails() { - await volViewPage.notifications.click(); - - const errorPanel = $('.message-center .v-expansion-panel-title'); - await errorPanel.waitForClickable(); - await errorPanel.click(); - - const details = $('.message-center pre.details'); - await details.waitForDisplayed(); - // The panel animates open, so the text arrives a frame after the element. - await browser.waitUntil(async () => (await details.getText()).length > 0, { - timeout: 5000, - timeoutMsg: 'expected the error details to render', - }); - return details.getText(); } -async function loadAndReadRejection(manifestName: string) { +async function loadSplitSeries(dirName: string, scoutSlice: number) { + const manifestName = `${dirName}-${Date.now()}.json`; + await writeSeries(dirName, scoutSlice, manifestName); await volViewPage.open(`?urls=[tmp/${manifestName}]`); - await volViewPage.waitForNotification(); - await waitForSeriesToSettle(); - const errorCount = await volViewPage.getNotificationsCount(); - const text = await readErrorDetails(); - return { text, errorCount }; + await volViewPage.waitForViews(); + await waitForVolumeCards(2); } -describe('DICOM series with an instance of a different size', () => { - it('names the offending file when it overruns its slot', async () => { - const manifestName = `dimension-mismatch-big-${Date.now()}.json`; - const outlierSopUid = await writeSeries( - 'dimension-mismatch-big', - { rows: SMALL_ROWS, cols: SMALL_COLS }, - { rows: BIG_ROWS, cols: BIG_COLS }, - MIDDLE_SLICE, - manifestName - ); +describe('DICOM series with instances of two pixel geometries', () => { + it('splits the scout out when it arrives first', async () => { + await loadSplitSeries('geometry-split-first', 0); - const { text, errorCount } = await loadAndReadRejection(manifestName); + await volViewPage.waitForVolumeCardSliceCounts([1, 4]); - expect(text).toContain(outlierSopUid); - expect(text).toContain(`${BIG_COLS}x${BIG_ROWS}x1`); - expect(text).toContain(`${SMALL_COLS}x${SMALL_ROWS}x1`); - expect(text).toContain('Rows, Columns, and SamplesPerPixel'); - - // Only the instance that does not fit is rejected; the rest of the series - // still loads, so there is exactly one error to report. - expect(errorCount).toBe(1); + // Splitting is not a failure, so nothing is reported. + expect(await volViewPage.getNotificationsCount()).toBe(0); }); - // An under-sized instance fits inside its slot, so the write itself cannot - // detect it; only the metadata comparison can. - it('names the offending file when it underfills its slot', async () => { - const manifestName = `dimension-mismatch-small-${Date.now()}.json`; - const outlierSopUid = await writeSeries( - 'dimension-mismatch-small', - { rows: BIG_ROWS, cols: BIG_COLS }, - { rows: SMALL_ROWS, cols: SMALL_COLS }, - MIDDLE_SLICE, - manifestName - ); + it('splits the scout out when it arrives last', async () => { + await loadSplitSeries('geometry-split-last', SLICE_COUNT - 1); - const { text, errorCount } = await loadAndReadRejection(manifestName); + await volViewPage.waitForVolumeCardSliceCounts([1, 4]); - expect(text).toContain(outlierSopUid); - expect(text).toContain(`${SMALL_COLS}x${SMALL_ROWS}x1`); - expect(text).toContain(`${BIG_COLS}x${BIG_ROWS}x1`); - expect(errorCount).toBe(1); + expect(await volViewPage.getNotificationsCount()).toBe(0); }); - // Both axes differing would still be caught if either half of the comparison - // were dropped; a single differing axis pins down both halves. - it('rejects an instance that differs on rows alone', async () => { - const manifestName = `dimension-mismatch-rows-${Date.now()}.json`; - const outlierSopUid = await writeSeries( - 'dimension-mismatch-rows', - { rows: SMALL_ROWS, cols: SMALL_COLS }, - { rows: BIG_ROWS, cols: SMALL_COLS }, - MIDDLE_SLICE, - manifestName + it('thumbnails both volumes from their own slices', async () => { + await loadSplitSeries('geometry-split-thumbnails', 0); + + await browser.waitUntil( + async () => { + const sources = await $$('.volume-card img.v-img__img').map( + (thumbnail) => thumbnail.getAttribute('src') + ); + return ( + sources.length === 2 && + sources.every((src) => !!src && src.startsWith('data:image/')) + ); + }, + { + timeoutMsg: + 'expected both volume cards to render a data-URL thumbnail instead of the modality fallback', + } ); - - const { text, errorCount } = await loadAndReadRejection(manifestName); - - expect(text).toContain(outlierSopUid); - expect(text).toContain(`${SMALL_COLS}x${BIG_ROWS}x1`); - expect(text).toContain(`${SMALL_COLS}x${SMALL_ROWS}x1`); - expect(errorCount).toBe(1); - }); - - // The volume is sized from the first instance, so an outlier there rejects - // every other chunk, one error apiece. Collapsing them into a single - // notification belongs with the error-boundary work in issue 911. - it('rejects the rest of the series when the first instance is the outlier', async () => { - const manifestName = `dimension-mismatch-first-${Date.now()}.json`; - const outlierSopUid = await writeSeries( - 'dimension-mismatch-first', - { rows: SMALL_ROWS, cols: SMALL_COLS }, - { rows: BIG_ROWS, cols: BIG_COLS }, - 0, - manifestName - ); - - const { text, errorCount } = await loadAndReadRejection(manifestName); - - expect(errorCount).toBe(SLICE_COUNT - 1); - // The first instance defines the volume, so it is the other four that are - // named as not fitting. - expect(text).not.toContain(outlierSopUid); - expect(text).toContain('does not fit the volume it belongs to'); - expect(text).toContain(`${SMALL_COLS}x${SMALL_ROWS}x1`); - expect(text).toContain(`${BIG_COLS}x${BIG_ROWS}x1`); }); }); diff --git a/tests/specs/dicom-frame-reconstruction.e2e.ts b/tests/specs/dicom-frame-reconstruction.e2e.ts new file mode 100644 index 000000000..349705f7c --- /dev/null +++ b/tests/specs/dicom-frame-reconstruction.e2e.ts @@ -0,0 +1,137 @@ +import { createHash } from 'node:crypto'; +import { writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { openDicomConsumer } from '../dicomConsumer'; +import { enhancedFixtureBytes } from '../fixtures/dicom-consumer/enhancedFixtures'; +import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; +import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { volViewPage } from '../pageobjects/volview.page'; + +const frames = { + uneven: enhancedFixtureBytes({ + pixelValues: [20, 120, 220], + positions: [ + [10, 20, 30], + [10, 20, 31], + [10, 20, 33], + ], + }), + temporal: enhancedFixtureBytes({ + pixelValues: [20, 120], + sharedPosition: [10, 20, 30], + temporalPositions: [1, 2], + }), + varying: enhancedFixtureBytes({ + pixelValues: [2, 2], + transforms: [ + [1, 0], + [2, 0], + ], + }), + uniform: enhancedFixtureBytes({ + pixelValues: [2, 2], + transforms: [ + [2, 0], + [2, 0], + ], + }), +}; + +const hashFrames = (values: number[]) => + createHash('sha256') + .update( + Buffer.from( + Float64Array.from(values.flatMap((value) => Array(16).fill(value))) + .buffer + ) + ) + .digest('hex'); +const irregular = 'Cannot allocate irregular DICOM geometry: '; +const scenarios = [ + { + name: 'uneven', + policy: 'preserve-order', + values: [20, 120, 220], + reconstruction: 'irregular', + }, + { + name: 'uneven', + policy: 'reject', + error: `${irregular}uneven-slice-spacing`, + }, + { + name: 'temporal', + policy: 'reject', + error: `${irregular}unreadable-geometry`, + }, + { + name: 'varying', + error: + 'Cannot load DICOM frames with differing modality rescale: the decoder applies one transform to the entire instance', + }, + { + name: 'varying', + decoder: 'custom', + values: [2, 4], + reconstruction: 'regular', + }, + { name: 'uniform', values: [4, 4], reconstruction: 'regular' }, +]; + +describe('Encoded multiframe reconstruction contracts', () => { + let fixture: Awaited>; + before(async () => { + fixture = await startDicomConsumerFixtures(fixtureBytes(), { + kinds: ['corpus'], + fixtures: frames, + }); + }); + after(async () => fixture?.close()); + + for (const scenario of scenarios) { + for (const source of ['file', 'http']) { + it(`handles ${scenario.name} frames from ${source} with ${scenario.decoder ?? 'default'} decoding and ${scenario.policy ?? 'default'} geometry policy`, async () => { + const params = new URLSearchParams({ name: scenario.name, source }); + if (scenario.policy) params.set('policy', scenario.policy); + if (scenario.decoder) params.set('decoder', scenario.decoder); + await openDicomConsumer( + `${fixture.urls.corpus}?${params}`, + scenario.error + ); + if (scenario.values) { + await expect($('#pixel-hash')).toHaveText( + hashFrames(scenario.values) + ); + await expect($('#reconstruction')).toHaveText( + scenario.reconstruction + ); + } + }); + } + } +}); + +describe('Multiframe reconstruction notices', () => { + for (const name of ['uneven', 'temporal'] as const) { + it(`shows the user why ${name} frames have approximate spatial placement`, async () => { + const file = `enhanced-${name}.dcm`; + writeFileSync(resolve(TEMP_DIR, file), frames[name]); + await volViewPage.open(`?urls=[tmp/${file}]`); + await volViewPage.waitForVolumeCardSliceCounts([ + name === 'uneven' ? 3 : 2, + ]); + await volViewPage.waitForViews(); + expect(await volViewPage.getNotificationsCount()).toBe(1); + await volViewPage.notifications.click(); + const warning = $('.message-center .warn-message'); + await expect(warning).toHaveText( + expect.stringContaining('did not load as one sound volume') + ); + await warning.click(); + await expect($('.message-center .details')).toHaveText( + expect.stringContaining('positions and measurements') + ); + }); + } +}); diff --git a/tests/specs/dicom-import-regressions.e2e.ts b/tests/specs/dicom-import-regressions.e2e.ts new file mode 100644 index 000000000..574a493bc --- /dev/null +++ b/tests/specs/dicom-import-regressions.e2e.ts @@ -0,0 +1,198 @@ +import { PNG } from 'pngjs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { + buildSyntheticDicom, + newUid, + rawElement, + sequenceItem, + toImplicitVr, + undefinedLengthUnknown, +} from './syntheticDicom'; + +const AXIAL = [1, 0, 0, 0, 1, 0] as const; + +// Exercise the local File import path, including metadata scanning and pixel +// decoding, through the same drop event a user produces. +async function dropFiles(files: Uint8Array[]) { + await volViewPage.open(); + await $('#app-container').waitForExist(); + await browser.execute( + (encodedFiles) => { + const transfer = new DataTransfer(); + encodedFiles.forEach((encoded, i) => { + const bytes = Uint8Array.from(atob(encoded), (char) => + char.charCodeAt(0) + ); + transfer.items.add(new File([bytes], `slice-${i}.dcm`)); + }); + const event = new Event('drop', { bubbles: true, cancelable: true }); + // Synthetic items have no filesystem entries, so supply the files list. + Object.defineProperty(event, 'dataTransfer', { + value: { items: null, files: transfer.files }, + }); + document.querySelector('#app-container')!.dispatchEvent(event); + }, + files.map((bytes) => Buffer.from(bytes).toString('base64')) + ); +} + +async function probeCenter(view: WebdriverIO.Element, expected: number) { + const canvas = view.$('canvas'); + await canvas.moveTo(); + await canvas.moveTo({ xOffset: 1, yOffset: 0 }); + await expect( + $('.probe-value-display .d-flex:first-child .text-right') + ).toHaveText(String(expected)); +} + +async function openSpacingDetails() { + await $('.volume-card [data-testid="dataset-menu-button"]').click(); + const item = $('[data-testid="dataset-menu-spacing-item"]'); + await item.waitForStable(); + await item.waitForClickable(); + await item.click(); + await $('[data-testid="image-spacing-details"]').waitForDisplayed(); +} + +async function axialView(sliceCount: number) { + return browser.waitUntil(async () => { + const views = await $$('[data-testid~="vtk-two-view"]'); + for (const view of views) { + const label = await view.$('.slice-label').getText(); + if (label.endsWith(`/${sliceCount}`)) return view; + } + return undefined; + }); +} + +async function selectSlice( + view: WebdriverIO.Element, + index: number, + count: number +) { + const slider = view + .$('./ancestor::div[contains(@class, "vtk-container-wrapper")]') + .$('.slice-slider'); + const location = await slider.getLocation(); + const size = await slider.getSize(); + const handleSize = await slider.$('.slice-slider-handle').getSize(); + const y = + location.y + + handleSize.height / 2 + + (size.height - handleSize.height) * (1 - index / (count - 1)); + await browser + .action('pointer') + .move({ x: Math.round(location.x + size.width / 2), y: Math.round(y) }) + .down() + .up() + .perform(); + await expect(view.$('.slice-label')).toHaveText( + `Slice: ${index + 1}/${count}` + ); +} + +describe('Local DICOM import regressions', () => { + it('keeps the planned 5 mm spacing with slightly different slice orientations', async () => { + const studyUid = newUid(); + const seriesUid = newUid(); + const sopPrefix = newUid(); + const files = Array.from({ length: 121 }, (_, i) => + buildSyntheticDicom({ + studyUid, + seriesUid, + // The axial representative sorts before the tilted spatial first slice. + sopUid: `${sopPrefix}.${i === 1 ? '1' : `2.${i}`}`, + instanceNumber: i + 1, + imageOrientationPatient: + i === 0 ? [Math.cos(0.0002), 0, Math.sin(0.0002), 0, 1, 0] : AXIAL, + imagePositionPatient: [0, 0, i * 5], + rows: 4, + cols: 4, + pixelValue: i, + }) + ); + + await dropFiles(files); + await volViewPage.waitForVolumeCardSliceCounts([121]); + await volViewPage.waitForViews(); + await volViewPage.waitForLoadingIndicator( + $('[data-testid~="vtk-two-view"]') + ); + await openSpacingDetails(); + await expect($('[data-testid="spacing-axis-Z"]')).toHaveText( + expect.stringContaining('5 mm') + ); + await $('[data-testid="spacing-details-close"]').click(); + const view = await axialView(121); + for (const index of [0, 60, 120]) { + await selectSlice(view, index, 121); + await probeCenter(view, index); + } + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); + + it('loads pixels from a file containing an undefined-length private UN sequence', async () => { + const content = toImplicitVr( + rawElement(0x0043, 0x1030, 'LO', new TextEncoder().encode('VALUE ')) + ); + await dropFiles([ + buildSyntheticDicom({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + instanceNumber: 1, + imageOrientationPatient: AXIAL, + imagePositionPatient: [0, 0, 0], + rows: 4, + cols: 4, + pixelValue: 123, + extraElements: [ + rawElement(0x0043, 0x0010, 'LO', new TextEncoder().encode('TEST')), + undefinedLengthUnknown(0x0043, 0x1029, sequenceItem(content)), + ], + }), + ]); + + await volViewPage.waitForVolumeCardSliceCounts([1]); + await volViewPage.waitForViews(); + await volViewPage.waitForLoadingIndicator( + $('[data-testid~="vtk-two-view"]') + ); + await probeCenter(await axialView(1), 123); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); + + it('renders green and blue content in a color DICOM thumbnail without red samples', async () => { + await dropFiles([ + buildSyntheticDicom({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + sopClassUid: '1.2.840.10008.5.1.4.1.1.7', + modality: 'OT', + instanceNumber: 1, + imageOrientationPatient: AXIAL, + imagePositionPatient: null, + rows: 4, + cols: 4, + bitsAllocated: 8, + rgbPixels: Array.from({ length: 4 }, () => [ + 0, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, + ]).flat(), + }), + ]); + await volViewPage.waitForVolumeCardSliceCounts([1]); + const thumbnail = $('.volume-card .thumbnail-container img'); + await expect(thumbnail).toHaveAttribute( + 'src', + expect.stringMatching(/^data:image\/png;base64,/) + ); + const source = await thumbnail.getAttribute('src'); + if (!source) throw new Error('Expected a visible PNG thumbnail'); + const pixels = PNG.sync.read(Buffer.from(source.split(',')[1], 'base64')); + expect(Array.from(pixels.data.slice(0, 12))).toEqual([ + 0, 0, 0, 255, 255, 255, 255, 255, 50, 50, 50, 255, + ]); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); +}); diff --git a/tests/specs/dicom-japanese-name.e2e.ts b/tests/specs/dicom-japanese-name.e2e.ts new file mode 100644 index 000000000..22a88816d --- /dev/null +++ b/tests/specs/dicom-japanese-name.e2e.ts @@ -0,0 +1,113 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import JSZip from 'jszip'; +import { cleanuptotal } from 'wdio-cleanuptotal-service'; + +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { volViewPage } from '../pageobjects/volview.page'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; +import { writeManifestToFile } from './utils'; + +const ascii = (text: string) => Array.from(text, (c) => c.charCodeAt(0)); + +// ESC $ B designates JIS X 0208, ESC ( B returns to ASCII, as ISO 2022 IR 87 +// requires around every run of ideographic or phonetic characters. +const jisX0208 = (...codes: number[]) => [ + 0x1b, + 0x24, + 0x42, + ...codes, + 0x1b, + 0x28, + 0x42, +]; + +const JAPANESE_NAME = 'Yamada^Tarou=山田^太郎=やまだ^たろう'; +const JAPANESE_NAME_BYTES = new Uint8Array([ + ...ascii('Yamada^Tarou='), + ...jisX0208(0x3b, 0x33, 0x45, 0x44), + ...ascii('^'), + ...jisX0208(0x42, 0x40, 0x4f, 0x3a), + ...ascii('='), + ...jisX0208(0x24, 0x64, 0x24, 0x5e, 0x24, 0x40), + ...ascii('^'), + ...jisX0208(0x24, 0x3f, 0x24, 0x6d, 0x24, 0x26), +]); + +const japaneseNameDicom = () => + buildSyntheticDicom({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + instanceNumber: 1, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, 0], + specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 87', + patientNameBytes: JAPANESE_NAME_BYTES, + }); + +const writeTempFile = (fileName: string, contents: Uint8Array | Buffer) => { + const filePath = path.join(TEMP_DIR, fileName); + fs.writeFileSync(filePath, contents); + cleanuptotal.addCleanup(async () => { + if (fs.existsSync(filePath)) fs.unlinkSync(filePath); + }); + return fileName; +}; + +const patientHeaderNames = async () => { + const headers = await $$('.patient-header-name'); + const names: string[] = []; + for (const header of headers) { + names.push(await header.getText()); + } + return names; +}; + +const waitForPatientName = async (expected: string) => { + let seen: string[] = []; + await browser.waitUntil( + async () => { + seen = await patientHeaderNames(); + return seen.includes(expected); + }, + { + timeoutMsg: `expected a patient named ${expected}`, + } + ); + expect(seen).toContain(expected); +}; + +describe('DICOM patient name in a non-default character set', () => { + it('decodes an ISO 2022 IR 87 name from a streamed DICOM', async () => { + const stamp = Date.now(); + const fileName = writeTempFile( + `japanese-name-${stamp}.dcm`, + japaneseNameDicom() + ); + const manifestName = `japanese-name-${stamp}.json`; + await writeManifestToFile( + { resources: [{ url: `/tmp/${fileName}`, name: fileName }] }, + manifestName + ); + + await volViewPage.open(`?urls=[tmp/${manifestName}]`); + await volViewPage.waitForViews(); + + await waitForPatientName(JAPANESE_NAME); + }); + + it('decodes an ISO 2022 IR 87 name from a DICOM inside an archive', async () => { + const zip = new JSZip(); + zip.file('japanese-name.dcm', japaneseNameDicom()); + const zipName = writeTempFile( + `japanese-name-${Date.now()}.zip`, + await zip.generateAsync({ type: 'nodebuffer' }) + ); + + await volViewPage.open(`?urls=[tmp/${zipName}]`); + await volViewPage.waitForViews(); + + await waitForPatientName(JAPANESE_NAME); + }); +}); diff --git a/tests/specs/dicom-modality-rescale.e2e.ts b/tests/specs/dicom-modality-rescale.e2e.ts index fbc261b43..7005a4ecb 100644 --- a/tests/specs/dicom-modality-rescale.e2e.ts +++ b/tests/specs/dicom-modality-rescale.e2e.ts @@ -49,16 +49,16 @@ async function writeRescaledSeries() { } describe('DICOM modality rescale', () => { - it('preserves the public DSC series Float64 output through volume loading', async () => { + it('keeps the public DSC series rescale to float32 precision through volume loading', async () => { const manifestName = await writeRescaledSeries(); await volViewPage.open(`?urls=[tmp/${manifestName}]`); await volViewPage.waitForViews(); const scalars = await waitForFirstCompleteCachedImageScalars(); expect(await volViewPage.getNotificationsCount()).toBe(0); - expect(scalars.type).toBe('Float64Array'); + expect(scalars.type).toBe('Float32Array'); const expected = STORED_VALUES.flatMap((stored) => - Array(ROWS * COLUMNS).fill(stored * PUBLIC_DSC_SLOPE) + Array(ROWS * COLUMNS).fill(Math.fround(stored * PUBLIC_DSC_SLOPE)) ); expect(scalars.values).toEqual(expected); }); diff --git a/tests/specs/dicom-native-parity.e2e.ts b/tests/specs/dicom-native-parity.e2e.ts new file mode 100644 index 000000000..4cc40b13a --- /dev/null +++ b/tests/specs/dicom-native-parity.e2e.ts @@ -0,0 +1,206 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import JSZip from 'jszip'; +import corpus from '../dicomVolumeCorpus.json'; +import composition from '../dicomCompositionCorpus.json'; +import { DATASET_CACHE } from '../downloadDatasets'; +import { openDicomConsumer } from '../dicomConsumer'; +import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; +import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { + EXPLICIT_BE, + EXPLICIT_LE, + IMPLICIT_LE, + nativePixelDicom, + type DataElement, + type NativePixelOptions, +} from '../nativePixelDicom'; + +const SOP_CLASSES = { + CT: '1.2.840.10008.5.1.4.1.1.2', + MR: '1.2.840.10008.5.1.4.1.1.4', + PT: '1.2.840.10008.5.1.4.1.1.128', + SC: '1.2.840.10008.5.1.4.1.1.7', + US: '1.2.840.10008.5.1.4.1.1.6.1', + USMultiframe: '1.2.840.10008.5.1.4.1.1.3.1', + XA: '1.2.840.10008.5.1.4.1.1.12.1', + NM: '1.2.840.10008.5.1.4.1.1.20', + DX: '1.2.840.10008.5.1.4.1.1.1.1', + CR: '1.2.840.10008.5.1.4.1.1.1', + EnhancedCT: '1.2.840.10008.5.1.4.1.1.2.1', + EnhancedMR: '1.2.840.10008.5.1.4.1.1.4.1', + OCT: '1.2.840.10008.5.1.4.1.1.77.1.5.4', +}; + +const us = (tag: number, value: number): DataElement => ({ + tag, + vr: 'US', + value: [value], +}); + +const overlay = [ + us(0x60000010, 5), + us(0x60000011, 3), + us(0x60000100, 16), + us(0x60000102, 12), +]; + +// Stored words span every bit pattern, high bits above Bits Stored included. +// The flag says whether the capability predicate must decode natively. +// prettier-ignore +const synthetic: Array<[string, boolean, NativePixelOptions]> = [ + ['u8', true, { bitsAllocated: 8 }], + ['s8', true, { bitsAllocated: 8, pixelRepresentation: 1 }], + ['u8-bs6', false, { bitsAllocated: 8, bitsStored: 6 }], + ['u16', true, {}], + ['s16', true, { pixelRepresentation: 1 }], + ['u16-bs12', true, { bitsStored: 12 }], + ['s16-bs12', true, { bitsStored: 12, pixelRepresentation: 1 }], + ['u16-bs1', true, { bitsStored: 1 }], + ['u32', true, { bitsAllocated: 32 }], + ['s32', true, { bitsAllocated: 32, pixelRepresentation: 1 }], + ['u32-bs24', false, { bitsAllocated: 32, bitsStored: 24 }], + ['implicit-u16-bs12', true, { transferSyntaxUid: IMPLICIT_LE, bitsStored: 12 }], + ['implicit-s16', true, { transferSyntaxUid: IMPLICIT_LE, pixelRepresentation: 1 }], + ['implicit-u8', true, { transferSyntaxUid: IMPLICIT_LE, bitsAllocated: 8 }], + ['be-u16-bs12', true, { transferSyntaxUid: EXPLICIT_BE, bitsStored: 12 }], + ['be-s16', true, { transferSyntaxUid: EXPLICIT_BE, pixelRepresentation: 1 }], + ['be-s16-bs12-frames', true, { transferSyntaxUid: EXPLICIT_BE, bitsStored: 12, pixelRepresentation: 1, frames: 3 }], + ['be-u8', false, { transferSyntaxUid: EXPLICIT_BE, bitsAllocated: 8 }], + ['be-u32', false, { transferSyntaxUid: EXPLICIT_BE, bitsAllocated: 32 }], + ['rgb', true, { samplesPerPixel: 3, bitsAllocated: 8, planarConfiguration: 0 }], + ['rgb-planar', true, { samplesPerPixel: 3, bitsAllocated: 8, planarConfiguration: 1 }], + ['rgb-planar-frames', true, { samplesPerPixel: 3, bitsAllocated: 8, planarConfiguration: 1, frames: 3 }], + ['implicit-rgb', true, { transferSyntaxUid: IMPLICIT_LE, samplesPerPixel: 3, bitsAllocated: 8 }], + ['rgb16', false, { samplesPerPixel: 3, bitsAllocated: 16 }], + ['ybr-full', false, { samplesPerPixel: 3, bitsAllocated: 8, photometric: 'YBR_FULL' }], + ['palette', false, { bitsAllocated: 8, photometric: 'PALETTE COLOR' }], + ['monochrome1', false, { photometric: 'MONOCHROME1', bitsStored: 12 }], + ['frames-u16', true, { frames: 4, bitsStored: 12, rescale: [1, -1024] }], + ['frames-u8', true, { frames: 5, bitsAllocated: 8 }], + ['high-bit-shifted', false, { bitsStored: 12, highBit: 14 }], + ['overlay', false, { bitsStored: 12, extra: overlay }], + ['padding', true, { bitsStored: 12, pixelRepresentation: 1, extra: [{ tag: 0x00280120, vr: 'SS', value: [-2000] }] }], + ['s16-ct-float32', true, { pixelRepresentation: 1, rescale: [1, -1024] }], + ['s32-fractional-float64', true, { bitsAllocated: 32, pixelRepresentation: 1, rescale: [0.5, 0.25] }], + ['ct-fractional', true, { bitsStored: 12, rescale: [0.5, -0.25] }], + ['ct-irrational', true, { pixelRepresentation: 1, rescale: [1.9413152, 0.1] }], + ['ct-zero-slope', true, { pixelRepresentation: 1, rescale: [0, 7] }], + ['enhanced-ct-uniform', true, { sopClassUid: SOP_CLASSES.EnhancedCT, frames: 3, frameRescales: [[2, -1], [2, -1], [2, -1]] }], + ['enhanced-mr-fractional', true, { sopClassUid: SOP_CLASSES.EnhancedMR, modality: 'MR', frames: 2, frameRescales: [[0.3, 1], [0.3, 1]] }], + ['enhanced-ct-differing', false, { sopClassUid: SOP_CLASSES.EnhancedCT, frames: 2, frameRescales: [[1, 0], [2, 0]] }], + ...Object.entries(SOP_CLASSES).flatMap( + ([name, sopClassUid]): Array<[string, boolean, NativePixelOptions]> => [ + [`${name}-integer-rescale`, true, { sopClassUid, bitsStored: 12, rescale: [3, -7] }], + [`${name}-fractional-rescale`, true, { sopClassUid, pixelRepresentation: 1, rescale: [0.7, 2.5] }], + ] + ), +]; + +const NATIVE_SYNTAXES = new Set([IMPLICIT_LE, EXPLICIT_LE, EXPLICIT_BE]); + +// Uncompressed public files decode natively, except the enhanced CT whose +// supplemental palette GDCM applies. +const corpusNative = (name: string, syntax: string) => + NATIVE_SYNTAXES.has(syntax) && !name.includes('eCT_Supplemental'); + +const cached = (names: string[]) => + names.map( + (name) => [name, readFileSync(resolve(DATASET_CACHE, name))] as const + ); + +const zipped = async (zip: string) => { + const archive = await JSZip.loadAsync( + readFileSync(resolve(DATASET_CACHE, zip)) + ); + const files = Object.values(archive.files).filter((file) => !file.dir); + return Promise.all( + files.map( + async (file) => + [`${zip}/${file.name}`, await file.async('uint8array')] as const + ) + ); +}; + +/** Pages per source, each small enough to finish quickly under load. */ +const PAGES = 16; + +type ParityResult = { + name: string; + plan?: string; + volume?: string; + gdcm?: string; + native?: string; + mismatch?: string | null; + rawMismatch?: string | null; + error?: string; +}; + +describe('Native frame decoding parity with GDCM', () => { + let fixture: Awaited>; + const expectedNative = new Map(); + let cases: string[] = []; + before(async () => { + const files = [ + ...synthetic.map( + ([name, , options], index) => + [name, nativePixelDicom({ ...options, instance: index + 1 })] as const + ), + ...cached(corpus.map(({ name }) => name)), + ...cached(composition.datasets.map(({ name }) => name)), + ...cached(['CT000085.dcm', 'minimal.dcm', 'retinal-oct.dcm']), + ...cached(['US-MONO2-8-8x-echo.dcm', 'US_multiframe_30frames.dcm']), + ...cached(['color3d_jpeg_baseline.dcm']), + ...(await zipped('prostate.zip')), + ...(await zipped('MRA-Head_and_Neck.zip')), + ]; + cases = files.map(([name]) => name); + synthetic.forEach(([name, native]) => expectedNative.set(name, native)); + corpus.forEach(({ name, transferSyntaxUID }) => + expectedNative.set(name, corpusNative(name, transferSyntaxUID)) + ); + // The two MR acquisitions are JPEG Lossless; the PET/CT files are not. + composition.datasets.forEach(({ name }) => + expectedNative.set(name, name.startsWith('PET-CT-')) + ); + files.forEach(([name]) => { + if (!expectedNative.has(name)) + expectedNative.set(name, !/US_multiframe|jpeg_baseline/.test(name)); + }); + fixture = await startDicomConsumerFixtures(fixtureBytes(), { + kinds: ['parity'], + fixtures: { + ...Object.fromEntries(files), + 'parity-cases.json': Buffer.from(JSON.stringify(cases)), + }, + }); + }); + after(async () => fixture?.close()); + + const pageSize = () => Math.ceil(cases.length / PAGES); + const pageOf = (page: number) => + cases.slice(page * pageSize(), (page + 1) * pageSize()); + + for (const source of ['file', 'http']) + for (let page = 0; page < PAGES; page += 1) + it(`writes the volume natively as GDCM does from ${source}, page ${page + 1}`, async () => { + const wanted = pageOf(page); + const from = page * pageSize(); + await openDicomConsumer( + `${fixture.urls.parity}?source=${source}&from=${from}&to=${from + wanted.length}` + ); + const results: ParityResult[] = JSON.parse( + await $('#report').getText() + ); + const unexpected = results.filter( + (result) => + result.error || + result.mismatch || + result.rawMismatch || + (result.plan === 'frames') !== expectedNative.get(result.name) || + (result.plan === 'frames' && result.native !== result.volume) + ); + expect(unexpected).toEqual([]); + expect(results.map(({ name }) => name)).toEqual(wanted); + }); +}); diff --git a/tests/specs/dicom-package.e2e.ts b/tests/specs/dicom-package.e2e.ts new file mode 100644 index 000000000..e6076d630 --- /dev/null +++ b/tests/specs/dicom-package.e2e.ts @@ -0,0 +1,59 @@ +import { PNG } from 'pngjs'; +import { resolve } from 'node:path'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; +import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { openDicomConsumer } from '../dicomConsumer'; + +// Both pages consume emitted JavaScript; metadata workers and GDCM assets are +// served from the same standalone output, without VolView startup. +describe('Independent DICOM package consumers', () => { + let fixture: Awaited>; + before(async () => { + fixture = await startDicomConsumerFixtures(fixtureBytes()); + }); + after(async () => fixture?.close()); + + it('rejects a failed worker startup and finishes queued and later reads', async () => { + await openDicomConsumer(`${fixture.urls.core}?scenario=worker-recovery`); + await expect($('#first-error')).toHaveText('DICOM decoder worker failed'); + await expect($('#queued-pixels')).toHaveText( + Array(16).fill('-10').join(', ') + ); + await expect($('#retry-pixels')).toHaveText( + Array(16).fill('-10').join(', ') + ); + }); + + for (const kind of ['core', 'vtk'] as const) { + for (const source of ['file', 'http']) { + it(`${kind} preserves metadata and calibrated pixels from ${source}`, async () => { + await openDicomConsumer(`${fixture.urls[kind]}?source=${source}`); + await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); + await expect($('#position')).toHaveText('10, 20, 30'); + await expect($('#pixel-spacing')).toHaveText('2, 3'); + if (kind === 'core') { + await expect($('#pixels')).toHaveText( + Array(16).fill('-10').join(', ') + ); + } else { + await expect($('#spacing')).toHaveText('3, 2, 4'); + await expect($('#origin')).toHaveText('10, 20, 30'); + await expect($('#range')).toHaveText('-10, -10'); + const screenshot = PNG.sync.read( + await $('#viewport').saveScreenshot( + resolve(TEMP_DIR, `dicom-${source}.png`) + ) + ); + const center = + ((screenshot.height >> 1) * screenshot.width + + (screenshot.width >> 1)) * + 4; + expect(screenshot.data[center]).toBeGreaterThan(110); + expect(screenshot.data[center]).toBeLessThan(145); + expect(screenshot.data[0]).toBe(0); + } + }); + } + } +}); diff --git a/tests/specs/dicom-spacing-details.e2e.ts b/tests/specs/dicom-spacing-details.e2e.ts new file mode 100644 index 000000000..4738dfac6 --- /dev/null +++ b/tests/specs/dicom-spacing-details.e2e.ts @@ -0,0 +1,179 @@ +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { volViewPage } from '../pageobjects/volview.page'; +import { + buildSyntheticDicom, + newUid, + type SyntheticSliceOptions, +} from './syntheticDicom'; +import { enhancedFixtureBytes } from '../fixtures/dicom-consumer/enhancedFixtures'; +import { dropFiles, SESSION_SAVE_TIMEOUT, waitForFileExists } from './utils'; + +const dialog = () => $('[data-testid="image-spacing-details"]'); +const axis = (name: string) => + dialog().$(`[data-testid="spacing-axis-${name}"]`); +const closeDetails = () => $('[data-testid="spacing-details-close"]').click(); + +async function openDetails() { + await $('.volume-card [data-testid="dataset-menu-button"]').click(); + const item = $('[data-testid="dataset-menu-spacing-item"]'); + await item.waitForDisplayed(); + await item.waitForStable(); + await item.waitForClickable(); + await item.click(); + await dialog().waitForDisplayed(); +} + +function slice(options: Partial = {}) { + return buildSyntheticDicom({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + instanceNumber: 1, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, 0], + rows: 4, + cols: 4, + pixelSpacing: [0.5, 0.25], + pixelValue: 80, + ...options, + }); +} + +async function openFile(name: string, bytes: Uint8Array, slices = 1) { + writeFileSync(join(TEMP_DIR, name), bytes); + await volViewPage.open(`?urls=[tmp/${name}]`); + await volViewPage.waitForVolumeCardSliceCounts([slices]); + await openDetails(); +} + +describe('DICOM physical spacing details', () => { + it('identifies unknown physical units in a public secondary capture', async () => { + await volViewPage.open('?urls=[tmp/dicom-corpus-image_dfl.dcm]'); + await volViewPage.waitForVolumeCardSliceCounts([1]); + await openDetails(); + await expect(axis('X')).toHaveText( + expect.stringContaining('physical unit unknown') + ); + await expect(axis('Y')).toHaveText( + expect.stringContaining('Assumed: Display default') + ); + await expect(dialog()).toHaveText( + expect.stringContaining('They do not establish a physical distance.') + ); + }); + + it('updates derived spacing after another slice arrives and restores it with the session', async () => { + const studyUid = newUid(); + const seriesUid = newUid(); + const first = slice({ studyUid, seriesUid }); + const secondName = 'spacing-second.dcm'; + writeFileSync( + join(TEMP_DIR, secondName), + slice({ + studyUid, + seriesUid, + instanceNumber: 2, + imagePositionPatient: [0, 0, 2], + }) + ); + await openFile('spacing-first.dcm', first); + await expect(axis('X')).toHaveText(expect.stringContaining('0.25 mm')); + await expect(axis('X')).toHaveText( + expect.stringContaining('Declared: PixelSpacing') + ); + await expect(axis('Z')).toHaveText(expect.stringContaining('One sample')); + await expect(axis('Z')).toHaveText( + expect.stringContaining('physical unit unknown') + ); + await closeDetails(); + + await dropFiles([join(TEMP_DIR, secondName)]); + await volViewPage.waitForVolumeCardSliceCounts([2]); + await openDetails(); + await expect(axis('Z')).toHaveText(expect.stringContaining('2 mm')); + await expect(axis('Z')).toHaveText( + expect.stringContaining('Derived: ImagePositionPatient') + ); + await closeDetails(); + + const saved = await volViewPage.saveSession(); + await waitForFileExists(join(TEMP_DIR, saved), SESSION_SAVE_TIMEOUT); + await volViewPage.open(`?urls=[tmp/${saved}]`); + await volViewPage.waitForVolumeCardSliceCounts([2]); + await openDetails(); + await expect(axis('X')).toHaveText(expect.stringContaining('0.25 mm')); + await expect(axis('Z')).toHaveText( + expect.stringContaining('Derived: ImagePositionPatient') + ); + await browser.saveScreenshot(join(TEMP_DIR, 'dicom-spacing-details.png')); + }); + + it('preserves the valid axis when the other PixelSpacing value is unusable', async () => { + await openFile('spacing-partial.dcm', slice({ pixelSpacing: [0, 0.25] })); + await expect(axis('X')).toHaveText(expect.stringContaining('0.25 mm')); + await expect(axis('X')).toHaveText( + expect.stringContaining('Declared: PixelSpacing') + ); + await expect(axis('Y')).toHaveText( + expect.stringContaining('physical unit unknown') + ); + await expect(axis('Y')).toHaveText( + expect.stringContaining('no usable positive spacing') + ); + }); + + it('reports the declared step of a single-file multiframe volume', async () => { + await openFile( + 'spacing-multiframe.dcm', + slice({ framePixelValues: [40, 80], spacingBetweenSlices: 1.5 }), + 2 + ); + await expect(axis('Z')).toHaveText(expect.stringContaining('1.5 mm')); + await expect(axis('Z')).toHaveText( + expect.stringContaining('Declared: SpacingBetweenSlices') + ); + }); + + it('identifies the ultrasound unit conversion and its region scope', async () => { + await openFile( + 'spacing-ultrasound.dcm', + slice({ + modality: 'US', + sopClassUid: '1.2.840.10008.5.1.4.1.1.6.1', + ultrasoundRegion: { physicalDeltaX: 0.05, physicalDeltaY: 0.03 }, + }) + ); + await expect(axis('X')).toHaveText(expect.stringContaining('0.5 mm')); + await expect(axis('Y')).toHaveText(expect.stringContaining('0.3 mm')); + await expect(dialog()).toHaveText( + expect.stringContaining('cm converted to mm') + ); + await expect(dialog()).toHaveText( + expect.stringContaining('not necessarily the entire image') + ); + }); + + it('keeps physical units distinct from an approximate reconstruction', async () => { + await openFile( + 'spacing-uneven.dcm', + enhancedFixtureBytes({ + pixelValues: [20, 80, 140], + positions: [ + [0, 0, 0], + [0, 0, 1], + [0, 0, 3], + ], + }), + 3 + ); + await expect(axis('X')).toHaveText(expect.stringContaining('mm')); + await expect(dialog()).toHaveText( + expect.stringContaining('Slices are not evenly spaced.') + ); + await expect(dialog()).toHaveText( + expect.stringContaining('The displayed grid is approximate') + ); + }); +}); diff --git a/tests/specs/dicom-volume-composition.e2e.ts b/tests/specs/dicom-volume-composition.e2e.ts new file mode 100644 index 000000000..fe685c2fe --- /dev/null +++ b/tests/specs/dicom-volume-composition.e2e.ts @@ -0,0 +1,116 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import corpus from '../dicomCompositionCorpus.json'; +import { DATASET_CACHE } from '../downloadDatasets'; +import { waitForDicomConsumer } from '../dicomConsumer'; +import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; +import { volViewPage } from '../pageobjects/volview.page'; +import { waitForRenderedSlice } from './dicomRenderedSlice'; + +type ExpectedVolume = (typeof corpus.cases)[number]['volumes'][number]; + +async function expectComposedVolumes( + volumes: ExpectedVolume[], + partial: boolean +) { + await expect($$('.volume')).toBeElementsArrayOfSize(volumes.length); + for (const volume of volumes) { + const members = partial + ? volume.sopInstanceUIDs.filter((_, index) => index % 2 === 0) + : volume.sopInstanceUIDs; + const expected = partial ? volume.initial : volume.expected; + const section = $(`.volume[data-first-sop="${members[0]}"]`); + await expect(section.$('[data-field="members"]')).toHaveText( + members.join(', ') + ); + await expect(section.$('[data-field="pixel-hash"]')).toHaveText( + expected.pixelHash + ); + await expect(section.$('[data-field="dimensions"]')).toHaveText( + expected.dimensions.join(', ') + ); + const numeric = { + spacing: expected.spacing, + origin: expected.origin, + direction: expected.direction, + range: expected.range, + 'first-plane': expected.firstPlanePosition, + 'last-plane': expected.lastPlanePosition, + }; + for (const [name, values] of Object.entries(numeric)) { + const actual = (await section.$(`[data-field="${name}"]`).getText()) + .split(', ') + .map(Number); + expect(actual).toHaveLength(values.length); + values.forEach((value, index) => + expect(Math.abs(actual[index] - value)).toBeLessThanOrEqual( + corpus.geometryToleranceMm + ) + ); + } + } +} + +describe('Downloaded DICOM volume composition', () => { + let fixture: Awaited>; + before(async () => { + const fixtures = Object.fromEntries( + corpus.datasets.map(({ name }) => [ + name, + readFileSync(resolve(DATASET_CACHE, name)), + ]) + ); + fixture = await startDicomConsumerFixtures(fixtureBytes(), { + kinds: ['composition'], + fixtures, + }); + }); + after(async () => fixture?.close()); + + for (const scenario of corpus.cases) { + for (const source of ['file', 'http']) { + for (const mode of ['batch', 'incremental']) { + it(`composes every ${scenario.id} collection from shuffled ${source} sources in ${mode} mode`, async () => { + await browser.url( + `${fixture.urls.composition}?${new URLSearchParams({ case: scenario.id, source, mode })}` + ); + if (mode === 'incremental') { + await waitForDicomConsumer(undefined, 'partial'); + await expectComposedVolumes(scenario.volumes, true); + await $('#complete-import').click(); + } + await waitForDicomConsumer(); + await expectComposedVolumes(scenario.volumes, false); + }); + } + } + } +}); + +describe('VolView downloaded collection import', () => { + for (const scenario of corpus.cases) { + it(`keeps the ${scenario.id} volumes separate in the application`, async () => { + const urls = scenario.volumes + .flatMap(({ files }) => files.map((name) => `tmp/${name}`)) + .reverse(); + await volViewPage.open(`?urls=[${urls.join(',')}]`); + await volViewPage.waitForVolumeCardSliceCounts( + scenario.volumes + .map(({ expected }) => expected.dimensions[2]) + .sort((a, b) => a - b) + ); + await volViewPage.waitForViews(); + const views = $$('[data-testid~="vtk-view"]'); + for (let index = 0; index < (await views.length); index++) + await volViewPage.waitForLoadingIndicator(views[index]); + await expect($('.loading-indicator')).not.toBeExisting(); + await waitForRenderedSlice( + `composition-${scenario.id}.png`, + 0, + scenario.id === 'pet-ct' + ); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); + } +}); diff --git a/tests/specs/dicom-volume-corpus.e2e.ts b/tests/specs/dicom-volume-corpus.e2e.ts new file mode 100644 index 000000000..7af3d4893 --- /dev/null +++ b/tests/specs/dicom-volume-corpus.e2e.ts @@ -0,0 +1,157 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { Key } from 'webdriverio'; +import corpus from '../dicomVolumeCorpus.json'; +import { DATASET_CACHE } from '../downloadDatasets'; +import { openDicomConsumer } from '../dicomConsumer'; +import { + fixtureBytes, + nullPaddedFixtureBytes, +} from '../fixtures/dicom-consumer/fixtureData'; +import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { + waitForRenderedSlice, + waitForRenderedSliceChange, +} from './dicomRenderedSlice'; + +type VolumeExpectation = { + dimensions: number[]; + range: number[]; + pixelHash: string; + spacing?: number[]; + origin?: number[]; + direction?: number[]; +}; + +const fractionalCalibration = { rescaleSlope: 1.9413152, rescaleIntercept: 0 }; +// A Float32 volume holds this fractional rescale, so samples are float32-rounded. +const calibratedValue = Math.fround(5 * fractionalCalibration.rescaleSlope); +const pixelHash = (value: number) => + createHash('sha256') + .update(Buffer.from(new Float64Array(16).fill(value).buffer)) + .digest('hex'); + +// Expected hashes were independently decoded with pydicom. Each lossless +// variant must preserve every calibrated voxel, including frame order. +const cases: Array<{ + name: string; + expected?: VolumeExpectation; + expectedError?: string; +}> = [ + ...corpus, + { + name: 'null-padded-numbers.dcm', + expected: { + dimensions: [4, 4, 1], + range: [-10, -10], + spacing: [3, 2, 4], + origin: [10, 20, 30], + pixelHash: pixelHash(-10), + }, + }, + { + name: 'null-padded-fractional-rescale.dcm', + expected: { + dimensions: [4, 4, 1], + range: [calibratedValue, calibratedValue], + pixelHash: pixelHash(calibratedValue), + }, + }, +]; + +async function expectNumbers(id: string, expected: number[]) { + const actual = (await $(`#${id}`).getText()).split(', ').map(Number); + for (const [axis, value] of expected.entries()) { + expect(actual[axis]).toBeCloseTo(value, 8); + } +} + +describe('Public DICOM volume corpus', () => { + let fixture: Awaited>; + before(async () => { + const files = Object.fromEntries( + corpus.map(({ name }) => [ + name, + readFileSync(resolve(DATASET_CACHE, name)), + ]) + ); + fixture = await startDicomConsumerFixtures(fixtureBytes(), { + kinds: ['corpus'], + fixtures: { + ...files, + 'null-padded-numbers.dcm': nullPaddedFixtureBytes(), + 'null-padded-fractional-rescale.dcm': nullPaddedFixtureBytes( + fractionalCalibration + ), + }, + }); + }); + after(async () => fixture?.close()); + + for (const { name, expected, expectedError } of cases) { + for (const source of ['file', 'http']) { + const behavior = expectedError ? 'rejects' : 'preserves'; + it(`${behavior} ${name} pixels and geometry from ${source}`, async () => { + const params = new URLSearchParams({ name, source }); + await openDicomConsumer( + `${fixture.urls.corpus}?${params}`, + expectedError + ); + if (expectedError) return; + if (!expected) throw new Error(`Missing expectations for ${name}`); + await expect($('#dimensions')).toHaveText( + expected.dimensions.join(', ') + ); + await expect($('#pixel-hash')).toHaveText(expected.pixelHash); + await expectNumbers('range', expected.range); + for (const id of ['spacing', 'origin', 'direction'] as const) { + if (expected[id]) await expectNumbers(id, expected[id]); + } + }); + } + } +}); + +describe('VolView multiframe volume import', () => { + const volumes = corpus.filter( + ({ modality, expected }) => + expected && + expected.dimensions[2] > 1 && + (modality === 'CT' || modality === 'NM') + ); + for (const { name, expected } of volumes) { + it(`displays ${name} as a complete volume`, async () => { + await volViewPage.open(`?urls=[tmp/${name}]`); + await volViewPage.waitForVolumeCardSliceCounts([expected!.dimensions[2]]); + await volViewPage.waitForViews(); + await expect($('.loading-indicator')).not.toBeExisting(); + const before = await waitForRenderedSlice(`${name}-initial.png`); + await volViewPage.focusFirst2DView(); + const label = await $( + '[data-testid~="vtk-two-view"] .slice-label' + ).getText(); + const match = label.match(/Slice:\s*(\d+)\s*\/\s*(\d+)/); + if (!match) throw new Error('Expected a displayed slice counter'); + const slice = Number(match[1]); + const total = Number(match[2]); + if (total <= 1) throw new Error('Expected navigable image planes'); + const delta = slice > 1 ? -1 : 1; + const steps = Math.min(3, delta < 0 ? slice - 1 : total - slice); + for (let offset = 1; offset <= steps; offset++) { + await browser.keys([delta < 0 ? Key.ArrowDown : Key.ArrowUp]); + await browser.waitUntil( + async () => + (await volViewPage.getFirst2DSlice()) === slice + delta * offset, + { + timeoutMsg: + 'Expected the displayed slice counter to follow navigation', + } + ); + } + await waitForRenderedSliceChange(before, `${name}-navigated.png`); + expect(await volViewPage.getNotificationsCount()).toBe(0); + }); + } +}); diff --git a/tests/specs/dicomRenderedSlice.ts b/tests/specs/dicomRenderedSlice.ts new file mode 100644 index 000000000..a4dec4653 --- /dev/null +++ b/tests/specs/dicomRenderedSlice.ts @@ -0,0 +1,128 @@ +import { resolve } from 'node:path'; +import { PNG } from 'pngjs'; +import { TEMP_DIR } from '../../wdio.shared.conf'; + +type RenderedSlice = { width: number; height: number; data: Buffer }; + +async function captureSlice(fileName: string, viewIndex: number) { + const image = PNG.sync.read( + await browser.saveScreenshot(resolve(TEMP_DIR, fileName)) + ); + const geometry = await browser.execute((index) => { + const view = document.querySelectorAll('[data-testid~="vtk-two-view"]')[ + index + ]; + if (!view) return null; + const rect = view.getBoundingClientRect(); + return { + x: rect.x, + y: rect.y, + width: rect.width, + height: rect.height, + viewportWidth: window.innerWidth, + viewportHeight: window.innerHeight, + }; + }, viewIndex); + if (!geometry) throw new Error(`No slice viewport at index ${viewIndex}`); + const scaleX = image.width / geometry.viewportWidth; + const scaleY = image.height / geometry.viewportHeight; + const left = Math.ceil((geometry.x + geometry.width * 0.18) * scaleX); + const top = Math.ceil((geometry.y + geometry.height * 0.18) * scaleY); + const width = Math.floor(geometry.width * 0.64 * scaleX); + const height = Math.floor(geometry.height * 0.64 * scaleY); + if ( + width <= 0 || + height <= 0 || + left < 0 || + top < 0 || + left + width > image.width || + top + height > image.height + ) + throw new Error('The slice viewport has no interior image region'); + // The central image region excludes orientation labels, slice counters, + // sliders and viewport controls, so UI text cannot satisfy image assertions. + const data = Buffer.alloc(width * height * 4); + for (let row = 0; row < height; row++) { + const source = ((top + row) * image.width + left) * 4; + image.data.copy(data, row * width * 4, source, source + width * 4); + } + return { width, height, data }; +} + +function hasImageContent( + { width, height, data }: RenderedSlice, + color = false +) { + let visible = 0; + let midtone = 0; + const tones = new Set(); + for (let index = 0; index < data.length; index += 4) { + const red = data[index]; + const green = data[index + 1]; + const blue = data[index + 2]; + const intensity = (red + green + blue) / 3; + if (!color && Math.max(red, green, blue) - Math.min(red, green, blue) > 3) + continue; + if (intensity > 16) visible++; + if (intensity > 32 && intensity < 224) midtone++; + tones.add(Math.floor(intensity / 16)); + } + const count = width * height; + return ( + visible > count * 0.01 && + visible < count * 0.9 && + midtone > count * 0.003 && + tones.size >= 5 + ); +} + +function imageChanged(before: RenderedSlice, after: RenderedSlice) { + if (before.width !== after.width || before.height !== after.height) + return false; + let changed = 0; + for (let index = 0; index < before.data.length; index += 4) { + const delta = + Math.abs(before.data[index] - after.data[index]) + + Math.abs(before.data[index + 1] - after.data[index + 1]) + + Math.abs(before.data[index + 2] - after.data[index + 2]); + if (delta >= 24) changed++; + } + return changed > before.width * before.height * 0.002; +} + +export async function waitForRenderedSlice( + fileName: string, + viewIndex = 0, + color = false +) { + await $('header').moveTo(); + let image: RenderedSlice | undefined; + await browser.waitUntil( + async () => { + image = await captureSlice(fileName, viewIndex); + return hasImageContent(image, color); + }, + { + timeoutMsg: `Expected anatomical ${color ? 'color' : 'grayscale'} content inside the slice viewport`, + } + ); + return image!; +} + +export async function waitForRenderedSliceChange( + before: RenderedSlice, + fileName: string, + viewIndex = 0 +) { + await $('header').moveTo(); + await browser.waitUntil( + async () => { + const after = await captureSlice(fileName, viewIndex); + return hasImageContent(after) && imageChanged(before, after); + }, + { + timeoutMsg: + 'Expected slice navigation to change the interior image pixels', + } + ); +} diff --git a/tests/specs/incremental-positionless-import.e2e.ts b/tests/specs/incremental-positionless-import.e2e.ts new file mode 100644 index 000000000..1a9105fdf --- /dev/null +++ b/tests/specs/incremental-positionless-import.e2e.ts @@ -0,0 +1,116 @@ +// A second import must not dissolve the volumes the first one earned. +// +// One series holds two overlapping acquisitions, which load as two volumes. +// A later import brings one more slice of that series whose +// ImagePositionPatient is empty, so nothing can be said about where it sits. +// Both volumes must survive, the unplaceable slice must arrive as a volume of +// its own, and the user must be told about it. +// +// Synthetic DICOMs are generated on the fly so the test carries no binary +// fixtures. +import * as path from 'path'; +import * as fs from 'fs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { dropFiles, writeManifestToFile } from './utils'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; + +const SLICE_SPACING = 2.5; +const ORIENTATION = [1, 0, 0, 0, 1, 0] as const; + +// Offset by half a slice, so the two passes overlap and the planner separates +// them. Slice counts differ so each volume card is identifiable by its label. +const ACQUISITIONS = [ + { number: 1, firstSliceZ: 0, sliceCount: 5 }, + { number: 2, firstSliceZ: 1.25, sliceCount: 6 }, +]; + +const DIR_NAME = 'incremental-positionless-import'; +const MANIFEST_NAME = 'incremental-positionless-import.json'; +const POSITIONLESS_NAME = 'positionless.dcm'; + +const seriesUid = newUid(); +const studyUid = newUid(); + +const dir = () => path.join(TEMP_DIR, DIR_NAME); + +function writeSeries() { + fs.mkdirSync(dir(), { recursive: true }); + + let instanceNumber = 0; + return ACQUISITIONS.flatMap(({ number, firstSliceZ, sliceCount }) => + Array.from({ length: sliceCount }, (_, i) => { + instanceNumber += 1; + const filename = `acq${number}-slice${i}.dcm`; + fs.writeFileSync( + path.join(dir(), filename), + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + instanceNumber, + acquisitionNumber: number, + imageOrientationPatient: ORIENTATION, + imagePositionPatient: [0, 0, firstSliceZ + i * SLICE_SPACING], + sliceThickness: SLICE_SPACING, + }) + ); + return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; + }) + ); +} + +// Same series and same hard facts as the two passes, so only its unreadable +// geometry can keep it out of them. +function writePositionlessSlice() { + fs.writeFileSync( + path.join(dir(), POSITIONLESS_NAME), + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + instanceNumber: 99, + imageOrientationPatient: ORIENTATION, + imagePositionPatient: null, + sliceThickness: SLICE_SPACING, + }) + ); +} + +describe('Incremental import of a slice with no readable position', () => { + before(async () => { + const resources = writeSeries(); + writePositionlessSlice(); + await writeManifestToFile({ resources }, MANIFEST_NAME); + }); + + it('keeps both acquisitions and warns about the slice it cannot place', async () => { + await volViewPage.open(`?urls=[tmp/${MANIFEST_NAME}]`); + await volViewPage.waitForViews(); + + const passes = ACQUISITIONS.map((a) => a.sliceCount).sort((a, b) => a - b); + await volViewPage.waitForVolumeCardSliceCounts(passes); + expect(await volViewPage.getNotificationsCount()).toEqual(0); + + await dropFiles([path.join(dir(), POSITIONLESS_NAME)]); + + // The two passes are untouched, and the unplaceable slice is a volume of + // its own rather than a member of either. + await volViewPage.waitForVolumeCardSliceCounts([1, ...passes]); + + await volViewPage.waitForNotification(); + + // The toast of that same warning covers the notifications button. + await browser.waitUntil( + async () => (await $$('.Vue-Toastification__toast').length) === 0, + { timeoutMsg: 'expected the warning toast to close' } + ); + + await volViewPage.notifications.click(); + const dialog = await $('.message-center'); + await dialog.waitForDisplayed(); + expect(await dialog.getText()).toContain( + 'A DICOM series did not load as one sound volume' + ); + }); +}); diff --git a/tests/specs/layers-and-rendering.e2e.ts b/tests/specs/layers-and-rendering.e2e.ts index fba5789e9..526931ac0 100644 --- a/tests/specs/layers-and-rendering.e2e.ts +++ b/tests/specs/layers-and-rendering.e2e.ts @@ -44,6 +44,9 @@ describe('Layers and Rendering', () => { await renderTab.click(); const view3D = await volViewPage.getView3D(); + await volViewPage.waitForLoadingIndicator( + $('[data-testid~="vtk-volume-view"]') + ); const volumeRenderingSection = await volViewPage.getVolumeRenderingSection(); diff --git a/tests/specs/multi-acquisition-series.e2e.ts b/tests/specs/multi-acquisition-series.e2e.ts new file mode 100644 index 000000000..f299ca446 --- /dev/null +++ b/tests/specs/multi-acquisition-series.e2e.ts @@ -0,0 +1,78 @@ +// One DICOM series carrying several overlapping acquisitions must load as one +// volume per acquisition, not as a single stack of interleaved slices. +// +// Modelled on IDC series +// 1.3.6.1.4.1.14519.5.2.1.3098.5025.295130953269492004748715270821, which +// holds three 2.5mm chest/abdomen passes offset from each other by fractions +// of a slice. Synthetic DICOMs are generated on the fly so the test carries +// no binary fixtures. +import * as path from 'path'; +import * as fs from 'fs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { writeManifestToFile } from './utils'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; + +const SLICE_SPACING = 2.5; + +// Each pass is uniform on its own; the sub-slice offsets are what make the +// merged stack irregular. Slice counts differ so each volume card is +// identifiable by its label alone. +const ACQUISITIONS = [ + { number: 1, firstSliceZ: 0, sliceCount: 5 }, + { number: 2, firstSliceZ: 0.75, sliceCount: 6 }, + { number: 3, firstSliceZ: 1.75, sliceCount: 4 }, +]; + +const DIR_NAME = 'multi-acquisition-series'; +const MANIFEST_NAME = 'multi-acquisition-series.json'; + +async function writeSeries() { + const studyUid = newUid(); + const seriesUid = newUid(); + const dir = path.join(TEMP_DIR, DIR_NAME); + fs.mkdirSync(dir, { recursive: true }); + + let instanceNumber = 0; + const resources = ACQUISITIONS.flatMap( + ({ number, firstSliceZ, sliceCount }) => + Array.from({ length: sliceCount }, (_, i) => { + instanceNumber += 1; + const filename = `acq${number}-slice${i}.dcm`; + fs.writeFileSync( + path.join(dir, filename), + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + instanceNumber, + acquisitionNumber: number, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, firstSliceZ + i * SLICE_SPACING], + sliceThickness: SLICE_SPACING, + }) + ); + return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; + }) + ); + + await writeManifestToFile({ resources }, MANIFEST_NAME); +} + +describe('Multi-acquisition series: one series holding three overlapping scans', () => { + before(async () => { + await writeSeries(); + }); + + it('loads one volume per acquisition instead of one interleaved stack', async () => { + await volViewPage.open(`?urls=[tmp/${MANIFEST_NAME}]`); + await volViewPage.waitForViews(); + + const expected = ACQUISITIONS.map((a) => a.sliceCount).sort( + (a, b) => a - b + ); + + // One card per acquisition, each holding only that acquisition's slices. + await volViewPage.waitForVolumeCardSliceCounts(expected); + }); +}); diff --git a/tests/specs/octTestUtils.ts b/tests/specs/octTestUtils.ts index 4693d4066..eaeea0e3c 100644 --- a/tests/specs/octTestUtils.ts +++ b/tests/specs/octTestUtils.ts @@ -160,10 +160,13 @@ const enFaceView = async (view?: WebdriverIO.Element) => view ?? $(VIEWER).getElement(); export async function selectEnFace(viewIndex = 0) { - const switcher = (await $$('.view-type-select .v-field'))[viewIndex]; + const switcher = $$('.view-type-select .v-field')[viewIndex]; await switcher.click(); const option = overlayOption('En face'); await option.waitForExist(); + // Source canvases render progressively; En face stays disabled until the + // complete volume has loaded. Use that view's published loading state. + await volViewPage.waitForLoadingIndicator(switcher); await option.waitForClickable(); await option.click(); await $(CANVAS).waitForExist(); diff --git a/tests/specs/pet-ct-sample.e2e.ts b/tests/specs/pet-ct-sample.e2e.ts index 82ad17552..a2e3e7be9 100644 --- a/tests/specs/pet-ct-sample.e2e.ts +++ b/tests/specs/pet-ct-sample.e2e.ts @@ -44,7 +44,9 @@ async function openAxialSample() { await volViewPage.open(); await selectLayout('Axial Only', 1, false); const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); - await sample.scrollIntoView(); + await sample.execute((element) => + element.scrollIntoView({ block: 'center', behavior: 'instant' }) + ); await sample.waitForClickable(); await sample.click(); await volViewPage.waitForViews(); @@ -149,25 +151,28 @@ async function editPetColors( }; } -async function reopenSample( - expected: Awaited>, - range: string[], - preset = 'DICOM Hot Iron' -) { +async function showSampleData() { await $('[data-testid="module-tab-Data"]').click(); await waitForModuleTransitions(); const samplesSection = $('.v-expansion-panel-title*=Sample Data'); - if ((await samplesSection.getAttribute('aria-expanded')) === 'true') { + if ((await samplesSection.getAttribute('aria-expanded')) !== 'true') { await samplesSection.click(); - await expect(samplesSection).toHaveAttribute('aria-expanded', 'false'); + await expect(samplesSection).toHaveAttribute('aria-expanded', 'true'); await waitForModuleTransitions(); } - await samplesSection.click(); - await expect(samplesSection).toHaveAttribute('aria-expanded', 'true'); +} + +async function reopenSample( + expected: Awaited>, + range: string[], + preset = 'DICOM Hot Iron' +) { + await showSampleData(); const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); await sample.waitForExist(); - await waitForModuleTransitions(); - await sample.scrollIntoView({ block: 'center', behavior: 'instant' }); + await sample.execute((element) => + element.scrollIntoView({ block: 'center', behavior: 'instant' }) + ); await browser.saveScreenshot(path.join(TEMP_DIR, 'pet-ct-sample-reload.png')); await sample.waitForClickable(); await sample.click(); @@ -313,16 +318,11 @@ describe('PET/CT sample', () => { await volViewPage.open(); await selectLayout('Four Up', 3, true); for (let loading = 0; loading < 2; loading++) { - await $('[data-testid="module-tab-Data"]').click(); - await waitForModuleTransitions(); - const samplesSection = $('.v-expansion-panel-title*=Sample Data'); - if ((await samplesSection.getAttribute('aria-expanded')) !== 'true') { - await samplesSection.click(); - await expect(samplesSection).toHaveAttribute('aria-expanded', 'true'); - await waitForModuleTransitions(); - } + await showSampleData(); const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); - await sample.scrollIntoView({ block: 'center', behavior: 'instant' }); + await sample.execute((element) => + element.scrollIntoView({ block: 'center', behavior: 'instant' }) + ); await sample.waitForClickable(); await sample.click(); await expect($('[data-testid~="vtk-two-view"]')).toHaveText( diff --git a/tests/specs/sample-rendering.e2e.ts b/tests/specs/sample-rendering.e2e.ts index 632bee255..1020854e7 100644 --- a/tests/specs/sample-rendering.e2e.ts +++ b/tests/specs/sample-rendering.e2e.ts @@ -1,6 +1,7 @@ import AppPage from '../pageobjects/volview.page'; import { PROSTATEX_DATASET } from '../datasets'; import { useCachedSample } from './utils'; +import { DOWNLOAD_TIMEOUT } from '../../wdio.shared.conf'; const THRESHOLD = 12; // percent - handle pixel jitter in 3D view const RENDER_STABLE_TIMEOUT = 5000; @@ -11,7 +12,27 @@ describe('VolView', () => { await AppPage.open(); await AppPage.downloadProstateSample(); - await AppPage.waitForViews(); + + await browser.waitUntil( + async () => + browser.execute(() => { + const canvases = document.querySelectorAll( + '.layout-container [data-testid~="vtk-view"] canvas' + ); + return ( + canvases.length === 4 && + Array.from(canvases).every((element) => { + const canvas = element as HTMLCanvasElement; + return canvas.width > 10 && canvas.height > 10; + }) && + !document.querySelector('.layout-container .loading-indicator') + ); + }), + { + timeout: DOWNLOAD_TIMEOUT, + timeoutMsg: 'Expected all sample views to finish loading', + } + ); const layoutContainer = await $('.layout-container'); diff --git a/tests/specs/segmentationTestUtils.ts b/tests/specs/segmentationTestUtils.ts index ae2cd4b5d..e9f7e2e05 100644 --- a/tests/specs/segmentationTestUtils.ts +++ b/tests/specs/segmentationTestUtils.ts @@ -1,5 +1,6 @@ import { Key, type ChainablePromiseElement } from 'webdriverio'; import { setValueVueInput, volViewPage } from '../pageobjects/volview.page'; +import { DOWNLOAD_TIMEOUT } from '../../wdio.shared.conf'; const SEGMENT_LIST = '[data-testid="segment-list"]'; const SHAPE_ROW = '[data-testid="segment-shape-row"]'; @@ -67,7 +68,10 @@ export const waitForSegmentContent = async (name: string) => { const row = await segmentRow(name); await browser.waitUntil( async () => (await $(SEGMENT_LIST).getAttribute('aria-busy')) !== 'true', - { timeoutMsg: 'Expected the scene to finish loading' } + { + timeout: DOWNLOAD_TIMEOUT, + timeoutMsg: 'Expected the scene to finish loading', + } ); await row.$('button[data-testid="reveal-segment-button"]').waitForEnabled(); }; diff --git a/tests/specs/session-overlapping-imports.e2e.ts b/tests/specs/session-overlapping-imports.e2e.ts new file mode 100644 index 000000000..e0080eb48 --- /dev/null +++ b/tests/specs/session-overlapping-imports.e2e.ts @@ -0,0 +1,109 @@ +// A session saved after an incremental import must restore what the browser +// shows, not the membership the first import saw. +// +// One series holds two overlapping acquisitions. The first import loads one of +// them; a second import brings the other, and the planner regroups the series +// into two volumes. The session saved afterwards must restore both. Deleting +// one volume and saving again must restore only the survivor: a dataset the +// user removed cannot come back. +// +// Synthetic DICOMs are generated on the fly so the test carries no binary +// fixtures. +import * as path from 'path'; +import * as fs from 'fs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { + SESSION_SAVE_TIMEOUT, + dropFiles, + waitForFileExists, + writeManifestToFile, +} from './utils'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; + +const SLICE_SPACING = 2.5; +const ORIENTATION = [1, 0, 0, 0, 1, 0] as const; + +// Offset by half a slice, so the two passes overlap and the planner separates +// them. Slice counts differ so each volume card is identifiable by its label. +const FIRST_PASS = { number: 1, firstSliceZ: 0, sliceCount: 5 }; +const SECOND_PASS = { number: 2, firstSliceZ: 1.25, sliceCount: 6 }; + +const DIR_NAME = 'session-overlapping-imports'; +const MANIFEST_NAME = 'session-overlapping-imports.json'; + +const seriesUid = newUid(); +const studyUid = newUid(); + +const dir = () => path.join(TEMP_DIR, DIR_NAME); + +type Pass = typeof FIRST_PASS; + +function writePass({ number, firstSliceZ, sliceCount }: Pass) { + fs.mkdirSync(dir(), { recursive: true }); + + return Array.from({ length: sliceCount }, (_, i) => { + const filename = `acq${number}-slice${i}.dcm`; + fs.writeFileSync( + path.join(dir(), filename), + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + // Unique across both passes, so no instance looks like a re-send. + instanceNumber: number * 100 + i, + acquisitionNumber: number, + imageOrientationPatient: ORIENTATION, + imagePositionPatient: [0, 0, firstSliceZ + i * SLICE_SPACING], + sliceThickness: SLICE_SPACING, + }) + ); + return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; + }); +} + +const saveSession = async () => { + const fileName = await volViewPage.saveSession(); + await waitForFileExists(path.join(TEMP_DIR, fileName), SESSION_SAVE_TIMEOUT); + return fileName; +}; + +const openSavedSession = async (fileName: string) => { + await volViewPage.open(`?urls=[tmp/${fileName}]`); + await volViewPage.waitForViews(); +}; + +describe('Session saved after an incremental import of one series', () => { + let secondPassFiles: string[]; + + before(async () => { + const resources = writePass(FIRST_PASS); + secondPassFiles = writePass(SECOND_PASS).map(({ name }) => name); + await writeManifestToFile({ resources }, MANIFEST_NAME); + }); + + it('restores both volumes, and drops one the user deleted', async () => { + await volViewPage.open(`?urls=[tmp/${MANIFEST_NAME}]`); + await volViewPage.waitForViews(); + await volViewPage.waitForVolumeCardSliceCounts([FIRST_PASS.sliceCount]); + + // The regroup this triggers replaces the volume the first import earned. + await dropFiles(secondPassFiles.map((name) => path.join(dir(), name))); + const bothPasses = [FIRST_PASS.sliceCount, SECOND_PASS.sliceCount].sort( + (a, b) => a - b + ); + await volViewPage.waitForVolumeCardSliceCounts(bothPasses); + + const withBoth = await saveSession(); + await openSavedSession(withBoth); + await volViewPage.waitForVolumeCardSliceCounts(bothPasses); + + await volViewPage.deleteVolumeCard(0); + const survivor = bothPasses.slice(1); + await volViewPage.waitForVolumeCardSliceCounts(survivor); + + const withSurvivor = await saveSession(); + await openSavedSession(withSurvivor); + await volViewPage.waitForVolumeCardSliceCounts(survivor); + }); +}); diff --git a/tests/specs/syntheticDicom.ts b/tests/specs/syntheticDicom.ts index eb9454a0d..c5269b055 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -1,12 +1,14 @@ // Minimal synthetic DICOM (Explicit VR Little Endian) for tests. // Emits just enough tags for ITK/GDCM to categorize and load a series: -// SOP Class/Instance UIDs, Study/SeriesInstanceUID, SeriesNumber, Modality, +// SOP Class/Instance UIDs, Study/SeriesInstanceUID, SeriesNumber, +// AcquisitionNumber, Modality, // Patient identifiers, ImageOrientationPatient, ImagePositionPatient, // PixelSpacing, SliceThickness, image geometry, and constant-valued PixelData. const SOP_CLASS_MR = '1.2.840.10008.5.1.4.1.1.4'; const SOP_CLASS_ULTRASOUND_MULTIFRAME = '1.2.840.10008.5.1.4.1.1.3.1'; const TS_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; +const TS_IMPLICIT_VR_LE = '1.2.840.10008.1.2'; const enc = new TextEncoder(); @@ -63,8 +65,10 @@ export const LONG_FORM_VRS = new Set([ 'OD', 'OF', 'OL', + 'OV', 'OW', 'SQ', + 'SV', 'UC', 'UN', 'UR', @@ -105,6 +109,145 @@ const ds = (g: number, e: number, v: string) => const us = (g: number, e: number, v: number) => elemShort(g, e, 'US', writeShort(v)); +const writeDouble = (v: number) => { + const b = new Uint8Array(8); + new DataView(b.buffer).setFloat64(0, v, true); + return b; +}; + +const fd = (g: number, e: number, v: number) => + elemShort(g, e, 'FD', writeDouble(v)); + +// A PN whose bytes are already encoded in some Specific Character Set, padded +// to DICOM's even length with a space. +const pnRaw = (g: number, e: number, v: Uint8Array) => + elemShort( + g, + e, + 'PN', + v.length % 2 === 0 ? v : combine(v, new Uint8Array([0x20])) + ); + +// One Explicit VR LE element, short or long form as the VR requires. Lets a +// fixture write a VR this helper has no named writer for. +export const rawElement = ( + group: number, + element: number, + vr: string, + value: Uint8Array +) => + LONG_FORM_VRS.has(vr) + ? elemLong(group, element, vr, value) + : elemShort(group, element, vr, value); + +// An AT value is the referenced tag as two little-endian unsigned shorts. +export const attributeTagValue = (group: number, element: number) => + tagBytes(group, element); + +const ITEM_GROUP = 0xfffe; +const ITEM_TAG = 0xe000; +const ITEM_DELIMITER_TAG = 0xe00d; +const SEQUENCE_DELIMITER_TAG = 0xe0dd; +const UNDEFINED_LENGTH = 0xffffffff; + +// One sequence item of defined length, holding the elements given. +export const sequenceItem = (content: Uint8Array) => + combine(tagBytes(ITEM_GROUP, ITEM_TAG), writeLong(content.length), content); + +// One sequence item whose length the delimiter that follows it declares. +export const undefinedLengthItem = (content: Uint8Array) => + combine( + tagBytes(ITEM_GROUP, ITEM_TAG), + writeLong(UNDEFINED_LENGTH), + content, + tagBytes(ITEM_GROUP, ITEM_DELIMITER_TAG), + writeLong(0) + ); + +/** + * An Explicit VR LE sequence whose length the delimiter that follows it + * declares, the form an item's own length cannot be stepped over in. Not + * convertible to Implicit VR by `buildSyntheticDicom`. + */ +export const undefinedLengthSequence = ( + group: number, + element: number, + items: Uint8Array +) => + combine( + tagBytes(group, element), + enc.encode('SQ'), + new Uint8Array(2), + writeLong(UNDEFINED_LENGTH), + items, + tagBytes(ITEM_GROUP, SEQUENCE_DELIMITER_TAG), + writeLong(0) + ); + +/** An unknown sequence retains its Implicit VR LE items inside an explicit UN. */ +export const undefinedLengthUnknown = ( + group: number, + element: number, + items: Uint8Array +) => { + const bytes = undefinedLengthSequence(group, element, items); + bytes.set(enc.encode('UN'), 4); + return bytes; +}; + +// Items and delimiters carry no VR in either syntax, so only the elements +// inside each item change shape. Item lengths must be defined. +const itemsToImplicitVr = (value: Uint8Array): Uint8Array => { + const view = new DataView(value.buffer, value.byteOffset, value.length); + const out: Uint8Array[] = []; + let offset = 0; + while (offset < value.length) { + const group = view.getUint16(offset, true); + const element = view.getUint16(offset + 2, true); + const length = view.getUint32(offset + 4, true); + const contentStart = offset + 8; + if (group !== 0xfffe) + throw new Error(`Expected an item tag, got ${group.toString(16)}`); + if (element !== ITEM_TAG) { + out.push(value.subarray(offset, contentStart)); + offset = contentStart; + continue; + } + if (length === UNDEFINED_LENGTH) + throw new Error('Undefined-length items are not supported'); + const content = toImplicitVr( + value.subarray(contentStart, contentStart + length) + ); + out.push(tagBytes(group, element), writeLong(content.length), content); + offset = contentStart + length; + } + return combine(...out); +}; + +// Re-encodes an Explicit VR LE dataset as Implicit VR LE: tag, 4-byte length, +// value, with the VR carried only by the reader's dictionary. +export const toImplicitVr = (dataset: Uint8Array): Uint8Array => { + const view = new DataView(dataset.buffer, dataset.byteOffset, dataset.length); + const out: Uint8Array[] = []; + let offset = 0; + while (offset < dataset.length) { + const group = view.getUint16(offset, true); + const element = view.getUint16(offset + 2, true); + const vr = String.fromCharCode(dataset[offset + 4], dataset[offset + 5]); + const longForm = LONG_FORM_VRS.has(vr); + const length = longForm + ? view.getUint32(offset + 8, true) + : view.getUint16(offset + 6, true); + const valueStart = offset + (longForm ? 12 : 8); + const explicitValue = dataset.subarray(valueStart, valueStart + length); + const value = + vr === 'SQ' ? itemsToImplicitVr(explicitValue) : explicitValue; + out.push(combine(tagBytes(group, element), writeLong(value.length), value)); + offset = valueStart + length; + } + return combine(...out); +}; + // DICOM element values must have an even length, so an odd-sized 8-bit frame // gets a trailing pad byte. const frameBytes8 = (sampleCount: number, value: number) => { @@ -121,6 +264,24 @@ const frameBytes16 = (sampleCount: number, value: number) => { return bytes; }; +const rgbFrame = (samples: readonly number[], count: number, bits: number) => { + if (bits !== 8 || samples.length !== count * 3) + throw new Error('RGB fixtures require three 8-bit samples per pixel'); + const bytes = new Uint8Array(samples.length + (samples.length % 2)); + bytes.set(samples); + return bytes; +}; + +// A single-item sequence with an explicit item length, so a reader that skips +// sequences and one that descends into them both stay in step. +const sequenceOfOneItem = (g: number, e: number, item: Uint8Array) => + elemLong( + g, + e, + 'SQ', + combine(tagBytes(0xfffe, 0xe000), writeLong(item.length), item) + ); + export type SyntheticSliceOptions = { studyUid: string; seriesUid: string; @@ -134,7 +295,9 @@ export type SyntheticSliceOptions = { number, number, ]; - imagePositionPatient: readonly [number, number, number]; + // Null writes a zero length ImagePositionPatient, which reads as a slice + // whose geometry is unknown. + imagePositionPatient: readonly [number, number, number] | null; rows?: number; cols?: number; bitsAllocated?: number; @@ -146,14 +309,34 @@ export type SyntheticSliceOptions = { // Stored value written to every sample. Signed values are written as two's // complement, so they pair with pixelRepresentation 1. pixelValue?: number; + // Interleaved samples for one 8-bit RGB frame. + rgbPixels?: readonly number[]; + // One constant sample value per frame; writes NumberOfFrames when supplied. + framePixelValues?: readonly number[]; + // Enhanced images carry these attributes in Functional Groups instead. + rootGeometry?: boolean; pixelSpacing?: readonly [number, number]; spacingBetweenSlices?: number; sliceThickness?: number; modality?: string; + sopClassUid?: string; patientName?: string; patientId?: string; seriesNumber?: number; + acquisitionNumber?: number; studyDate?: string; + // (0008,0005), e.g. 'ISO 2022 IR 6\\ISO 2022 IR 87'. Omitted when absent. + specificCharacterSet?: string; + // PatientName bytes already encoded in specificCharacterSet, used instead of + // patientName. + patientNameBytes?: Uint8Array; + // Encodes the dataset (not the file meta group) as Implicit VR LE. + implicitVr?: boolean; + // Writes a Sequence of Ultrasound Regions (0018,6011) holding one item. + ultrasoundRegion?: { physicalDeltaX: number; physicalDeltaY: number }; + // Explicit VR LE element bytes, from `rawElement`, written just before Pixel + // Data. Tags must sort after (0028,1053) to keep the data set ascending. + extraElements?: readonly Uint8Array[]; }; export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { @@ -173,14 +356,24 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { rescaleSlope, rescaleIntercept, pixelValue = 0, + rgbPixels, + framePixelValues, + rootGeometry = true, pixelSpacing = [1, 1] as const, spacingBetweenSlices, sliceThickness = 1, modality = 'MR', + sopClassUid = SOP_CLASS_MR, patientName = 'TEST', patientId = 'TEST001', seriesNumber = 1, + acquisitionNumber, studyDate = '20260101', + specificCharacterSet, + patientNameBytes, + implicitVr = false, + ultrasoundRegion, + extraElements = [], } = opts; if (bitsAllocated !== 8 && bitsAllocated !== 16) { @@ -189,13 +382,28 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { ); } - const dataset = combine( - ui(0x0008, 0x0016, SOP_CLASS_MR), + const pixels = rgbPixels + ? rgbFrame(rgbPixels, rows * cols, bitsAllocated) + : combine( + ...(framePixelValues ?? [pixelValue]).map((value) => + bitsAllocated === 8 + ? frameBytes8(rows * cols, value) + : frameBytes16(rows * cols, value) + ) + ); + + const explicitDataset = combine( + ...(specificCharacterSet == null + ? [] + : [cs(0x0008, 0x0005, specificCharacterSet)]), + ui(0x0008, 0x0016, sopClassUid), ui(0x0008, 0x0018, sopUid), da(0x0008, 0x0020, studyDate), da(0x0008, 0x0021, studyDate), cs(0x0008, 0x0060, modality), - pn(0x0010, 0x0010, patientName), + patientNameBytes == null + ? pn(0x0010, 0x0010, patientName) + : pnRaw(0x0010, 0x0010, patientNameBytes), lo(0x0010, 0x0020, patientId), da(0x0010, 0x0030, '19700101'), cs(0x0010, 0x0040, 'O'), @@ -203,26 +411,55 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { ...(spacingBetweenSlices == null ? [] : [ds(0x0018, 0x0088, String(spacingBetweenSlices))]), + ...(ultrasoundRegion == null + ? [] + : [ + sequenceOfOneItem( + 0x0018, + 0x6011, + combine( + us(0x0018, 0x6024, 3), + us(0x0018, 0x6026, 3), + fd(0x0018, 0x602c, ultrasoundRegion.physicalDeltaX), + fd(0x0018, 0x602e, ultrasoundRegion.physicalDeltaY) + ) + ), + ]), ui(0x0020, 0x000d, studyUid), ui(0x0020, 0x000e, seriesUid), sh(0x0020, 0x0010, '1'), is(0x0020, 0x0011, String(seriesNumber)), + ...(acquisitionNumber == null + ? [] + : [is(0x0020, 0x0012, String(acquisitionNumber))]), is(0x0020, 0x0013, String(instanceNumber)), - ds( - 0x0020, - 0x0032, - imagePositionPatient.map((n) => n.toString()).join('\\') - ), - ds( - 0x0020, - 0x0037, - imageOrientationPatient.map((n) => n.toString()).join('\\') - ), - us(0x0028, 0x0002, 1), - cs(0x0028, 0x0004, 'MONOCHROME2'), + ...(rootGeometry + ? [ + ds( + 0x0020, + 0x0032, + imagePositionPatient === null + ? '' + : imagePositionPatient.map((n) => n.toString()).join('\\') + ), + ds( + 0x0020, + 0x0037, + imageOrientationPatient.map((n) => n.toString()).join('\\') + ), + ] + : []), + us(0x0028, 0x0002, rgbPixels ? 3 : 1), + cs(0x0028, 0x0004, rgbPixels ? 'RGB' : 'MONOCHROME2'), + ...(rgbPixels ? [us(0x0028, 0x0006, 0)] : []), + ...(framePixelValues + ? [is(0x0028, 0x0008, String(framePixelValues.length))] + : []), us(0x0028, 0x0010, rows), us(0x0028, 0x0011, cols), - ds(0x0028, 0x0030, pixelSpacing.map((n) => n.toString()).join('\\')), + ...(rootGeometry + ? [ds(0x0028, 0x0030, pixelSpacing.map((n) => n.toString()).join('\\'))] + : []), us(0x0028, 0x0100, bitsAllocated), us(0x0028, 0x0101, bitsStored), us(0x0028, 0x0102, highBit), @@ -231,16 +468,17 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { ? [] : [ds(0x0028, 0x1052, String(rescaleIntercept))]), ...(rescaleSlope == null ? [] : [ds(0x0028, 0x1053, String(rescaleSlope))]), - bitsAllocated === 8 - ? elemLong(0x7fe0, 0x0010, 'OB', frameBytes8(rows * cols, pixelValue)) - : elemLong(0x7fe0, 0x0010, 'OW', frameBytes16(rows * cols, pixelValue)) + ...extraElements, + elemLong(0x7fe0, 0x0010, bitsAllocated === 8 ? 'OB' : 'OW', pixels) ); + const dataset = implicitVr ? toImplicitVr(explicitDataset) : explicitDataset; + const fileMetaBody = combine( elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), - ui(0x0002, 0x0002, SOP_CLASS_MR), + ui(0x0002, 0x0002, sopClassUid), ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, TS_EXPLICIT_VR_LE) + ui(0x0002, 0x0010, implicitVr ? TS_IMPLICIT_VR_LE : TS_EXPLICIT_VR_LE) ); const fileMeta = combine( elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), @@ -250,6 +488,24 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); } +/** The bytes a Part 10 file spends on its preamble and DICM prefix. */ +const PART_10_HEADER_LENGTH = 132; + +/** The same file with its preamble and prefix cut off: file meta comes first. */ +export const stripPreamble = (bytes: Uint8Array) => + bytes.slice(PART_10_HEADER_LENGTH); + +/** The same file as a bare data set: no preamble, prefix or file meta. */ +export const stripFileMeta = (bytes: Uint8Array) => { + const meta = stripPreamble(bytes); + // (0002,0000) UL: tag, VR and a 16 bit length, then the group length. + const bodyLength = new DataView(meta.buffer, meta.byteOffset).getUint32( + 8, + true + ); + return meta.slice(12 + bodyLength); +}; + export type SyntheticCineOptions = { studyUid: string; seriesUid: string; @@ -290,6 +546,7 @@ export function buildSyntheticCineDicom( da(0x0008, 0x0020, studyDate), da(0x0008, 0x0021, studyDate), cs(0x0008, 0x0060, 'US'), + lo(0x0008, 0x103e, 'Synthetic cine'), pn(0x0010, 0x0010, patientName), lo(0x0010, 0x0020, patientId), da(0x0010, 0x0030, '19700101'), @@ -298,7 +555,6 @@ export function buildSyntheticCineDicom( ui(0x0020, 0x000e, seriesUid), sh(0x0020, 0x0010, '1'), is(0x0020, 0x0011, String(seriesNumber)), - lo(0x0008, 0x103e, 'Synthetic cine'), us(0x0028, 0x0002, 1), cs(0x0028, 0x0004, 'MONOCHROME2'), is(0x0028, 0x0008, String(numberOfFrames)), diff --git a/tests/specs/utils.ts b/tests/specs/utils.ts index 01532ec11..2ee03a8d4 100644 --- a/tests/specs/utils.ts +++ b/tests/specs/utils.ts @@ -299,6 +299,40 @@ export async function useCachedSample(dataset: { ); } +/** Drops local files onto the open app using its files-list import path. */ +export async function dropFiles(filePaths: string[]) { + const encoded = filePaths.map((filePath) => ({ + name: path.basename(filePath), + base64: fs.readFileSync(filePath).toString('base64'), + })); + const dropped = await browser.execute( + (files: Array<{ name: string; base64: string }>) => { + const transfer = new DataTransfer(); + files.forEach(({ name, base64 }) => { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i += 1) + bytes[i] = binary.charCodeAt(i); + transfer.items.add(new File([bytes], name)); + }); + + const target = document.querySelector('#app-container'); + if (!target) return false; + + const drop = new Event('drop', { bubbles: true, cancelable: true }); + // Synthetic items have no filesystem entry, so use the files list. + Object.defineProperty(drop, 'dataTransfer', { + value: { items: null, files: transfer.files }, + }); + // dispatchEvent reports preventDefault, not delivery. + target.dispatchEvent(drop); + return true; + }, + encoded + ); + expect(dropped).toBe(true); +} + /** Loads a file into the page already open, through the Open files dialog. */ export async function openThroughDialog( filePath: string, diff --git a/tests/unit/octFixture.ts b/tests/unit/octFixture.ts index 1e818edb7..279fa52ee 100644 --- a/tests/unit/octFixture.ts +++ b/tests/unit/octFixture.ts @@ -1,9 +1,21 @@ import dicomParser from 'dicom-parser'; -import { Chunk } from '@/src/core/streaming/chunk'; -import DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; -import { DicomFileMetaLoader } from '@/src/core/streaming/dicom/dicomFileMetaLoader'; -import { DicomFileDataLoader } from '@/src/core/streaming/dicom/dicomFileDataLoader'; -import { Tags, toDicomParserKey } from '@/src/core/dicomTags'; +import { + readInstance, + type Instance, +} from '@/packages/dicom/core/instance/readInstance'; +import { fromBlob } from '@/packages/dicom/core/source/byteSource'; +import { readGeometryFacts } from '@/packages/dicom/core/collections/instanceFacts'; +import type { DicomCollection } from '@/packages/dicom/core/collections/planDicomCollections'; +import { allocateVolume } from '@/packages/dicom/core/volume/allocateVolume'; +import { + createDicomRuntime, + type PixelDecoder, +} from '@/packages/dicom/core/runtime/createDicomRuntime'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; +import { + Tags, + toDicomParserKey, +} from '@/packages/dicom/core/metadata/dicomTags'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useViewStore } from '@/src/store/views'; import { untilLoaded } from '@/src/composables/untilLoaded'; @@ -14,7 +26,7 @@ import { overwriteDicomString, } from '../fixtures/oct/dicom'; -/** Reads the named VolView tags, standing in for the itk-wasm tag reader. */ +/** Reads raw named tags for assertions, independently of the structured loader. */ export async function readDicomTags(file: Blob) { const data = dicomParser.parseDicom( new Uint8Array(await file.arrayBuffer()), @@ -32,8 +44,50 @@ export async function readDicomTags(file: Blob) { }); } -/** Uses synthetic pixels and production chunk/file loaders without a browser WASM worker. */ -export function createOCTFixture( +/** Reads a file's header the way the importer does, on the main thread. */ +export const readFixtureInstance = (file: Blob) => + readInstance(fromBlob(file), new AbortController().signal); + +/** + * Allocates these instances in the given order as one volume. Fixtures keep + * deliberate groups, so geometry is judged by allocation, not by the planner. + */ +export function volumeOf(instances: Instance[]) { + const { orientation } = readGeometryFacts(instances[0].dataset); + const allocation = allocateVolume({ + id: 'fixture', + members: instances, + collection: { orientation } as DicomCollection, + }); + if (allocation.kind !== 'volume') + throw new Error(`Expected a volume, got ${allocation.kind}`); + return allocation.volume; +} + +// Decodes every frame of an uncompressed little endian 16 bit instance. +const decodeOCT: PixelDecoder = async ({ bytes }) => { + const data = dicomParser.parseDicom(bytes); + const pixel = data.elements.x7fe00010; + const values = new DataView( + bytes.buffer, + bytes.byteOffset + pixel.dataOffset, + pixel.length + ); + return { + size: [ + data.uint16('x00280011')!, + data.uint16('x00280010')!, + data.intString('x00280008')!, + ], + data: Uint16Array.from({ length: pixel.length / 2 }, (_, index) => + values.getUint16(index * 2, true) + ), + imageType: { components: data.uint16('x00280002')! }, + }; +}; + +/** Uses synthetic pixels and the production header reader without a WASM worker. */ +export async function createOCTFixture( options: { scanPattern?: string; deferDecode?: boolean } = {} ) { const bytes = Uint8Array.from(createSyntheticOCT()); @@ -45,46 +99,23 @@ export function createOCTFixture( options.scanPattern ); } - const file = new File([bytes], 'synthetic-oct.dcm'); - const chunk = new Chunk({ - metaLoader: new DicomFileMetaLoader(file, readDicomTags), - dataLoader: new DicomFileDataLoader(file), - }); + const instance = await readFixtureInstance( + new File([bytes], 'synthetic-oct.dcm') + ); let releaseDecode = () => {}; const decodeGate = new Promise((resolve) => { releaseDecode = resolve; }); if (!options.deferDecode) releaseDecode(); - const image = new DicomChunkImage({ - splitAndSort: async (chunks) => ({ fixture: chunks }), - readDicomImage: async (input) => { - await decodeGate; - const source = new Uint8Array(await input.arrayBuffer()); - const data = dicomParser.parseDicom(source); - const pixel = data.elements.x7fe00010; - const values = new DataView( - source.buffer, - pixel.dataOffset, - pixel.length - ); - const scalars = Uint16Array.from( - { length: pixel.length / 2 }, - (_, index) => values.getUint16(index * 2, true) - ); - return { - image: { - size: [ - data.uint16('x00280011')!, - data.uint16('x00280010')!, - data.intString('x00280008')!, - ], - data: scalars, - imageType: { components: data.uint16('x00280002')! }, - }, - }; - }, + const image = new DicomVolumeImage({ + runtime: createDicomRuntime({ + decoder: async (request, signal) => { + await decodeGate; + return decodeOCT(request, signal); + }, + }), }); - return { image, chunk, releaseDecode }; + return { image, instance, releaseDecode }; } /** Replaces the first layout view with an active En face view of `dataID`. */ @@ -107,12 +138,10 @@ export async function loadOCT( id = 'retina-oct', options: Parameters[0] = {} ) { - const fixture = createOCTFixture(options); + const fixture = await createOCTFixture(options); releases.push(fixture.releaseDecode); + fixture.image.setVolume(volumeOf([fixture.instance])); useImageCacheStore().addProgressiveImage(fixture.image, { id }); - await fixture.chunk.loadMeta(); - await fixture.image.addChunks([fixture.chunk]); - fixture.image.startLoad(); if (!options.deferDecode) await untilLoaded(id); return id; } diff --git a/tsconfig.json b/tsconfig.json index 1b262cfbe..5a2d8c7b1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -24,17 +24,11 @@ "@wdio/visual-service" ], "paths": { - "@/*": [ - "./*" - ] + "@/*": ["./*"], + "@volview/dicom/core/*": ["./packages/dicom/core/*"], + "@volview/dicom/vtk/*": ["./packages/dicom/vtk/*"] }, - "lib": [ - "esnext", - "dom", - "dom.iterable", - "scripthost", - "WebWorker" - ] + "lib": ["esnext", "dom", "dom.iterable", "scripthost", "WebWorker"] }, "include": [ "src/**/*.ts", @@ -43,11 +37,10 @@ "backend-contract/**/*.ts", "test/**/*.ts", "tests/**/*.ts", - "tests/**/*.tsx" - ], - "exclude": [ - "node_modules" + "tests/**/*.tsx", + "packages/dicom/**/*.ts" ], + "exclude": ["node_modules", "packages/dicom/dist"], "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" diff --git a/vite.config.ts b/vite.config.ts index d17b0d6a1..64a6423cf 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -246,13 +246,6 @@ export default defineConfig({ ), dest: 'itk/pipelines', }, - { - src: resolvePath( - rootDir, - 'src/io/itk-dicom/emscripten-build/**/dicom*' - ), - dest: 'itk/pipelines', - }, { src: resolvePath( rootDir, @@ -289,6 +282,9 @@ export default defineConfig({ environment: 'happy-dom', // canvas support. See: https://github.com/vitest-dev/vitest/issues/740 maxWorkers: 1, + // A store that outlives an import must not pin its chunks, which only a + // collection proves. + execArgv: ['--expose-gc'], server: { deps: { inline: ['vuetify'], From 3da5bf9a509139e17c8fd990a890374ea40cb6bf Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 13 Nov 2026 09:10:50 -0500 Subject: [PATCH 02/32] refactor(dicom): simplify the loading module Remove the standalone package build. packages/dicom is a plain directory whose public surface is core/index.ts and vtk/index.ts, enforced by lint. The browser test pages build straight from source. Load every unit of pixels one way. Native frames and GDCM are both pixel decoders that plan units from a header, the decoder table lists candidates per transfer syntax in preference order, and loadVolume has one read, decode and write path. A decoder's units must cover every frame exactly once. Pixels are written when a decode completes and a slice is marked loaded when its update is yielded. Let the plan say what a collection is. Registry updates carry whether a collection is an image or a segmentation and whether it is new, unchanged or changed, so allocateVolume returns a Volume and importInstances plans and commits synchronously. Decide cine from the header. A clip is built from its instance, reads its pixel bytes when loading starts, and cuts encapsulated frames with splitEncapsulatedFrames, so dicom-parser is no longer a dependency. A clip whose pixel data cannot be read now fails as a clip at load instead of falling back to a volume import, and malformed encapsulated streams throw. Keep only DICOM in the module. The URI fetcher returns to src/core/streaming, itk-wasm loads when GDCM first decodes so the core entry point imports in Node, and core may import only relative paths, comlink, dcmjs and itk-wasm. --- .github/workflows/checks.yml | 4 +- .gitignore | 2 - eslint.config.js | 44 +- package-lock.json | 8 - package.json | 7 +- packages/dicom/README.md | 459 ++++++++------ packages/dicom/__tests__/boundaries.spec.ts | 105 ++-- .../__tests__/instanceRegistry.spec.ts | 78 ++- .../__tests__/registryAcrossImports.spec.ts | 48 +- .../core/collections/assignCollectionIds.ts | 6 - .../dicom/core/collections/instanceFacts.ts | 2 +- .../dicom/core/collections/instanceKey.ts | 2 +- .../core/collections/instanceRegistry.ts | 74 ++- .../core/collections/planDicomCollections.ts | 10 +- .../core/collections/reconstructVolume.ts | 10 +- .../__tests__/byteDeque.spec.ts | 0 .../__tests__/dicomHeaderEncodings.spec.ts | 8 +- .../__tests__/streamingByteReader.spec.ts | 2 +- .../core/{streaming => header}/byteDeque.ts | 0 .../dicom => header}/dicomParser.ts | 18 +- .../dicom => header}/readDicomHeader.ts | 4 +- .../streamingByteReader.ts | 0 packages/dicom/core/index.ts | 100 +++ .../instance/__tests__/instanceFixture.ts | 19 - .../instance/__tests__/readInstance.spec.ts | 2 +- .../__tests__/readInstanceSources.spec.ts | 2 +- packages/dicom/core/instance/readInstance.ts | 4 +- .../metadata/__tests__/dcmjsParser.spec.ts | 4 +- .../metadata/__tests__/dicomDataset.spec.ts | 2 +- .../metadata/__tests__/dicomLayout.spec.ts | 2 +- .../metadata/__tests__/metadataReader.spec.ts | 2 +- .../__tests__/ultrasoundRegion.spec.ts | 4 +- packages/dicom/core/metadata/datasetAccess.ts | 5 +- packages/dicom/core/metadata/dcmjs.d.ts | 4 + packages/dicom/core/metadata/dicomDataset.ts | 8 +- packages/dicom/core/metadata/dicomLayout.ts | 2 +- packages/dicom/core/metadata/dicomTags.ts | 4 +- .../dicom/core/metadata/functionalGroups.ts | 6 +- .../dicom/core/metadata/spatialMetadata.ts | 2 +- .../dicom => metadata}/ultrasoundRegion.ts | 52 +- .../pixels/__tests__/decoderTable.spec.ts | 93 ++- .../__tests__/encapsulatedFrames.spec.ts | 187 ++++++ packages/dicom/core/pixels/decoderTable.ts | 192 +++--- .../dicom/core/pixels/encapsulatedFrames.ts | 139 +++++ packages/dicom/core/pixels/frameIndex.ts | 6 +- packages/dicom/core/pixels/nativeFrame.ts | 36 +- packages/dicom/core/pixels/pixelDecoder.ts | 64 ++ .../__tests__/decoderCalibration.spec.ts | 34 +- .../runtime/__tests__/dicomRuntime.spec.ts | 143 +++-- .../__tests__/requestPool.spec.ts | 0 .../dicom/core/runtime/createDicomRuntime.ts | 145 +---- packages/dicom/core/runtime/decoder.ts | 101 --- packages/dicom/core/runtime/gdcmDecoder.ts | 203 +++++++ .../{streaming => runtime}/requestPool.ts | 0 .../core/source/__tests__/byteSource.spec.ts | 34 +- .../__tests__/parseContentRangeHeader.spec.ts | 0 packages/dicom/core/source/byteSource.ts | 8 +- .../core/{streaming => source}/httpCodes.ts | 0 .../parseContentRangeHeader.ts | 1 - packages/dicom/core/utils.ts | 35 ++ packages/dicom/core/utils/abort.ts | 37 -- .../volume/__tests__/allocateVolume.spec.ts | 25 +- .../volume/__tests__/functionalGroups.spec.ts | 51 +- .../core/volume/__tests__/loadFrames.spec.ts | 198 +++++- .../core/volume/__tests__/loadVolume.spec.ts | 132 +++- .../volume/__tests__/pixelValidation.spec.ts | 7 +- .../core/volume/__tests__/volumeFixture.ts | 41 +- packages/dicom/core/volume/allocateVolume.ts | 33 +- packages/dicom/core/volume/loadVolume.ts | 574 +++++++++--------- packages/dicom/core/volume/pixelValidation.ts | 72 +-- .../dicom/core/volume/ultrasoundSpacing.ts | 2 +- packages/dicom/core/volume/volumeLayout.ts | 26 +- packages/dicom/package.json | 38 -- packages/dicom/scripts/build.mjs | 95 --- packages/dicom/scripts/check-consumers.mjs | 97 --- packages/dicom/tsconfig.build.json | 23 - .../dicom/vtk/__tests__/thumbnail.spec.ts | 5 +- .../dicom/vtk/__tests__/volumeImage.spec.ts | 5 +- packages/dicom/vtk/index.ts | 9 + packages/dicom/vtk/thumbnail.ts | 2 +- .../ControlsStripTools.enFace.spec.ts | 2 +- ...tientStudyVolumeBrowser.thumbnails.spec.ts | 52 +- src/components/__tests__/PlayControls.spec.ts | 5 +- .../vtk/VtkBaseVolumeRepresentation.vue | 2 +- src/core/cine/DicomCineImage.ts | 135 ++-- .../cine/__tests__/DicomCineImage.spec.ts | 293 +++++---- src/core/cine/__tests__/cineFixtures.ts | 119 ++-- src/core/cine/__tests__/cineInstance.spec.ts | 253 ++++++++ .../cine/__tests__/parseCineDicom.spec.ts | 330 ---------- src/core/cine/cineInstance.ts | 194 ++++++ src/core/cine/parseCineDicom.ts | 304 ---------- src/core/progressiveImage.ts | 2 +- .../__tests__/cachedStreamFetcher.spec.ts | 15 +- .../__tests__/dicomVolumeImage.spec.ts | 68 +-- .../core/streaming/cachedStreamFetcher.ts | 8 +- .../dicom/__tests__/octMetadata.spec.ts | 242 +++----- .../__tests__/octStructuredMetadata.spec.ts | 15 +- src/core/streaming/dicom/octDataset.ts | 17 +- src/core/streaming/dicom/octMetadata.ts | 34 +- src/core/streaming/dicom/octMetadataTags.ts | 3 +- src/core/streaming/dicom/seriesGeometry.ts | 2 +- src/core/streaming/dicomVolumeImage.ts | 52 +- src/core/streaming/httpCodes.ts | 9 + .../dicom => src}/core/streaming/types.ts | 0 src/enface/__tests__/availability.spec.ts | 2 +- src/enface/__tests__/calibration.spec.ts | 7 +- src/enface/__tests__/dicomMetadataFixture.ts | 2 +- src/enface/__tests__/inputCalibration.spec.ts | 2 +- .../__tests__/occupiedDepthSupport.spec.ts | 12 +- src/enface/__tests__/seriesGeometry.spec.ts | 67 +- src/enface/availability.ts | 2 +- src/enface/occupiedDepthSupport.ts | 4 +- .../readDicomTags.differential.spec.ts | 3 +- src/io/__tests__/readDicomTags.spec.ts | 13 +- src/io/__tests__/readDicomTagsFixtures.ts | 339 +---------- src/io/import/__tests__/dataSource.spec.ts | 2 +- .../__tests__/dicomImportResults.spec.ts | 113 +--- .../__tests__/dicomInstanceProvenance.spec.ts | 27 +- src/io/import/dataSource.ts | 4 +- src/io/import/importDataSources.ts | 105 ++-- .../processors/__tests__/handleDicom.spec.ts | 71 ++- src/io/import/processors/handleDicom.ts | 17 +- src/io/import/processors/openUriStream.ts | 2 +- src/io/import/processors/updateUriType.ts | 2 +- src/io/magic.ts | 2 +- src/io/readDicomTags.ts | 15 +- .../__tests__/artifactParentRestore.spec.ts | 30 +- .../datasets-dicom-acquisition-split.spec.ts | 85 ++- .../__tests__/datasets-dicom-cine.spec.ts | 188 ++---- .../__tests__/datasets-dicom-geometry.spec.ts | 20 +- .../__tests__/datasets-dicom-lifetime.spec.ts | 4 +- .../__tests__/datasets-dicom-reimport.spec.ts | 101 ++- .../datasets-dicom-transaction.spec.ts | 209 ++----- src/store/__tests__/dicomImportFixtures.ts | 66 +- src/store/__tests__/dicomTagFixtures.ts | 2 +- .../__tests__/duplicateDatasetSave.spec.ts | 5 +- src/store/datasets-dicom.ts | 235 +++---- src/store/datasets.ts | 10 +- src/store/dicom-runtime.ts | 2 +- src/store/dicom-web/dicom-web-store.ts | 2 +- src/types/image.ts | 2 +- src/utils/__tests__/dicomWindowRange.spec.ts | 2 +- src/utils/dicom/windowMetadata.ts | 4 +- src/utils/dicomWindowRange.ts | 2 +- src/utils/index.ts | 13 + src/utils/parseContentRangeHeader.ts | 40 ++ .../byteSourceFixtures.ts | 17 +- tests/dicomDataset.ts | 23 +- tests/dicomOrientationFixtures.ts | 10 +- tests/{dicomConsumer.ts => dicomPages.ts} | 6 +- tests/dicomSourceFixtures.ts | 59 +- tests/dicomVolumeFixtures.ts | 21 + .../composition.html | 0 .../composition.ts | 6 +- .../compositionReference.py | 0 .../{dicom-consumer => dicom-pages}/core.html | 4 +- .../{dicom-consumer => dicom-pages}/core.ts | 15 +- .../corpus.html | 4 +- .../{dicom-consumer => dicom-pages}/corpus.ts | 14 +- .../describeVolume.ts | 2 +- .../enhancedFixtures.ts | 0 .../fixtureData.ts | 0 .../loadVolume.ts | 28 +- .../parity.html | 0 .../{dicom-consumer => dicom-pages}/parity.ts | 73 ++- .../server.mjs | 82 ++- .../{dicom-consumer => dicom-pages}/shared.ts | 32 +- .../{dicom-consumer => dicom-pages}/vtk.html | 4 +- .../{dicom-consumer => dicom-pages}/vtk.ts | 0 tests/fixtures/oct/dicom.ts | 325 ++++++---- tests/fixtures/oct/padding.ts | 49 +- tests/fixtures/oct/volumes.ts | 61 +- tests/nativePixelDicom.ts | 32 +- tests/specs/dicom-frame-reconstruction.e2e.ts | 17 +- ...ckage.e2e.ts => dicom-module-pages.e2e.ts} | 18 +- tests/specs/dicom-native-parity.e2e.ts | 12 +- tests/specs/dicom-spacing-details.e2e.ts | 2 +- tests/specs/dicom-volume-composition.e2e.ts | 14 +- tests/specs/dicom-volume-corpus.e2e.ts | 15 +- tests/specs/dicomElementFixtures.ts | 337 ++++++++++ tests/specs/oct-en-face.e2e.ts | 11 +- tests/specs/pet-ct-sample.e2e.ts | 55 +- tests/specs/syntheticDicom.ts | 64 +- tests/unit/octFixture.ts | 99 +-- tsconfig.json | 6 +- 185 files changed, 5019 insertions(+), 4497 deletions(-) rename packages/dicom/core/{streaming => header}/__tests__/byteDeque.spec.ts (100%) rename packages/dicom/core/{streaming/dicom => header}/__tests__/dicomHeaderEncodings.spec.ts (94%) rename packages/dicom/core/{streaming => header}/__tests__/streamingByteReader.spec.ts (97%) rename packages/dicom/core/{streaming => header}/byteDeque.ts (100%) rename packages/dicom/core/{streaming/dicom => header}/dicomParser.ts (96%) rename packages/dicom/core/{streaming/dicom => header}/readDicomHeader.ts (98%) rename packages/dicom/core/{streaming => header}/streamingByteReader.ts (100%) create mode 100644 packages/dicom/core/index.ts delete mode 100644 packages/dicom/core/instance/__tests__/instanceFixture.ts rename packages/dicom/core/{streaming/dicom => metadata}/__tests__/ultrasoundRegion.spec.ts (95%) rename packages/dicom/core/{streaming/dicom => metadata}/ultrasoundRegion.ts (65%) create mode 100644 packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts create mode 100644 packages/dicom/core/pixels/encapsulatedFrames.ts create mode 100644 packages/dicom/core/pixels/pixelDecoder.ts rename packages/dicom/core/{streaming => runtime}/__tests__/requestPool.spec.ts (100%) delete mode 100644 packages/dicom/core/runtime/decoder.ts create mode 100644 packages/dicom/core/runtime/gdcmDecoder.ts rename packages/dicom/core/{streaming => runtime}/requestPool.ts (100%) rename packages/dicom/core/{utils => source}/__tests__/parseContentRangeHeader.spec.ts (100%) rename packages/dicom/core/{streaming => source}/httpCodes.ts (100%) rename packages/dicom/core/{utils => source}/parseContentRangeHeader.ts (94%) delete mode 100644 packages/dicom/core/utils/abort.ts delete mode 100644 packages/dicom/package.json delete mode 100644 packages/dicom/scripts/build.mjs delete mode 100644 packages/dicom/scripts/check-consumers.mjs delete mode 100644 packages/dicom/tsconfig.build.json rename src/core/streaming/__tests__/dicomThumbnail.spec.ts => packages/dicom/vtk/__tests__/thumbnail.spec.ts (97%) create mode 100644 packages/dicom/vtk/index.ts create mode 100644 src/core/cine/__tests__/cineInstance.spec.ts delete mode 100644 src/core/cine/__tests__/parseCineDicom.spec.ts create mode 100644 src/core/cine/cineInstance.ts delete mode 100644 src/core/cine/parseCineDicom.ts rename {packages/dicom => src}/core/streaming/__tests__/cachedStreamFetcher.spec.ts (92%) rename {packages/dicom => src}/core/streaming/cachedStreamFetcher.ts (97%) create mode 100644 src/core/streaming/httpCodes.ts rename {packages/dicom => src}/core/streaming/types.ts (100%) create mode 100644 src/utils/parseContentRangeHeader.ts rename packages/dicom/core/source/__tests__/sourceFixtures.ts => tests/byteSourceFixtures.ts (74%) rename tests/{dicomConsumer.ts => dicomPages.ts} (74%) create mode 100644 tests/dicomVolumeFixtures.ts rename tests/fixtures/{dicom-consumer => dicom-pages}/composition.html (100%) rename tests/fixtures/{dicom-consumer => dicom-pages}/composition.ts (94%) rename tests/fixtures/{dicom-consumer => dicom-pages}/compositionReference.py (100%) rename tests/fixtures/{dicom-consumer => dicom-pages}/core.html (84%) rename tests/fixtures/{dicom-consumer => dicom-pages}/core.ts (84%) rename tests/fixtures/{dicom-consumer => dicom-pages}/corpus.html (66%) rename tests/fixtures/{dicom-consumer => dicom-pages}/corpus.ts (78%) rename tests/fixtures/{dicom-consumer => dicom-pages}/describeVolume.ts (92%) rename tests/fixtures/{dicom-consumer => dicom-pages}/enhancedFixtures.ts (100%) rename tests/fixtures/{dicom-consumer => dicom-pages}/fixtureData.ts (100%) rename tests/fixtures/{dicom-consumer => dicom-pages}/loadVolume.ts (56%) rename tests/fixtures/{dicom-consumer => dicom-pages}/parity.html (100%) rename tests/fixtures/{dicom-consumer => dicom-pages}/parity.ts (67%) rename tests/fixtures/{dicom-consumer => dicom-pages}/server.mjs (59%) rename tests/fixtures/{dicom-consumer => dicom-pages}/shared.ts (69%) rename tests/fixtures/{dicom-consumer => dicom-pages}/vtk.html (85%) rename tests/fixtures/{dicom-consumer => dicom-pages}/vtk.ts (100%) rename tests/specs/{dicom-package.e2e.ts => dicom-module-pages.e2e.ts} (71%) create mode 100644 tests/specs/dicomElementFixtures.ts diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 4ad57ece2..88571e12c 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -18,11 +18,9 @@ jobs: cache: npm - run: npm ci - name: Enforce code style - run: npx prettier --list-different "src/**/*.[jt]s" "tests/**/*.[jt]s" "src/**/*.vue" "packages/dicom/**/*.{ts,mjs,json,md}" + run: npx prettier --list-different "src/**/*.[jt]s" "tests/**/*.[jt]s" "src/**/*.vue" "packages/dicom/**/*.{ts,md}" - name: Lint run: npm run lint - - name: Build independent DICOM consumers - run: npm run dicom:check - name: Quality ratchets # A file may not get worse than it is on the pull request's target branch. if: github.event_name == 'pull_request' diff --git a/.gitignore b/.gitignore index f1546634b..dd9be9f03 100644 --- a/.gitignore +++ b/.gitignore @@ -36,5 +36,3 @@ reports .github/copilot CLAUDE.md .claude/ - -/packages/dicom/dist/ diff --git a/eslint.config.js b/eslint.config.js index f7de6d5fe..fb460209d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -64,9 +64,11 @@ const ownFeatureExceptPure = (feature) => { const upperLayerMessage = (feature) => `The ${feature.dir} pure layer must not import stores, components, or upper feature modules. Dependencies point downward only.`; +// The DICOM module's public surface is its two entry points, core and vtk. const dicomPublicSurface = { - regex: '^@/packages/dicom/(?!core/.+|vtk/.+)', - message: 'Import the defining DICOM core or vtk module directly.', + regex: '(^|/)packages/dicom(?!/(core|vtk)$)', + message: + 'Import the DICOM module only through @/packages/dicom/core or @/packages/dicom/vtk.', }; const featureBoundaries = (features) => { @@ -185,7 +187,6 @@ export default tseslint.config( 'src/io/resample/emscripten-build/**', '**/*.d.ts', 'dist/**', - 'packages/dicom/dist/**', 'node_modules/**', ], }, @@ -408,8 +409,14 @@ export default tseslint.config( ], }, }, - ...['core', 'vtk'].map((entry) => ({ - files: [`packages/dicom/${entry}/**/*.{js,ts}`], + { + files: ['tests/**/*.{js,ts,mjs}'], + rules: { + 'no-restricted-imports': ['error', { patterns: [dicomPublicSurface] }], + }, + }, + { + files: ['packages/dicom/core/**/*.{js,ts}'], ignores: ['**/__tests__/**'], rules: { 'no-restricted-imports': [ @@ -417,17 +424,32 @@ export default tseslint.config( { patterns: [ { - regex: - entry === 'core' - ? '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/|@kitware/vtk\\.js(?:/|$))' - : '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/)', + regex: '^(?!\\.\\.?/|(comlink|dcmjs|itk-wasm)$)', message: - 'DICOM package internals use relative imports and cannot depend on application state or UI frameworks. Core cannot depend on vtk.js.', + 'DICOM core imports only relative paths and comlink, dcmjs and itk-wasm. A new dependency is a deliberate change to this list.', }, ], }, ], }, - })), + }, + { + files: ['packages/dicom/vtk/**/*.{js,ts}'], + ignores: ['**/__tests__/**'], + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/)', + message: + 'DICOM module internals use relative imports and cannot depend on application state or UI frameworks.', + }, + ], + }, + ], + }, + }, eslintConfigPrettier ); diff --git a/package-lock.json b/package-lock.json index 1a73d11e6..a827a3940 100644 --- a/package-lock.json +++ b/package-lock.json @@ -47,7 +47,6 @@ "cors": "^2.8.5", "cross-env": "^10.1.0", "dcmjs": "^0.52.0", - "dicom-parser": "^1.8.21", "dicomweb-client-typed": "^0.8.6", "eslint": "^9.39.1", "eslint-config-prettier": "^10.1.8", @@ -10680,13 +10679,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/dicom-parser": { - "version": "1.8.21", - "resolved": "https://registry.npmjs.org/dicom-parser/-/dicom-parser-1.8.21.tgz", - "integrity": "sha512-lYCweHQDsC8UFpXErPlg86Px2A8bay0HiUY+wzoG3xv5GzgqVHU3lziwSc/Gzn7VV7y2KeP072SzCviuOoU02w==", - "dev": true, - "license": "MIT" - }, "node_modules/dicomweb-client-typed": { "version": "0.8.6", "resolved": "https://registry.npmjs.org/dicomweb-client-typed/-/dicomweb-client-typed-0.8.6.tgz", diff --git a/package.json b/package.json index d143bc6f4..9a225bec0 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "test:e2e:chrome": "cross-env VITE_SHOW_SAMPLE_DATA=true npm run build && cross-env HEADED=0 wdio run ./wdio.chrome.conf.ts", "test:e2e:chrome:skip-build": "cross-env HEADED=0 wdio run ./wdio.chrome.conf.ts", "test:e2e:dev": "cross-env HEADED=0 VITE_SHOW_SAMPLE_DATA=true concurrently -P \"npm run dev\" \"wdio run ./wdio.dev.conf.ts --watch {@}\"", - "lint": "vue-tsc --noEmit && eslint \"src/**/*.{js,ts,vue}\" \"tests/**/*.{js,ts}\" \"scripts/**/*.mjs\" \"packages/dicom/**/*.{js,ts,mjs}\"", + "lint": "vue-tsc --noEmit && eslint \"src/**/*.{js,ts,vue}\" \"tests/**/*.{js,ts,mjs}\" \"scripts/**/*.mjs\" \"packages/dicom/**/*.ts\"", "build:all": "npm run build:resample && npm run build", "build:resample": "itk-wasm -s src/io/resample/ build ", "build:resample:debug": "itk-wasm -s src/io/resample/ build -- -DCMAKE_BUILD_TYPE=Debug", @@ -34,9 +34,7 @@ "prettify": "prettier --write src tests packages/dicom", "docs:dev": "vitepress dev docs", "docs:build": "vitepress build docs", - "docs:preview": "vitepress preview docs", - "dicom:build": "node packages/dicom/scripts/build.mjs", - "dicom:check": "npm run dicom:build && node packages/dicom/scripts/check-consumers.mjs" + "docs:preview": "vitepress preview docs" }, "devDependencies": { "@commitlint/cli": "^21.0.0", @@ -78,7 +76,6 @@ "cors": "^2.8.5", "cross-env": "^10.1.0", "dcmjs": "^0.52.0", - "dicom-parser": "^1.8.21", "dicomweb-client-typed": "^0.8.6", "eslint": "^9.39.1", "eslint-config-prettier": "^10.1.8", diff --git a/packages/dicom/README.md b/packages/dicom/README.md index 13b48a597..9f0202dbd 100644 --- a/packages/dicom/README.md +++ b/packages/dicom/README.md @@ -1,43 +1,56 @@ # Browser DICOM module -This private directory uses VolView's root install, lockfile and checks. It has -no workspace install or release workflow. VolView imports defining source -modules directly; the root npm distribution includes the core and vtk source -files alongside `dist`, `src` and `backend-contract`. Package tests and -standalone build output are excluded from that distribution. - -- `core/`: byte sources, header reading into structured `DicomDataset` - metadata, collection planning with stable identity, volume allocation and - loading into calibrated typed arrays, and the runtime that owns workers and - requests. It has no Vue, Pinia or vtk.js dependency. -- `vtk/`: a thin adapter that shows a core `Volume` as a `vtkImageData`. - vtk.js is an optional peer, required only by consumers of these modules. - -The package exports concrete module subpaths under `@volview/dicom/core/*` and -`@volview/dicom/vtk/*`; there are no aggregate entry points. - -VolView owns its reactive wrappers, messages, browser state, selections, -annotations, layers, import handling and session provenance. +Reads DICOM instances from Blobs or URLs, groups them into collections and +loads calibrated pixel volumes in the browser. It is a directory of VolView +source, not a separate package. + +## Entry points + +- `@/packages/dicom/core`: sources, instances, datasets, collections, volume + allocation and loading, decoders and the runtime. No Vue, Pinia, vtk.js or + VolView application code. +- `@/packages/dicom/vtk`: shows a core `Volume` as a `vtkImageData` and makes + slice thumbnails. + +Each `index.ts` lists every exported name, grouped by topic. Lint lets `src` +and `tests` import the module only through these two paths, by alias or by +relative path. Inside the module, `core` imports only relative paths and its +npm dependencies (`comlink`, `dcmjs`, `itk-wasm`); `vtk` adds vtk.js and +gl-matrix. `__tests__/boundaries.spec.ts` checks that relative imports stay +inside the module, that `core` does not reach `vtk`, that no module file +imports an entry point, and that module tests, with the shared fixtures they +import from `tests/`, reach no VolView application code. + +| Directory | Holds | +| ------------------ | ------------------------------------------------------------------------ | +| `core/source` | byte sources for Blobs and URLs, HTTP range handling | +| `core/header` | the streaming reader that finds Pixel Data and the header parser over it | +| `core/metadata` | datasets, tags, functional groups, rescale, spacing, ultrasound regions | +| `core/instance` | `readInstance` | +| `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 | +| `vtk` | the vtk.js image and thumbnails | ## Values and effects -Instances, plans and volumes are plain values. Only the runtime holds -resources, and only it has `dispose()`. Every asynchronous operation takes an -`AbortSignal`; aborting it is the whole of cancellation. +Instances, collection updates and volumes are plain values. Only the runtime +holds resources, and only it has `dispose()`. Every asynchronous operation +takes an `AbortSignal`; aborting it is the whole of cancellation. Importing +an entry point starts no worker and touches no DOM. ```ts -import { createDicomRuntime } from '@volview/dicom/core/runtime/createDicomRuntime'; -import { fromBlob, fromUrl } from '@volview/dicom/core/source/byteSource'; import { + allocateVolume, + createDicomRuntime, emptyRegistry, + fromBlob, + fromUrl, + loadVolume, registerInstances, -} from '@volview/dicom/core/collections/instanceRegistry'; -import { allocateVolume } from '@volview/dicom/core/volume/allocateVolume'; -import { loadVolume } from '@volview/dicom/core/volume/loadVolume'; -import { - applyVolumeUpdate, - toVtkImageData, -} from '@volview/dicom/vtk/volumeImage'; +} from '@/packages/dicom/core'; +import { applyVolumeUpdate, toVtkImageData } from '@/packages/dicom/vtk'; const runtime = createDicomRuntime({ assets: { @@ -56,192 +69,256 @@ const instances = await Promise.all( ); const { state, updates } = registerInstances(emptyRegistry, instances); -const allocation = allocateVolume(updates[0]); -if (allocation.kind === 'volume') { - const { volume } = allocation; +const [update] = updates; +if (update.kind === 'image') { + const volume = allocateVolume(update); const image = toVtkImageData(volume); - for await (const update of loadVolume(volume, { runtime, signal })) { - if ('error' in update) console.error(update.error); - else applyVolumeUpdate(image, volume, update); + for await (const loaded of loadVolume(volume, { runtime, signal })) { + if ('error' in loaded) console.error(loaded.error); + else applyVolumeUpdate(image, loaded); } } ``` -### Sources +## Sources -A `ByteSource` opens a fresh stream for every `read(signal, range?)` and holds -nothing open between reads. `fromBlob` reads slices of a Blob or File. +A `ByteSource` opens a fresh stream for every `read(signal, range?)` and +holds nothing open between reads. `fromBlob` reads slices of a Blob or File. `fromUrl` issues HTTP Range requests and accepts a server that ignores Range; pass `runtime.fetch` so requests share the runtime's pool, or any `fetch` for -authentication and other request policies. `readBytes(source, signal, range?)` -reads a source or range into memory. Decoded instances keep no bytes; read the -source again when original bytes are needed. `rangeSupport()` reports whether -a URL source's last ranged response honoured Range. Ranged URL reads bypass -the HTTP cache, since Chrome can answer a Range from an entry an earlier -cancelled read left behind with status 200 and only the range's bytes. - -### Instances - -`runtime.readInstance(source, signal)` reads only the header, stopping at Pixel -Data, and returns a frozen `Instance`: its source, dataset, Part 10 layout, -transfer syntax, ultrasound regions and where the Pixel Data element and its -value sit. The dataset omits private -attributes, including private elements nested in public sequences; use -`readDicomDataset` directly when they are needed. A source without a preamble -or file meta information is read with its transfer syntax assumed and reported -in `layout`. The runtime's `imageImportPolicy: 'skip-radiotherapy'` returns -after the Modality element of RT objects; `'complete-header'` (the default) -reads through the header. - -### Collections +authentication and other request policies. Its `rangeSupport()` reports +whether the latest ranged response honoured Range. Ranged URL reads bypass the +HTTP cache, since Chrome can answer a Range from an entry an earlier cancelled +read left behind with status 200 and only the range's bytes. +`readBytes(source, signal, range?)` reads a source or a range into memory. +Instances keep no bytes; read the source again when the original bytes are +needed. + +## Instances and datasets + +`runtime.readInstance(source, signal)` scans the header on the calling +thread, stopping where Pixel Data begins, parses the dataset in a worker and +returns a frozen `Instance`: its source, dataset, Part 10 layout, transfer +syntax, ultrasound regions and where the Pixel Data element and its value sit. +`readInstance` does both on the calling thread. +A source without a preamble or file meta information is read with its +transfer syntax assumed and reported in `layout`. The runtime's +`imageImportPolicy: 'skip-radiotherapy'` returns after the Modality element of +RT objects; `'complete-header'` (the default) reads through the header. + +The dataset omits private elements, including those nested in public +sequences; `readDicomDataset(bytes)` reads every element of a Part 10 file. +`getDatasetTag(dataset, tag)` returns an element's values as backslash +separated text, `getDatasetModality` the trimmed Modality, `sequenceItems` +the items of a sequence, and `trimDicomPadding` strips the space and NUL +padding DICOM text values carry. `Tags` names the attributes VolView reads; +tags may be written `ggggeeee` or `gggg|eeee`. `ultrasoundRegionsOf(dataset)` +reads every item of the Sequence of Ultrasound Regions. + +## Collections `registerInstances(state, instances)` is a pure reducer. It returns the next -`state`, the collections whose membership or label changed as `updates`, the -ids a replan dissolved as `removed`, and SOP Instance UIDs re-supplied with -conflicting geometry. Each update carries a stable `id` that starts with the -Series Instance UID, the planned `collection`, `members` in planned order and, -aligned with them, `provenance`: the batch's own instance wherever it -re-supplied one. The first registration of a SOP Instance UID is kept; -instances without one are identified by object. Abandoning an import is not -assigning the returned state. `forgetCollection(state, id)` drops a collection -and its instances so a later import plans them afresh; `isRegistered` checks -whether an object is the registered instance. - -### Volumes - -`allocateVolume(update, options, previous?)` allocates the buffer a planned -collection fills, or reports `{ kind: 'segmentation' }` for SEG, whose labels a -segmentation reader turns into its own image. A `Volume` holds a typed array, -dimensions, components, origin, row-major direction, spacing, spatial metadata, -reconstruction, members, allocation warnings and a per-slice `loaded` mask. -With `previous`, slices it already decoded are copied by instance identity, so -growing a volume never decodes them again. The buffer type comes from the -headers' rescaled value ranges. Ranges beyond 16 bit integers use Float32 -rather than Int32 or Uint32 while every value is within 2^24, and fractional -rescales use Float32 rather than Float64 while Bits Stored is at most 24 and -float32's spacing stays below the slope, since vtk.js converts any other -buffer type to float32 whole on every upload. Decoded values a Float32 volume -would round or merge are rejected. `irregularGeometry: 'preserve-order'` (the -default) keeps approximate spacing for irregular stacks; `'reject'` refuses -them. Neither resamples. Supplied slots must start at zero because the first -member anchors the origin; gaps such as `[0, 2]` are allowed. +`state`; `updates`, the collections of each touched series that are new or +changed, or that the batch re-supplied a member of; `removed`, the committed +ids a replan dissolved; and `conflictingInstanceUids`, SOP Instance UIDs +re-supplied with different geometry. The first registration of a SOP Instance +UID is kept; instances without one are identified by object. Abandoning an +import is not assigning the returned state. + +Each `InstanceCollectionUpdate` carries a stable `id` that starts with the +Series Instance UID, its `seriesKey`, the planned `collection`, `members` in +planned order and, aligned with them, `provenance`: the batch's own instance +wherever it re-supplied one. `kind` is `image`, or `segmentation` when the +first member's Modality is SEG; a segmentation reader turns those labels into +its own image. `change` says how the collection differs from what was last +committed under its id: `new`, `unchanged` (same members, key and geometry) or +`changed`. + +`forgetCollection(state, id)` drops a collection and its instances, so a later +import plans them afresh. `seriesKeyOf` gives the series an instance plans in. + +## Volumes and loading + +`allocateVolume(update, options?, previous?)` allocates the `Volume` an image +collection fills: a typed array, dimensions, components, origin, row-major +direction, spacing, spatial metadata, reconstruction, members, allocation +warnings and a per-slice `loaded` mask. With `previous`, slices it already +decoded are copied by instance identity, so growing a volume never decodes +them again. `irregularGeometry: 'preserve-order'` (the default) keeps +approximate spacing for irregular stacks; `'reject'` refuses them. Neither +resamples. Slots must start at zero because the first member anchors the +origin; gaps such as `[0, 2]` are allowed. + +The buffer type comes from the headers' rescaled value ranges +(`getVolumeBufferType(instancePixelFormats(dataset))` for one instance). +Integer ranges beyond 16 bits use Float32 rather than Int32 or Uint32 while +every value is within 2^24, and fractional rescales use Float32 rather than +Float64 while Bits Stored is at most 24 and float32's spacing stays below the +slope, since vtk.js converts any other buffer type to float32 whole on every +upload. Decoded values the buffer would round, merge or not hold are rejected. `loadVolume(volume, { runtime, signal, focus?, readAhead? })` is an async -generator of `{ slot, extent, range }` or `{ slot, extent, error }` updates. It -writes decoded pixels into `volume.data` and marks `volume.loaded`. A failure's -extent spans the slices it leaves unloaded, and loading continues. Units load -focus first and then coarse to fine across the stack (`pickNextSlot`); `focus` -is read before every read and decode, so moving it reorders the remaining -work. Reads run ahead of decoding: at most `readAhead` units, defaulting to -the runtime's request concurrency, are being read or waiting to decode. -Aborting `signal`, leaving the loop or disposing the runtime ends the -iteration without throwing. - -The unit is a frame wherever the runtime's decoder table can decode one -without a codec (`planDecode` in `core/pixels/decoderTable.ts`): each frame is -a ranged read from the Pixel Data value (`indexFrames`), decoded on the -calling thread (`decodeNativeFrame`). Every other instance is read and decoded -whole. Once a URL source shows that its server ignores Range, the remaining -frames of that instance come from one read instead of one download each; -until then its frames are read one at a time. - -### Runtime - -`createDicomRuntime(options)` owns the decoder table (`decoders`), the request pool (`requestConcurrency`, +generator of `{ slot, extent, range }` or `{ slot, extent, error }` updates. +It writes each unit's samples into `volume.data` as soon as they decode, and +marks its slices in `volume.loaded` only when its update is yielded, so a +consumer that awaits between updates never holds up decoding and never sees a +slice loaded before its update. Nothing is written after the load stops. A +failure's extent spans the slices it leaves unloaded, and loading continues. +Units load focus first, then coarse to fine across the stack; `focus` +(default `() => middleSlot(volume)`) is a function called before every read +and decode, so moving the focus reorders the remaining work. At most +`readAhead` units, defaulting to the runtime's `readConcurrency`, are being +read or waiting to decode, and at most `decodeConcurrency` decode at once. Aborting `signal`, leaving the loop or +disposing the runtime ends the iteration without throwing. + +## Decoders + +A `PixelDecoder` has a `name` and a `plan(instance, target)` that, from the +header alone, returns the `DecodeUnit`s it would load the instance in, or +`{ declined: reason }`. A unit covers consecutive frames: `firstFrame`, +`frames`, the byte `range` of the source to read (null for the whole source) +and `decode(bytes, signal)`, which returns `DecodedPixels`. A decoder's units +must cover the instance's frames exactly once, in any order; otherwise every +slice of that instance fails with an error naming the decoder. Every unit is +read, decoded, validated and written the same way. + +A `DecoderTable` lists candidate decoders per transfer syntax in preference +order, a `fallback` list for unlisted syntaxes, and syntax names for errors. +`planDecode(table, instance, target)` asks each candidate in turn; the first +that does not decline wins. The default table, `defaultDecoderTable(gdcm)`, +tries `nativeFrameDecoder` and then GDCM for Implicit and Explicit VR Little +Endian and Explicit VR Big Endian, sends other known syntaxes and unknown ones +to GDCM, and fails JPIP, video and JPEG XL syntaxes as known syntaxes without +a decoder. + +`nativeFrameDecoder` plans one ranged read per frame, located by +`indexFrames(instance)` from the header, and decodes on the calling thread. It +accepts only instances whose result is identical to GDCM's: MONOCHROME2 or +unscaled unsigned 8 bit RGB samples, 8, 16 or 32 bit words with Bits Stored +ending at High Bit (fewer stored bits only in 16 bit words), big endian only +for 16 bit words, one modality rescale for all frames, and no overlay, curve, +Modality LUT, palette or ICC data. GDCM plans the whole instance as one unit. Both +apply one modality transform to the entire instance and reject differing +per-frame slopes or intercepts. Once a URL source shows that its server +ignores Range, the remaining ranged units of that instance come from one read +instead of one download each. + +To add a decoder, give the runtime a table that places it: + +```ts +const runtime = createDicomRuntime({ + decoders: (gdcm) => { + const table = defaultDecoderTable(gdcm); + return { + ...table, + byTransferSyntax: new Map(table.byTransferSyntax).set(syntax, [ + myDecoder, + gdcm, + ]), + }; + }, +}); +``` + +`decodeConcurrency` bounds a caller-supplied decoder's decodes within one +`loadVolume`, not across volumes; a decoder that needs a global limit owns its +own pool. + +`wholeInstanceDecoder(name, decode)` makes a decoder that reads each instance +whole and passes its bytes to `decode`; `singleDecoderTable(decoder)` sends +every instance to one decoder. `splitEncapsulatedFrames(value, frameCount)` +cuts an encapsulated Pixel Data value into frames by its Basic Offset Table +(whose first entry must be 0), by one fragment per frame when the counts +match, or else at JPEG End Of Image markers, optionally followed by one zero +pad byte. + +## Runtime + +`createDicomRuntime(options)` owns the request pool (`requestConcurrency`, default 24, exposed as `readConcurrency`), the metadata parser workers -(`metadataConcurrency`, or `metadataWorkerFactory` for another asset layout) -and a pool of GDCM decode workers (`decodeConcurrency`, default half the -cores, at most four; each worker carries its own WASM heap). A supplied -`decoder` replaces GDCM and owns its own resources; with one, every instance -goes to it whole unless `decoders` says otherwise. Metadata-only use needs no -decoder or WASM assets. `dispose()` aborts everything pending. - -The default table decodes Implicit and Explicit VR Little Endian and Explicit -VR Big Endian frames natively where the result is identical to GDCM's: -MONOCHROME2 or unsigned 8 bit RGB samples, 8, 16 or 32 bit words with Bits -Stored ending at High Bit (fewer stored bits only in 16 bit words), 16 bit -words only when big endian, one modality rescale for all frames, and no -overlay, curve, Modality LUT, palette or ICC data. Other transfer syntaxes and -declined instances go to GDCM; video and JPEG XL syntaxes fail as known -syntaxes without a decoder. Both paths apply one modality transform to the -entire instance and reject differing per-frame slopes or intercepts. Injected -decoders may support those transforms. Separate single-frame files may have -different transforms. - -### vtk adapter +(`metadataConcurrency`, default 2, or `metadataWorkerFactory` for another +asset layout) and the GDCM decoder, which runs at most `decodeConcurrency` +workers at once (default half the cores, at most four; each worker carries its +own WASM heap) and terminates a worker whose decode is aborted. `assets` +locates the ITK pipeline worker and the GDCM image reader; reading headers +needs neither, and `itk-wasm` itself loads on the first GDCM decode. +`decoders` builds the decoder table around the GDCM decoder. +`dispose()` aborts everything pending and its `signal`. + +## vtk adapter `toVtkImageData(volume)` wraps the volume's buffer and geometry without copying; before any slice decodes its scalar range is a 0 to 255 placeholder. -`applyVolumeUpdate(image, volume, update)` widens the scalar range by a -decoded slice and marks the image modified. `sliceThumbnail(image, slice)` -downsamples one loaded slice to an 8 bit greyscale thumbnail, and -`encodeThumbnailToUri` in `vtk/thumbnail.ts` turns it into a PNG data URI. +`applyVolumeUpdate(image, update)` widens the scalar range by a decoded unit +and marks the image modified. `sliceThumbnail(image, slice)` downsamples one +slice to at most 256 pixels on its longer side and windows it to an 8 bit +greyscale `ThumbnailSlice` on the loaded range, or on luminance across the +volume for color. `encodeThumbnailToUri` turns a thumbnail into a PNG data +URI. + +## Byte streaming + +`StreamingByteReader` is the byte reader under the header parser; VolView +also uses it to sniff file types. ## Geometry and calibration Enhanced instances read image geometry and modality transforms from their shared and per-frame functional groups. Regular spatial frames retain their stored pixel order, including acquisitions whose frame direction opposes the -row/column cross product. Single-detector reconstructed NM stacks use their -detector patient geometry and signed slice spacing. Gated NM requires temporal -assembly and is rejected. - -OCT shared in-plane spacing is preserved. Calibrated placement between B-scans -requires a matching ophthalmic localizer and remains unsupported. Optical slice -thickness does not define B-scan separation. Vendor-specific ultrasound volume -calibration, RT dose semantics and floating-point parametric maps also require -dedicated import support. VolView skips all RT modalities for both File and HTTP -imports, including RTIMAGE and RTDOSE; these objects do not create a volume. - -`volume.spatialMetadata` reports the applied spacing in image x/y/z order, -including ultrasound region overrides. Each axis records its value, unit (`mm` -or `unknown`), source, and whether it was declared, derived from positions, or -supplied as a display fallback. Reconstruction quality and ultrasound region -limitations are separate from the unit. These are statements about the source -and allocation, not independent calibration. +row and column cross product. Single-detector reconstructed NM stacks use +their detector patient geometry and signed slice spacing. Gated NM requires +temporal assembly and is rejected. + +OCT shared in-plane spacing is preserved. Calibrated placement between +B-scans requires a matching ophthalmic localizer and remains unsupported. +Optical slice thickness does not define B-scan separation. Vendor-specific +ultrasound volume calibration, RT dose semantics and floating-point parametric +maps also require dedicated import support. + +`volume.spatialMetadata` reports the applied spacing in image x, y, z order, +including ultrasound region overrides (`unitToMm` converts region units). +Each axis records its value, unit (`mm` or `unknown`), source, and whether it +was declared, derived from positions, or supplied as a display fallback +(`physicalSpacing` and `fallbackSpacing` build those records). Reconstruction +quality and ultrasound region limitations are separate from the unit. These +are statements about the source and allocation, not independent calibration. Missing physical spacing is permitted for some DICOM objects, including [secondary captures](https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_A.8.html). -Ordinary patient PixelSpacing and ImagePositionPatient use millimeters without -requiring an additional calibration tag. A fallback value of 1 does not +Ordinary patient PixelSpacing and ImagePositionPatient use millimeters +without an additional calibration tag. A fallback value of 1 does not establish a millimeter scale. A singleton axis does not establish a distance between slices. -## Standalone checks - -`npm run dicom:build` emits ES modules and declarations in `packages/dicom/dist`, -including the parser worker, the ITK pipeline worker and the GDCM image reader -assets. Serve the assets from a URL your application controls and pass their -locations explicitly. `npm run dicom:check` builds the package and typechecks -and bundles two small consumers against its emitted JavaScript and -declarations. It rejects VolView application imports and Vue/Pinia -dependencies, and rejects vtk.js in the core consumer. Package boundary tests -also check relative imports and declared dependencies. - -`npm run test:e2e:chrome:skip-build -- --spec tests/specs/dicom-package.e2e.ts` -serves those standalone production bundles, generates its DICOM in memory, and -checks Blob/HTTP metadata, calibrated pixel values, decode worker recovery and -vtk geometry through rendered page output, including a screenshot. - -`tests/specs/dicom-volume-corpus.e2e.ts` exercises pinned public CT, MR and -SPECT files through both File and HTTP sources, plus numeric-padding fixtures. -It checks dimensions, physical geometry, explicit unsupported-topology errors -and the hash of every calibrated voxel through rendered consumer output. Public -URLs, input checksums, independently decoded pixel hashes and provenance are -recorded in `tests/dicomVolumeCorpus.json`; downloads use the ignored dataset -cache. - -`tests/specs/dicom-native-parity.e2e.ts` decodes synthesized instances across -the native format matrix and every cached uncompressed dataset through GDCM -and frame by frame natively, from File and HTTP sources. Wherever the decoder -table plans native frames, both must write identical samples into the volume, -which for a fractional rescale means equal after the same float32 rounding, -and integer GDCM output must equal the native values before any conversion. - -`tests/specs/dicom-volume-composition.e2e.ts` composes downloaded classic CT/PET -series and two MR acquisitions sharing one Series UID. It checks every -collection's ordered SOP membership, complete calibrated voxel hash and -physical geometry after shuffled batch and incremental File/HTTP imports. -`tests/dicomCompositionCorpus.json` records the pinned inputs and independent -expectations. The optional `compositionReference.py` beside the consumer -fixtures reproduces those expectations using pydicom and NumPy from the cache. +## Browser test pages + +`tests/fixtures/dicom-pages` holds small pages that use this module +without VolView startup. `server.mjs` builds them with Vite straight from +this source, beside the ITK pipeline worker and GDCM image reader assets from +`node_modules`. A page build fails if it pulls in VolView application code, +Vue or Pinia, and the core page also fails on vtk.js. The pages import the +module through the entry points, as the app does. + +- `dicom-module-pages.e2e.ts` generates DICOM in memory and checks Blob and + HTTP metadata, calibrated pixel values, decode worker recovery and vtk + geometry through rendered page output, including a screenshot. +- `dicom-volume-corpus.e2e.ts` loads pinned public CT, MR and SPECT files + through File and HTTP sources, plus numeric-padding fixtures, and checks + dimensions, physical geometry, explicit unsupported-topology errors and the + hash of every calibrated voxel. Inputs, checksums, independently decoded + hashes and provenance are in `tests/dicomVolumeCorpus.json`. +- `dicom-native-parity.e2e.ts` decodes synthesized instances across the native + format matrix and every cached uncompressed dataset through GDCM and frame by + frame natively, from File and HTTP sources. Wherever the table plans native + frames, both must write identical samples, which for a fractional rescale + means equal after the same float32 rounding. +- `dicom-volume-composition.e2e.ts` composes downloaded classic CT and PET + series and two MR acquisitions sharing one Series UID, and checks every + collection's ordered SOP membership, calibrated voxel hash and physical + geometry after shuffled batch and incremental File and HTTP imports. + `tests/dicomCompositionCorpus.json` records the inputs and expectations; + `compositionReference.py` beside the pages reproduces them with pydicom and + NumPy. +- `dicom-frame-reconstruction.e2e.ts` and `dicom-spacing-details.e2e.ts` check + multiframe reconstruction and spacing reports. diff --git a/packages/dicom/__tests__/boundaries.spec.ts b/packages/dicom/__tests__/boundaries.spec.ts index 9acba20c0..0a4d08678 100644 --- a/packages/dicom/__tests__/boundaries.spec.ts +++ b/packages/dicom/__tests__/boundaries.spec.ts @@ -5,22 +5,19 @@ import ts from 'typescript'; import { describe, expect, it } from 'vitest'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); -const manifest = JSON.parse( - readFileSync(resolve(root, 'package.json'), 'utf8') -); -const dependencies = new Set([ - ...Object.keys(manifest.dependencies), - ...Object.keys(manifest.peerDependencies), -]); -const sourceFiles = (directory: string): string[] => +const repository = resolve(root, '../..'); +const tsFiles = (directory: string): string[] => readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { const file = resolve(directory, entry.name); - if (entry.isDirectory()) - return entry.name === '__tests__' ? [] : sourceFiles(file); + if (entry.isDirectory()) return tsFiles(file); return entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') ? [file] : []; }); +const isTest = (file: string) => file.includes('/__tests__/'); +const sourceFiles = (directory: string) => + tsFiles(directory).filter((file) => !isTest(file)); +const testFiles = (directory: string) => tsFiles(directory).filter(isTest); const importsOf = (file: string) => { const source = ts.createSourceFile( @@ -49,47 +46,73 @@ const importsOf = (file: string) => { return imports; }; +const entryPoints = new Set(['core', 'core/index', 'vtk', 'vtk/index']); + +// ESLint matches import specifiers, so relative paths that leave the module, +// reach vtk from core or come back through an entry point are checked against +// resolved locations here. for (const entry of ['core', 'vtk']) { - describe(`DICOM ${entry} dependency boundary`, () => { + describe(`DICOM ${entry} relative imports`, () => { const sources = sourceFiles(resolve(root, entry)); it.each(sources.map((file) => relative(root, file)))( - '%s stays inside its declared boundary', + '%s stays inside its boundary', (name) => { for (const specifier of importsOf(resolve(root, name))) { - if (specifier.startsWith('.')) { - const target = relative( - root, - resolve(dirname(resolve(root, name)), specifier) - ); - expect(target.startsWith('..')).toBe(false); - if (entry === 'core') expect(target.startsWith('vtk/')).toBe(false); - } else { - const dependency = specifier.startsWith('@') - ? specifier.split('/').slice(0, 2).join('/') - : specifier.split('/')[0]; - expect(dependencies.has(dependency), specifier).toBe(true); - expect(['vue', 'pinia', '@vueuse/core']).not.toContain(dependency); - if (entry === 'core') - expect(dependency).not.toBe('@kitware/vtk.js'); - } + if (!specifier.startsWith('.')) continue; + const target = relative( + root, + resolve(dirname(resolve(root, name)), specifier) + ); + expect(target.startsWith('..'), specifier).toBe(false); + expect(entryPoints.has(target), specifier).toBe(false); + if (entry === 'core') + expect(target.startsWith('vtk/'), specifier).toBe(false); } } ); }); } -it('VolView imports defining core and vtk modules directly', () => { - const repository = resolve(root, '../..'); - for (const file of sourceFiles(resolve(repository, 'src'))) { - for (const specifier of importsOf(file)) { - const target = specifier.startsWith('@/') - ? resolve(repository, specifier.slice(2)) - : resolve(dirname(file), specifier); - if (!target.startsWith(`${root}/`)) continue; - const module = relative(root, target).replace(/\.ts$/, ''); - expect(module, relative(repository, file)).toMatch(/^(core|vtk)\/.+/); - expect(module.endsWith('/index'), relative(repository, file)).toBe(false); - expect(existsSync(`${target.replace(/\.ts$/, '')}.ts`)).toBe(true); +/** The file a specifier names, or undefined for a package import. */ +const resolveImport = (from: string, specifier: string) => { + const base = specifier.startsWith('@/') + ? resolve(repository, specifier.slice(2)) + : specifier.startsWith('.') + ? resolve(dirname(from), specifier) + : undefined; + if (!base) return undefined; + return [base, `${base}.ts`, resolve(base, 'index.ts')].find( + (file) => existsSync(file) && file.endsWith('.ts') + ); +}; + +/** Files a test reaches through module and shared test fixture imports. */ +const reachedFrom = (file: string, seen = new Set()): Set => { + if (seen.has(file)) return seen; + seen.add(file); + importsOf(file) + .map((specifier) => resolveImport(file, specifier)) + .filter((target): target is string => !!target) + .forEach((target) => reachedFrom(target, seen)); + return seen; +}; + +describe('DICOM module tests', () => { + it.each(testFiles(root).map((file) => relative(root, file)))( + '%s reaches no VolView application code', + (name) => { + const reached = [...reachedFrom(resolve(root, name))].flatMap((file) => + importsOf(file) + .filter( + (specifier) => + relative( + repository, + resolveImport(file, specifier) ?? '' + ).startsWith('src/') || specifier.startsWith('@/src/') + ) + .map((specifier) => `${relative(repository, file)}: ${specifier}`) + ); + expect(reached).toEqual([]); } - } + ); }); diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts index caf38871a..777b9e393 100644 --- a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { getDatasetTag } from '../../metadata/datasetAccess'; import { Tags } from '../../metadata/dicomTags'; import type { Instance } from '../../instance/readInstance'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; import { emptyRegistry, forgetCollection, @@ -10,7 +10,7 @@ import { registerInstances, type RegistryState, } from '../instanceRegistry'; -import { mergingChunks } from '@/tests/dicomOrientationFixtures'; +import { mergingInstances } from '@/tests/dicomOrientationFixtures'; import { OTHER_SERIES_UID, SERIES_UID, @@ -109,7 +109,7 @@ describe('pure instance registry', () => { }); it('reports the id a replan dissolves when two collections merge', () => { - const { between, straight, tilted } = mergingChunks(slice); + const { between, straight, tilted } = mergingInstances(slice); const [first, second] = registerAll([[straight, tilted], [between]]); @@ -151,6 +151,78 @@ describe('pure instance registry', () => { expect(third.removed).toEqual([]); }); + it('says how each collection differs from what was committed', () => { + const [a, b] = [0, 1].map((z) => slice({ sop: `c${z}`, z })); + + const changes = registerAll([[a], [slice({ sop: 'c0', z: 0 })], [b]]).map( + ({ updates }) => updates.map((update) => update.change) + ); + + expect(changes).toEqual([['new'], ['unchanged'], ['changed']]); + }); + + it('reports a relabelled collection as changed', () => { + const acquisition = (number: string, zs: number[]) => + zs.map((z) => + slice({ + sop: `${number}-${z}`, + z, + tags: { [Tags.AcquisitionNumber]: number }, + }) + ); + + const [, second] = registerAll([ + acquisition('1', [0, 2]), + acquisition('2', [1, 3]), + ]); + + expect(second.updates.map((update) => update.change)).toEqual([ + 'changed', + 'new', + ]); + }); + + it('reports a collection whose axes a sibling pass outvoted as changed', () => { + // Within the orientation tolerance, so one bucket, but leaning the normal. + const tilted = '1\\0\\0\\0\\0.99995\\0.0099998'; + const acquisition = (number: string, zs: number[], orientation?: string) => + zs.map((z) => + slice({ + sop: `${number}-${z}`, + z, + orientation, + tags: { [Tags.AcquisitionNumber]: number }, + }) + ); + + const [first, second] = registerAll([ + [...acquisition('1', [0, 2]), ...acquisition('2', [1, 3], tilted)], + acquisition('2', [5], tilted), + ]); + + const before = first.updates.find((update) => + sopsOf(update.members).includes('1-0') + )!; + const after = second.updates.find((update) => update.id === before.id)!; + expect(sopsOf(after.members)).toEqual(['1-0', '1-2']); + expect(after.collection.key).toEqual(before.collection.key); + expect(after.collection.orientation).not.toEqual( + before.collection.orientation + ); + expect(after.change).toBe('changed'); + }); + + it.each(['SEG', 'SEG\u0000'])( + 'reports SEG modality %j as a segmentation collection', + (modality) => { + const [image, seg] = lastUpdates([ + [slice({ sop: 'image' }), slice({ sop: 'seg', modality, rows: '8' })], + ]); + + expect([image.kind, seg.kind]).toEqual(['image', 'segmentation']); + } + ); + it('plans series independently', () => { const first = slice({ sop: 'a', series: SERIES_UID }); const second = slice({ sop: 'b', series: OTHER_SERIES_UID }); diff --git a/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts b/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts index c1fd05c81..56a0c8069 100644 --- a/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts +++ b/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { getDatasetTag } from '../../metadata/datasetAccess'; import { Tags } from '../../metadata/dicomTags'; import type { Instance } from '../../instance/readInstance'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; import { emptyRegistry, forgetCollection, @@ -11,7 +11,7 @@ import { type InstanceCollectionUpdate, } from '../instanceRegistry'; import { UNREADABLE_POSITION_WARNING } from '../planDicomCollections'; -import { mergingChunks, tilt } from '@/tests/dicomOrientationFixtures'; +import { mergingInstances, tilt } from '@/tests/dicomOrientationFixtures'; import { SERIES_UID, sliceDataset, type SliceOptions } from './sliceFixture'; const sliceInstance = (options: SliceOptions = {}) => @@ -100,14 +100,14 @@ describe('instance registry across imports', () => { expect(update.collection.diagnostics).toEqual([]); }); - it('aligns the chunk members with the planned facts', () => { + it('aligns the instance members with the planned facts', () => { const registry = createRegistry(); - const chunks = [ + const instances = [ sliceInstance({ sop: 'a', z: 2 }), sliceInstance({ sop: 'b', z: 0 }), ]; - const { updates } = registry.register(chunks); + const { updates } = registry.register(instances); const [update] = updates; expect(update.collection.members.map((m) => m.sopInstanceUid)).toEqual( @@ -221,23 +221,23 @@ describe('instance registry across imports', () => { expect(registry.has(original)).toBe(false); }); - it('counts one chunk once however often a batch repeats it', () => { + it('counts one instance once however often a batch repeats it', () => { const registry = createRegistry(); - const chunk = sliceInstance({ sop: 'a', z: 0 }); + const instance = sliceInstance({ sop: 'a', z: 0 }); - const [update] = registry.register([chunk, chunk]).updates; + const [update] = registry.register([instance, instance]).updates; - expect(update.members).toEqual([chunk]); + expect(update.members).toEqual([instance]); }); - it('re-registers an anonymous chunk without duplicating it', () => { + it('re-registers an anonymous instance without duplicating it', () => { const registry = createRegistry(); - const chunk = sliceInstance({ sop: null, z: 0 }); + const instance = sliceInstance({ sop: null, z: 0 }); - registry.register([chunk]); - const [update] = registry.register([chunk]).updates; + registry.register([instance]); + const [update] = registry.register([instance]).updates; - expect(update.members).toEqual([chunk]); + expect(update.members).toEqual([instance]); }); it('splits one batch of incompatible instances into two collections', () => { @@ -275,7 +275,7 @@ describe('instance registry across imports', () => { // The positions of the two passes already earned their separation; a later // slice nothing spatial can be said about must not dissolve it. - it('keeps two separated acquisitions when a positionless chunk arrives later', () => { + it('keeps two separated acquisitions when a positionless instance arrives later', () => { const registry = createRegistry(); const first = [0, 2, 4].map((z) => sliceInstance({ @@ -331,9 +331,9 @@ describe('instance registry across imports', () => { expect(updates[0].provenance).toEqual([slice]); }); - const merging = () => mergingChunks(sliceInstance); + const merging = () => mergingInstances(sliceInstance); - it('reports a collection that lost members without gaining a chunk', () => { + it('reports a collection that lost members without gaining an instance', () => { const registry = createRegistry(); const straight = sliceInstance({ sop: 'sop-2', @@ -371,7 +371,7 @@ describe('instance registry across imports', () => { const resupplied = sliceInstance({ sop: 'a', z: 0 }); const second = registry.register([resupplied]); - // Identity, not shape: the released chunk is an equal but stale object. + // Identity, not shape: the released instance is an equal but stale object. expect(second.updates[0].members).toHaveLength(1); expect(second.updates[0].members[0]).toBe(resupplied); expect(second.updates[0].id).toBe(updates[0].id); @@ -410,12 +410,12 @@ describe('instance registry across imports', () => { it('surfaces the planner order and diagnostics for a positionless series', () => { const registry = createRegistry(); - const chunks = [ + const instances = [ sliceInstance({ sop: 'alpha', z: null, instanceNumber: 2 }), sliceInstance({ sop: 'beta', z: null, instanceNumber: 1 }), ]; - const [update] = registry.register(chunks).updates; + const [update] = registry.register(instances).updates; expect(sops(update.members)).toEqual(['beta', 'alpha']); expect(update.collection.order).toBe('instance-number'); @@ -426,15 +426,15 @@ describe('instance registry across imports', () => { it('does not mutate the batch it registers', () => { const registry = createRegistry(); - const chunks = [ + const instances = [ sliceInstance({ sop: 'a', z: 2 }), sliceInstance({ sop: 'b', z: 0 }), ]; - const order = [...chunks]; + const order = [...instances]; - registry.register(chunks); + registry.register(instances); - expect(chunks).toEqual(order); + expect(instances).toEqual(order); }); }); diff --git a/packages/dicom/core/collections/assignCollectionIds.ts b/packages/dicom/core/collections/assignCollectionIds.ts index 0233b9430..19be2a98d 100644 --- a/packages/dicom/core/collections/assignCollectionIds.ts +++ b/packages/dicom/core/collections/assignCollectionIds.ts @@ -9,12 +9,6 @@ export type CommittedCollection = { sopInstanceUids: string[]; }; -export type AssignedCollection = DicomCollection & { id: string }; - -export type AssignedPlan = { - collections: AssignedCollection[]; -}; - // encodeURIComponent escapes every separator the key values can carry, so the // join characters below cannot appear inside an encoded component. const escape = (value: string) => encodeURIComponent(value); diff --git a/packages/dicom/core/collections/instanceFacts.ts b/packages/dicom/core/collections/instanceFacts.ts index 6c4e2774d..5715c2e43 100644 --- a/packages/dicom/core/collections/instanceFacts.ts +++ b/packages/dicom/core/collections/instanceFacts.ts @@ -61,7 +61,7 @@ const cross = (left: number[], right: number[]) => [ * rescales any axis it is given, so a value printed to three decimals loads * as the scanner meant it while a skewed basis still does not. */ -export const ORTHOGONALITY_TOLERANCE = 1e-3; +const ORTHOGONALITY_TOLERANCE = 1e-3; const magnitude = (axis: number[]) => Math.sqrt(dot(axis, axis)); diff --git a/packages/dicom/core/collections/instanceKey.ts b/packages/dicom/core/collections/instanceKey.ts index 7d91d372d..26cc2ba8d 100644 --- a/packages/dicom/core/collections/instanceKey.ts +++ b/packages/dicom/core/collections/instanceKey.ts @@ -3,7 +3,7 @@ import type { InstanceFacts } from './planDicomCollections'; const anonymousKeys = new WeakMap(); let nextAnonymousKey = 0; -// Chunk facts are cached for the lifetime of their metadata. Object identity +// Instance facts are cached for the lifetime of their metadata. Object identity // survives replanning without retaining discarded facts, and the prefix cannot // be a DICOM UID, whose alphabet contains only digits and dots. export const instanceKey = (instance: InstanceFacts) => { diff --git a/packages/dicom/core/collections/instanceRegistry.ts b/packages/dicom/core/collections/instanceRegistry.ts index 97e859fe2..3bb2eabfb 100644 --- a/packages/dicom/core/collections/instanceRegistry.ts +++ b/packages/dicom/core/collections/instanceRegistry.ts @@ -1,6 +1,6 @@ import type { Instance } from '../instance/readInstance'; import { trimDicomPadding } from '../utils'; -import { getDatasetTag } from '../metadata/datasetAccess'; +import { getDatasetModality, getDatasetTag } from '../metadata/datasetAccess'; import { Tags } from '../metadata/dicomTags'; import { planDicomCollections, @@ -15,8 +15,15 @@ import { import { seriesKeyOf } from './instanceFacts'; import { readDatasetDetails } from './datasetDetails'; import { groupBy } from './groupBy'; +import type { Reconstruction } from './reconstructVolume'; -export type InstanceCollectionUpdate = { +/** + * How a collection differs from what was last committed under its ID: + * `unchanged` has the same members, key and geometry, re-supplied by the batch. + */ +type CollectionChange = 'new' | 'unchanged' | 'changed'; + +type CollectionUpdateFields = { id: string; seriesKey: string; collection: DicomCollection; @@ -24,6 +31,18 @@ export type InstanceCollectionUpdate = { members: Instance[]; /** Aligned with members: the batch's own instance wherever it re-supplied one. */ provenance: Instance[]; + change: CollectionChange; +}; + +/** + * An image volume, or a SEG object whose pixels are labels rather than an + * image. A union so that checking `kind` narrows the update for allocateVolume. + */ +export type InstanceCollectionUpdate = CollectionUpdateFields & + ({ kind: 'image' } | { kind: 'segmentation' }); + +export type ImageCollectionUpdate = InstanceCollectionUpdate & { + kind: 'image'; }; // An instance with no SOP Instance UID is identified by its object, so two of @@ -40,6 +59,8 @@ type Committed = { members: readonly InstanceKey[]; // Reported when relabelled even if its members did not move. key: string; + orientation: readonly number[] | null; + reconstruction: Reconstruction; }; type SeriesState = { @@ -90,11 +111,40 @@ const claimable = (committed: SeriesState['committed']) => ) .filter((collection) => collection.sopInstanceUids.length > 0); -const unchanged = (before: Committed | undefined, after: Committed) => - before !== undefined && +const sameList = (a: readonly T[] | null, b: readonly T[] | null) => + a === b || + (a !== null && + b !== null && + a.length === b.length && + a.every((value, index) => value === b[index])); + +const reasonOf = (reconstruction: Reconstruction) => + reconstruction.kind === 'irregular' ? reconstruction.reason : null; + +const sameReconstruction = (a: Reconstruction, b: Reconstruction) => + a.kind === b.kind && + reasonOf(a) === reasonOf(b) && + a.sliceSpacing === b.sliceSpacing && + sameList(a.slots, b.slots); + +const unchanged = (before: Committed, after: Committed) => before.key === after.key && - before.members.length === after.members.length && - before.members.every((key, index) => key === after.members[index]); + sameList(before.members, after.members) && + sameList(before.orientation, after.orientation) && + sameReconstruction(before.reconstruction, after.reconstruction); + +const changeOf = ( + before: Committed | undefined, + after: Committed +): CollectionChange => { + if (!before) return 'new'; + return unchanged(before, after) ? 'unchanged' : 'changed'; +}; + +const kindOf = (first: Instance) => + getDatasetModality(first.dataset) === 'SEG' + ? ('segmentation' as const) + : ('image' as const); // The first registration of an instance wins; a re-supply only reports back. function mergeBatch(series: SeriesState, batch: Registered[]) { @@ -143,18 +193,24 @@ function planSeries( const committed: Committed = { members: entries.map((entry) => entry.key), key: encodeCollectionKey(collection.key), + orientation: collection.orientation, + reconstruction: collection.reconstruction, }; + const members = entries.map((entry) => entry.instance); + const change = changeOf(series.committed.get(id), committed); const update: InstanceCollectionUpdate = { id, seriesKey, collection, - members: entries.map((entry) => entry.instance), + members, provenance: entries.map(provenanceOf), + change, + kind: kindOf(members[0]), }; // A replan can move members or relabel a collection the batch brought nothing. const changed = - committed.members.some((key) => supplied.has(key)) || - !unchanged(series.committed.get(id), committed); + change !== 'unchanged' || + committed.members.some((key) => supplied.has(key)); return { committed, update, changed }; }); diff --git a/packages/dicom/core/collections/planDicomCollections.ts b/packages/dicom/core/collections/planDicomCollections.ts index b2aa745ff..a214b919f 100644 --- a/packages/dicom/core/collections/planDicomCollections.ts +++ b/packages/dicom/core/collections/planDicomCollections.ts @@ -15,8 +15,8 @@ import { } from './reconstructVolume'; /** - * Facts read once per instance from a chunk's metadata. Plain data: the planner - * never sees a Chunk, a store, or an itk-wasm task. + * Facts read once per instance from its metadata. Plain data: the planner + * never sees a source, a store, or an itk-wasm task. */ export type InstanceFacts = { // Identity. Instances without a SOP Instance UID are never deduplicated. @@ -39,7 +39,7 @@ export type InstanceFacts = { position: number[] | null; projectedPosition: number | null; pixelSpacing: number[] | null; - /** Intra-instance frame geometry; slots still index source chunks. */ + /** Intra-instance frame geometry; slots still index source instances. */ frameReconstruction?: Reconstruction; // Ordering fallback. @@ -58,7 +58,7 @@ export type CollectionKey = { parts: Array<[string, string | null]>; }; -export type MemberOrder = 'spatial' | 'instance-number' | 'input'; +type MemberOrder = 'spatial' | 'instance-number' | 'input'; export type DicomCollection = { key: CollectionKey; @@ -82,7 +82,7 @@ export type DicomCollectionPlan = { collections: DicomCollection[]; }; -export type PlanInput = { +type PlanInput = { seriesKey: string; instances: InstanceFacts[]; }; diff --git a/packages/dicom/core/collections/reconstructVolume.ts b/packages/dicom/core/collections/reconstructVolume.ts index 2d38813ea..2599b9a3c 100644 --- a/packages/dicom/core/collections/reconstructVolume.ts +++ b/packages/dicom/core/collections/reconstructVolume.ts @@ -2,7 +2,7 @@ import type { InstanceFacts } from './planDicomCollections'; import { projectOnNormal, sliceNormalOf } from './instanceFacts'; /** The geometry a reconstruction judges. Nothing else about an instance. */ -export type ReconstructionMember = Pick< +type ReconstructionMember = Pick< InstanceFacts, 'orientation' | 'position' | 'pixelSpacing' > & { frameReconstruction?: Reconstruction; numberOfFrames?: string | null }; @@ -43,14 +43,14 @@ export type Reconstruction = * onto its normal jitters in the last digits; a genuine slab boundary or a * missed slice is orders of magnitude larger. */ -export const SLICE_SPACING_TOLERANCE_MM = 0.1; -export const SLICE_SPACING_RELATIVE_TOLERANCE = 0.01; +const SLICE_SPACING_TOLERANCE_MM = 0.1; +const SLICE_SPACING_RELATIVE_TOLERANCE = 0.01; /** How far a slice may sit from the in-plane origin of the first, in mm. */ export const IN_PLANE_TOLERANCE_MM = 0.1; /** How far two in-plane sample spacings may differ and still be one grid. */ -export const PIXEL_SPACING_TOLERANCE_MM = 1e-4; +const PIXEL_SPACING_TOLERANCE_MM = 1e-4; const spacingTolerance = (gap: number) => Math.max( @@ -206,7 +206,7 @@ export function reconstructVolume( : irregular(fault, positionStep(members), members.length); } -/** Instance slots index source chunks even when one source contains many frames. */ +/** Slots index source instances even when one instance holds many frames. */ export function reconstructInstances( members: ReconstructionMember[], normal?: number[] | null, diff --git a/packages/dicom/core/streaming/__tests__/byteDeque.spec.ts b/packages/dicom/core/header/__tests__/byteDeque.spec.ts similarity index 100% rename from packages/dicom/core/streaming/__tests__/byteDeque.spec.ts rename to packages/dicom/core/header/__tests__/byteDeque.spec.ts diff --git a/packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts b/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts similarity index 94% rename from packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts rename to packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts index f6e99395b..f8c4c6ca8 100644 --- a/packages/dicom/core/streaming/dicom/__tests__/dicomHeaderEncodings.spec.ts +++ b/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { findElement, readDicomDataset } from '../../../metadata/dicomDataset'; -import { getDatasetTag } from '../../../metadata/datasetAccess'; -import { sequenceItems } from '../../../metadata/functionalGroups'; -import { concatBytes } from '../../../utils'; +import { findElement, readDicomDataset } from '../../metadata/dicomDataset'; +import { getDatasetTag } from '../../metadata/datasetAccess'; +import { sequenceItems } from '../../metadata/functionalGroups'; +import { concatBytes } from '../../utils'; import { readHeader, syntheticSlice } from '@/tests/dicomSourceFixtures'; import { rawElement, diff --git a/packages/dicom/core/streaming/__tests__/streamingByteReader.spec.ts b/packages/dicom/core/header/__tests__/streamingByteReader.spec.ts similarity index 97% rename from packages/dicom/core/streaming/__tests__/streamingByteReader.spec.ts rename to packages/dicom/core/header/__tests__/streamingByteReader.spec.ts index cc720f925..6133c5421 100644 --- a/packages/dicom/core/streaming/__tests__/streamingByteReader.spec.ts +++ b/packages/dicom/core/header/__tests__/streamingByteReader.spec.ts @@ -1,5 +1,5 @@ import StreamingByteReader from '../streamingByteReader'; -import { asCoroutine } from '@/src/utils'; +import { asCoroutine } from '../../utils'; import { describe, it, expect } from 'vitest'; describe('StreamingByteReader', () => { diff --git a/packages/dicom/core/streaming/byteDeque.ts b/packages/dicom/core/header/byteDeque.ts similarity index 100% rename from packages/dicom/core/streaming/byteDeque.ts rename to packages/dicom/core/header/byteDeque.ts diff --git a/packages/dicom/core/streaming/dicom/dicomParser.ts b/packages/dicom/core/header/dicomParser.ts similarity index 96% rename from packages/dicom/core/streaming/dicom/dicomParser.ts rename to packages/dicom/core/header/dicomParser.ts index 39c4f81a4..c1b6e3f4d 100644 --- a/packages/dicom/core/streaming/dicom/dicomParser.ts +++ b/packages/dicom/core/header/dicomParser.ts @@ -1,10 +1,10 @@ -import StreamingByteReader from '../streamingByteReader'; -import { toAscii, asCoroutine } from '../../utils'; +import StreamingByteReader from './streamingByteReader'; +import { toAscii, asCoroutine } from '../utils'; import { PART_10_HEADER_LENGTH, sniffDicomLayout, type DicomLayout, -} from '../../metadata/dicomLayout'; +} from '../metadata/dicomLayout'; // [Group, Element] type Tag = [number, number]; @@ -17,11 +17,7 @@ export type DataElement = { data: Array | Uint8Array | undefined; }; -export type DataElementCallback = (el: DataElement) => void; -export type ElementTagCallback = ( - group: number, - element: number -) => string | null; +type DataElementCallback = (el: DataElement) => void; type ParseOptions = { peek?: boolean; @@ -45,7 +41,7 @@ const assertReadBounds = ( const UndefinedLength = 0xffffffff; const isEncapsulatedValue = (vr: string, length: number) => length === UndefinedLength && (vr === 'OB' || vr === 'OW'); -export const ImplicitTransferSyntaxUID = '1.2.840.10008.1.2'; +const ImplicitTransferSyntaxUID = '1.2.840.10008.1.2'; export const ExplicitVRBigEndianUID = '1.2.840.10008.1.2.2'; const DeflatedExplicitVRLittleEndianUID = '1.2.840.10008.1.2.1.99'; @@ -418,14 +414,14 @@ function* readFieldMetaInfo( }; } -export type ReadDicomOptions = { +type ReadDicomOptions = { stopAtElement?(group: number, element: number): boolean; onDataElement?: DataElementCallback; /** Called once the opening bytes say how the file is laid out. */ onLayout?(layout: DicomLayout): void; }; -export function* readDicomUntilPixelData(opts?: ReadDicomOptions) { +function* readDicomUntilPixelData(opts?: ReadDicomOptions) { const reader = new StreamingByteReader(); // Peeked rather than read: a file without the Part 10 preamble has its diff --git a/packages/dicom/core/streaming/dicom/readDicomHeader.ts b/packages/dicom/core/header/readDicomHeader.ts similarity index 98% rename from packages/dicom/core/streaming/dicom/readDicomHeader.ts rename to packages/dicom/core/header/readDicomHeader.ts index 3d86d772e..26ab3175a 100644 --- a/packages/dicom/core/streaming/dicom/readDicomHeader.ts +++ b/packages/dicom/core/header/readDicomHeader.ts @@ -2,8 +2,8 @@ import { createDicomParser, ExplicitVRBigEndianUID } from './dicomParser'; import { IMPLICIT_VR_LITTLE_ENDIAN, type DicomLayout, -} from '../../metadata/dicomLayout'; -import { concatBytes, toAscii } from '../../utils'; +} from '../metadata/dicomLayout'; +import { concatBytes, toAscii } from '../utils'; /** `skip-radiotherapy` returns after the Modality tag for RT objects. */ export type ImageImportPolicy = 'complete-header' | 'skip-radiotherapy'; diff --git a/packages/dicom/core/streaming/streamingByteReader.ts b/packages/dicom/core/header/streamingByteReader.ts similarity index 100% rename from packages/dicom/core/streaming/streamingByteReader.ts rename to packages/dicom/core/header/streamingByteReader.ts diff --git a/packages/dicom/core/index.ts b/packages/dicom/core/index.ts new file mode 100644 index 000000000..d2cf2c438 --- /dev/null +++ b/packages/dicom/core/index.ts @@ -0,0 +1,100 @@ +// Sources +export { + fromBlob, + fromUrl, + readBytes, + type ByteSource, +} from './source/byteSource'; + +// Instances +export { + readInstance, + type Instance, + type ReadInstanceOptions, +} from './instance/readInstance'; +export { + IMPLICIT_VR_LITTLE_ENDIAN, + EXPLICIT_VR_LITTLE_ENDIAN, + type DicomLayout, +} from './metadata/dicomLayout'; + +// Datasets +export { + readDicomDataset, + isPrivateElement, + type DicomDataset, + type DicomElement, +} from './metadata/dicomDataset'; +export { getDatasetTag, getDatasetModality } from './metadata/datasetAccess'; +export { sequenceItems } from './metadata/functionalGroups'; +export { trimDicomPadding } from './utils'; +export { + Tags, + SOP_CLASS_ULTRASOUND_MULTIFRAME, + SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, + isUltrasoundMultiframeSopClass, +} from './metadata/dicomTags'; + +// Collections +export { + emptyRegistry, + registerInstances, + forgetCollection, + type RegistryState, + type InstanceCollectionUpdate, +} from './collections/instanceRegistry'; +export { seriesKeyOf } from './collections/instanceFacts'; + +// Volumes +export { + allocateVolume, + type Volume, + type AllocateVolumeOptions, +} from './volume/allocateVolume'; +export { + loadVolume, + middleSlot, + type VolumeUpdate, + type Extent, +} from './volume/loadVolume'; +export { + getVolumeBufferType, + instancePixelFormats, + type VolumeBufferConstructor, +} from './volume/pixelFormat'; + +// Spatial metadata +export { + physicalSpacing, + fallbackSpacing, + type SpatialMetadata, +} from './metadata/spatialMetadata'; +export { unitToMm, ultrasoundRegionsOf } from './metadata/ultrasoundRegion'; + +// Decoders +export { + wholeInstanceDecoder, + type PixelDecoder, + type DecodeUnit, + type DecodedPixels, + type WholeInstanceDecode, +} from './pixels/pixelDecoder'; +export { + defaultDecoderTable, + singleDecoderTable, + planDecode, + type DecoderTable, +} from './pixels/decoderTable'; +export { nativeFrameDecoder } from './pixels/nativeFrame'; +export { indexFrames } from './pixels/frameIndex'; +export { splitEncapsulatedFrames } from './pixels/encapsulatedFrames'; + +// Runtime +export { + createDicomRuntime, + type DicomRuntime, + type DicomRuntimeOptions, +} from './runtime/createDicomRuntime'; + +// The byte reader under the header parser, which the app also uses to sniff file types +export { default as StreamingByteReader } from './header/streamingByteReader'; diff --git a/packages/dicom/core/instance/__tests__/instanceFixture.ts b/packages/dicom/core/instance/__tests__/instanceFixture.ts deleted file mode 100644 index f09d857af..000000000 --- a/packages/dicom/core/instance/__tests__/instanceFixture.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { DicomDataset } from '../../metadata/dicomDataset'; -import { fromBlob, type ByteSource } from '../../source/byteSource'; -import type { Instance } from '../readInstance'; - -const noBytes = fromBlob(new Blob([])); - -/** An instance as `readInstance` returns it, from a header built in memory. */ -export const instanceFor = ( - dataset: DicomDataset, - source: ByteSource = noBytes -): Instance => - Object.freeze({ - source, - dataset, - layout: null, - ultrasoundRegions: null, - transferSyntaxUid: null, - pixelData: null, - }); diff --git a/packages/dicom/core/instance/__tests__/readInstance.spec.ts b/packages/dicom/core/instance/__tests__/readInstance.spec.ts index 09f8e6c6f..bd17c3af4 100644 --- a/packages/dicom/core/instance/__tests__/readInstance.spec.ts +++ b/packages/dicom/core/instance/__tests__/readInstance.spec.ts @@ -7,7 +7,7 @@ import { withoutPixelData, } from '@/tests/dicomSourceFixtures'; import { rawElement } from '@/tests/specs/syntheticDicom'; -import { trackedSource } from '../../source/__tests__/sourceFixtures'; +import { trackedSource } from '@/tests/byteSourceFixtures'; const PATIENT_NAME = '00100010'; const CHUNK = 256; diff --git a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts index c9ece0565..593f0cc74 100644 --- a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts +++ b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts @@ -9,7 +9,7 @@ import { IMPLICIT_VR_LITTLE_ENDIAN, } from '../../metadata/dicomLayout'; import { fromBlob, fromUrl, readBytes } from '../../source/byteSource'; -import { trackedSource } from '../../source/__tests__/sourceFixtures'; +import { trackedSource } from '@/tests/byteSourceFixtures'; import { concatBytes } from '../../utils'; import { rawElement, diff --git a/packages/dicom/core/instance/readInstance.ts b/packages/dicom/core/instance/readInstance.ts index 617aae6f1..5dfd64bad 100644 --- a/packages/dicom/core/instance/readInstance.ts +++ b/packages/dicom/core/instance/readInstance.ts @@ -10,11 +10,11 @@ import { readDicomHeader, type ImageImportPolicy, type PixelDataElement, -} from '../streaming/dicom/readDicomHeader'; +} from '../header/readDicomHeader'; import { readUltrasoundRegions, type UltrasoundRegions, -} from '../streaming/dicom/ultrasoundRegion'; +} from '../metadata/ultrasoundRegion'; import type { Awaitable } from '../utils'; /** diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts index 701034e26..7df810002 100644 --- a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -1,13 +1,13 @@ import { readDicomDataset, findElement } from '../dicomDataset'; import { getDatasetTag } from '../datasetAccess'; import { getFrameTag } from '../functionalGroups'; -import { createDicomParser } from '../../streaming/dicom/dicomParser'; +import { createDicomParser } from '../../header/dicomParser'; import { deflateRawSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; import { parseDicomElements } from '../dcmjsParser'; import { PART_10_HEADER_LENGTH, PREAMBLE_LENGTH } from '../dicomLayout'; import { concatBytes } from '../../utils'; -import { buildSlice } from '@/src/io/__tests__/readDicomTagsFixtures'; +import { buildSlice } from '@/tests/specs/dicomElementFixtures'; import { pixelDataStart, readHeader } from '@/tests/dicomSourceFixtures'; import { rawElement, diff --git a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts index 4d4436b4b..b14d8f0da 100644 --- a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts @@ -13,7 +13,7 @@ import { MIXED_VR_ELEMENTS, UTF8_NAME, UTF8_NAME_BYTES, -} from '@/src/io/__tests__/readDicomTagsFixtures'; +} from '@/tests/specs/dicomElementFixtures'; const PATIENT_NAME = '00100010'; const PIXEL_SPACING = '00280030'; diff --git a/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts b/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts index d56e742d4..d4951f9ef 100644 --- a/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts @@ -6,7 +6,7 @@ import { sniffDicomLayout, } from '../dicomLayout'; import { stripFileMeta, stripPreamble } from '@/tests/specs/syntheticDicom'; -import { buildSlice } from '@/src/io/__tests__/readDicomTagsFixtures'; +import { buildSlice } from '@/tests/specs/dicomElementFixtures'; const head = (bytes: Uint8Array) => bytes.subarray(0, PART_10_HEADER_LENGTH); diff --git a/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts b/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts index 1177c24b5..69d62820f 100644 --- a/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts +++ b/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'; import { readDicomDataset } from '../dicomDataset'; import { createMetadataReader } from '../../runtime/metadataReader'; const readDicomDatasetOffThread = createMetadataReader().read; -import { buildSlice } from '@/src/io/__tests__/readDicomTagsFixtures'; +import { buildSlice } from '@/tests/specs/dicomElementFixtures'; // The test DOM has no Worker, so this covers the in-place path only; the // worker path is the same reader behind a message. diff --git a/packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts b/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts similarity index 95% rename from packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts rename to packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts index 7bfbc4519..c95b26c15 100644 --- a/packages/dicom/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts +++ b/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { readDicomDataset } from '../../../metadata/dicomDataset'; -import { concatBytes } from '../../../utils'; +import { readDicomDataset } from '../dicomDataset'; +import { concatBytes } from '../../utils'; import { syntheticSlice } from '@/tests/dicomSourceFixtures'; import { rawElement, sequenceItem } from '@/tests/specs/syntheticDicom'; import { diff --git a/packages/dicom/core/metadata/datasetAccess.ts b/packages/dicom/core/metadata/datasetAccess.ts index 26ee74de1..522ec0fe4 100644 --- a/packages/dicom/core/metadata/datasetAccess.ts +++ b/packages/dicom/core/metadata/datasetAccess.ts @@ -1,10 +1,11 @@ import type { DicomDataset, DicomElement } from './dicomDataset'; import { trimDicomPadding } from '../utils'; -const canonicalTag = (tag: string) => tag.replace('|', '').toUpperCase(); +/** `ggggeeee` or `gggg|eeee`, in either case. */ +export const canonicalTag = (tag: string) => tag.replace('|', '').toUpperCase(); /** Text and numeric values retain multiplicity; sequences and opaque bytes do not become text. */ -export function getElementText(element: DicomElement): string | undefined { +function getElementText(element: DicomElement): string | undefined { const { values } = element; switch (values.kind) { case 'text': diff --git a/packages/dicom/core/metadata/dcmjs.d.ts b/packages/dicom/core/metadata/dcmjs.d.ts index dccff0f97..a74c509fa 100644 --- a/packages/dicom/core/metadata/dcmjs.d.ts +++ b/packages/dicom/core/metadata/dcmjs.d.ts @@ -64,6 +64,10 @@ declare module 'dcmjs' { stream: DicomReadStream ) => DicomReadStream; DicomMessage: { + readFile(buffer: ArrayBuffer): { + dict: Record; + write(): ArrayBuffer; + }; _readTag( stream: DicomReadStream, syntax: string, diff --git a/packages/dicom/core/metadata/dicomDataset.ts b/packages/dicom/core/metadata/dicomDataset.ts index 601ec68ba..1e5f347b9 100644 --- a/packages/dicom/core/metadata/dicomDataset.ts +++ b/packages/dicom/core/metadata/dicomDataset.ts @@ -16,9 +16,9 @@ import { const SPECIFIC_CHARACTER_SET = '00080005'; /** A tag as `ggggeeee` in upper case hexadecimal. */ -export type DicomTagKey = string; +type DicomTagKey = string; -export type AttributeTag = { group: number; element: number }; +type AttributeTag = { group: number; element: number }; /** VRs whose values are text under the default repertoire or a declared set. */ const TEXT_VRS = new Set([ @@ -60,7 +60,7 @@ const KNOWN_VRS = new Set([ 'SQ', ]); -export type DicomValues = +type DicomValues = /** A text VR, one entry per value, with the Specific Character Set applied. */ | { kind: 'text'; values: string[] } /** DS and IS: the numbers, next to the characters the file wrote. A value @@ -94,7 +94,7 @@ export type DicomDataset = { specificCharacterSet: string[] | null; }; -export const tagKey = (group: number, element: number) => +const tagKey = (group: number, element: number) => `${hex4(group)}${hex4(element)}`; export const isPrivateElement = ({ group }: DicomElement) => (group & 1) === 1; diff --git a/packages/dicom/core/metadata/dicomLayout.ts b/packages/dicom/core/metadata/dicomLayout.ts index af3b2c294..8aae9ae53 100644 --- a/packages/dicom/core/metadata/dicomLayout.ts +++ b/packages/dicom/core/metadata/dicomLayout.ts @@ -10,7 +10,7 @@ import { toAscii } from '../utils'; * nothing to name its transfer syntax but the shape of its first element. */ export const PREAMBLE_LENGTH = 128; -export const DICOM_PREFIX = 'DICM'; +const DICOM_PREFIX = 'DICM'; /** The bytes a Part 10 file spends before its first element. */ export const PART_10_HEADER_LENGTH = PREAMBLE_LENGTH + DICOM_PREFIX.length; diff --git a/packages/dicom/core/metadata/dicomTags.ts b/packages/dicom/core/metadata/dicomTags.ts index 4bc1e6fe5..06b164742 100644 --- a/packages/dicom/core/metadata/dicomTags.ts +++ b/packages/dicom/core/metadata/dicomTags.ts @@ -46,6 +46,7 @@ const tags: Tag[] = [ { name: 'SOPClassUID', tag: '0008|0016' }, { name: 'OphthalmicVolumetricPropertiesFlag', tag: '0022|1622' }, { name: 'PhotometricInterpretation', tag: '0028|0004' }, + { name: 'PlanarConfiguration', tag: '0028|0006' }, { name: 'FrameTime', tag: '0018|1063' }, { name: 'SequenceOfUltrasoundRegions', tag: '0018|6011' }, { name: 'PhysicalUnitsXDirection', tag: '0018|6024' }, @@ -71,6 +72,3 @@ export function isUltrasoundMultiframeSopClass(uid: string): boolean { } export const Tags = Object.fromEntries(tags.map((t) => [t.name, t.tag])); - -// Converts an itk-wasm-style "GGGG|EEEE" tag to a dicom-parser element key. -export const toDicomParserKey = (tag: string) => `x${tag.replace('|', '')}`; diff --git a/packages/dicom/core/metadata/functionalGroups.ts b/packages/dicom/core/metadata/functionalGroups.ts index 2f84c1a99..0b0937264 100644 --- a/packages/dicom/core/metadata/functionalGroups.ts +++ b/packages/dicom/core/metadata/functionalGroups.ts @@ -1,6 +1,6 @@ import type { DicomDataset } from './dicomDataset'; import { findElement } from './dicomDataset'; -import { getDatasetTag } from './datasetAccess'; +import { canonicalTag, getDatasetTag } from './datasetAccess'; import { getNmDetectorTag } from './nmReconstruction'; const SHARED_GROUPS = '52009229'; @@ -17,7 +17,7 @@ const IMAGE_MACROS = new Map([ ]); export function sequenceItems(dataset: DicomDataset, tag: string) { - const values = findElement(dataset, tag)?.values; + const values = findElement(dataset, canonicalTag(tag))?.values; return values?.kind === 'sequence' ? values.items : []; } @@ -37,7 +37,7 @@ export function getFrameTag( frameIndex = 0 ) { if (!dataset) return undefined; - const key = tag.replace('|', '').toUpperCase(); + const key = canonicalTag(tag); const macro = IMAGE_MACROS.get(key); if (!macro) return getDatasetTag(dataset, key); const perFrame = sequenceItems(dataset, PER_FRAME_GROUPS)[frameIndex]; diff --git a/packages/dicom/core/metadata/spatialMetadata.ts b/packages/dicom/core/metadata/spatialMetadata.ts index e5406c490..b67d03f6e 100644 --- a/packages/dicom/core/metadata/spatialMetadata.ts +++ b/packages/dicom/core/metadata/spatialMetadata.ts @@ -4,7 +4,7 @@ import { getFrameTag } from './functionalGroups'; import { trimDicomPadding } from '../utils'; /** Describes the spacing actually used by the image, not independent calibration. */ -export type AxisSpacing = { +type AxisSpacing = { value: number; unit: 'mm' | 'unknown'; status: 'declared' | 'derived' | 'fallback'; diff --git a/packages/dicom/core/streaming/dicom/ultrasoundRegion.ts b/packages/dicom/core/metadata/ultrasoundRegion.ts similarity index 65% rename from packages/dicom/core/streaming/dicom/ultrasoundRegion.ts rename to packages/dicom/core/metadata/ultrasoundRegion.ts index 14a9d8885..4482b25fd 100644 --- a/packages/dicom/core/streaming/dicom/ultrasoundRegion.ts +++ b/packages/dicom/core/metadata/ultrasoundRegion.ts @@ -1,8 +1,8 @@ -import { getDatasetTag } from '../../metadata/datasetAccess'; -import { sequenceItems } from '../../metadata/functionalGroups'; -import type { DicomDataset } from '../../metadata/dicomDataset'; -import { trimDicomPadding } from '../../utils'; -import { Tags } from '../../metadata/dicomTags'; +import { getDatasetTag } from './datasetAccess'; +import { sequenceItems } from './functionalGroups'; +import type { DicomDataset } from './dicomDataset'; +import { trimDicomPadding } from '../utils'; +import { Tags } from './dicomTags'; // DICOM unit codes for PhysicalUnitsXDirection / YDirection. // See DICOM PS3.3 C.8.5.5.1.15. The only spatial spacing code defined for @@ -19,13 +19,31 @@ export const unitToMm = (code: number): number | null => { return null; }; -export type UltrasoundRegion = { +/** One item's spacing values, each NaN when absent or not a number. */ +type UltrasoundRegion = { physicalDeltaX: number; physicalDeltaY: number; physicalUnitsXDirection: number; physicalUnitsYDirection: number; }; +const readRegion = (item: DicomDataset): UltrasoundRegion => { + const value = (tag: string) => { + const text = trimDicomPadding(getDatasetTag(item, tag) ?? ''); + return text ? Number(text) : NaN; + }; + return { + physicalDeltaX: value(Tags.PhysicalDeltaX), + physicalDeltaY: value(Tags.PhysicalDeltaY), + physicalUnitsXDirection: value(Tags.PhysicalUnitsXDirection), + physicalUnitsYDirection: value(Tags.PhysicalUnitsYDirection), + }; +}; + +/** Every item of the Sequence of Ultrasound Regions, in order. */ +export const ultrasoundRegionsOf = (dataset: DicomDataset) => + sequenceItems(dataset, Tags.SequenceOfUltrasoundRegions).map(readRegion); + // First-region spacing plus the total number of regions in the source // SequenceOfUltrasoundRegions. Multi-region images (e.g. dual-pane B-mode + // Doppler) cannot be fully represented with a single VTK image spacing, so @@ -39,22 +57,12 @@ export type UltrasoundRegions = { export function readUltrasoundRegions( metadata: DicomDataset ): UltrasoundRegions { - const items = sequenceItems( - metadata, - Tags.SequenceOfUltrasoundRegions.replace('|', '') - ); - const value = (tag: string) => { - const text = trimDicomPadding(getDatasetTag(items[0], tag) ?? ''); - return text ? Number(text) : NaN; - }; - const region = { - physicalDeltaX: value(Tags.PhysicalDeltaX), - physicalDeltaY: value(Tags.PhysicalDeltaY), - physicalUnitsXDirection: value(Tags.PhysicalUnitsXDirection), - physicalUnitsYDirection: value(Tags.PhysicalUnitsYDirection), - }; + const regions = ultrasoundRegionsOf(metadata); + const [region] = regions; return { - regionCount: items.length, - ...(Object.values(region).every(Number.isFinite) ? { region } : {}), + regionCount: regions.length, + ...(region && Object.values(region).every(Number.isFinite) + ? { region } + : {}), }; } diff --git a/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts b/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts index 65367980f..9870a2e1b 100644 --- a/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts +++ b/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts @@ -2,40 +2,58 @@ import { describe, expect, it } from 'vitest'; import { defaultDecoderTable, planDecode, - wholeInstanceDecoderTable, + singleDecoderTable, } from '../decoderTable'; +import { nativeFrameDecoder } from '../nativeFrame'; +import { wholeInstanceDecoder, type PixelDecoder } from '../pixelDecoder'; import { pixelInstance } from './pixelFixture'; +const gdcm = wholeInstanceDecoder('GDCM', () => { + throw new Error('not decoded in these tests'); +}); +const table = defaultDecoderTable(gdcm); + +const declining = (name: string, reason: string): PixelDecoder => ({ + name, + plan: () => ({ declined: reason }), +}); + describe('planDecode', () => { - it('plans native frames for an uncompressed instance it reproduces', async () => { + it('plans a native unit per frame for an uncompressed instance it reproduces', async () => { const { instance } = await pixelInstance({ frames: 3 }); - const plan = planDecode(defaultDecoderTable, instance); + const plan = planDecode(table, instance, Uint16Array); - expect(plan).toMatchObject({ - kind: 'frames', - format: { rows: 5, columns: 3, bitsAllocated: 16 }, - }); - expect(plan.kind === 'frames' && plan.index.frames).toHaveLength(3); + expect('decoder' in plan && plan.decoder).toBe(nativeFrameDecoder); + expect('units' in plan && plan.units).toMatchObject([ + { firstFrame: 0, frames: 1 }, + { firstFrame: 1, frames: 1 }, + { firstFrame: 2, frames: 1 }, + ]); }); - it('hands a declined uncompressed instance to the whole-instance decoder', async () => { + it('falls through to GDCM, whole, when native decoding declines', async () => { const { instance } = await pixelInstance({ photometric: 'MONOCHROME1' }); - expect(planDecode(defaultDecoderTable, instance)).toEqual({ - kind: 'whole-instance', - reason: expect.stringMatching(/MONOCHROME1/), + expect(nativeFrameDecoder.plan(instance, Uint16Array)).toEqual({ + declined: expect.stringMatching(/MONOCHROME1/), + }); + expect(planDecode(table, instance, Uint16Array)).toEqual({ + decoder: gdcm, + units: [ + { firstFrame: 0, frames: 1, range: null, decode: expect.any(Function) }, + ], }); }); it.each([ ['a codec GDCM provides', '1.2.840.10008.1.2.4.90'], ['an unlisted transfer syntax', '1.2.3.4'], - ])('hands %s to the whole-instance decoder', async (_name, syntax) => { + ])('hands %s to GDCM', async (_name, syntax) => { const { instance } = await pixelInstance({ transferSyntaxUid: syntax }); - expect(planDecode(defaultDecoderTable, instance)).toEqual({ - kind: 'whole-instance', + expect(planDecode(table, instance, Uint16Array)).toMatchObject({ + decoder: gdcm, }); }); @@ -44,18 +62,53 @@ describe('planDecode', () => { transferSyntaxUid: '1.2.840.10008.1.2.4.102', }); - const plan = planDecode(defaultDecoderTable, instance); + const plan = planDecode(table, instance, Uint16Array); - expect(plan.kind === 'unsupported' && plan.error.message).toBe( + expect('error' in plan && plan.error.message).toBe( 'Known transfer syntax MPEG-4 AVC/H.264 High Profile (1.2.840.10008.1.2.4.102) has no decoder' ); }); - it('leaves everything to an injected whole-instance decoder', async () => { + it('takes the first candidate that accepts, in the order listed', async () => { const { instance } = await pixelInstance(); + const first = wholeInstanceDecoder('First', () => { + throw new Error('unused'); + }); + const second = wholeInstanceDecoder('Second', () => { + throw new Error('unused'); + }); + const ordered = { + ...singleDecoderTable(first), + fallback: [declining('Picky', 'not today'), first, second], + }; - expect(planDecode(wholeInstanceDecoderTable, instance)).toEqual({ - kind: 'whole-instance', + expect(planDecode(ordered, instance, Uint16Array)).toMatchObject({ + decoder: first, }); }); + + it('says why every candidate declined', async () => { + const { instance } = await pixelInstance(); + const syntax = instance.transferSyntaxUid!; + const picky = { + ...table, + byTransferSyntax: new Map([ + [syntax, [declining('A', 'too big'), declining('B', 'too small')]], + ]), + }; + + const plan = planDecode(picky, instance, Uint16Array); + + expect('error' in plan && plan.error.message).toBe( + 'Known transfer syntax Explicit VR Little Endian (1.2.840.10008.1.2.1) has no decoder: A declined (too big); B declined (too small)' + ); + }); + + it('sends every instance to the one decoder of a single-decoder table', async () => { + const { instance } = await pixelInstance(); + + expect( + planDecode(singleDecoderTable(gdcm), instance, Uint16Array) + ).toMatchObject({ decoder: gdcm }); + }); }); diff --git a/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts b/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts new file mode 100644 index 000000000..f3c956a8c --- /dev/null +++ b/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts @@ -0,0 +1,187 @@ +import { describe, expect, it } from 'vitest'; +import { encapsulatedPixelData, pixelItem } from '@/tests/specs/syntheticDicom'; +import { splitEncapsulatedFrames } from '../encapsulatedFrames'; + +const SOI = [0xff, 0xd8]; +const EOI = [0xff, 0xd9]; + +/** A JPEG-framed codestream whose body is `body`. */ +const jpeg = (...body: number[]) => Uint8Array.from([...SOI, ...body, ...EOI]); + +const bytesOf = (frames: Uint8Array[]) => frames.map((frame) => [...frame]); + +const DELIMITER = Uint8Array.from([0xfe, 0xff, 0xdd, 0xe0, 0, 0, 0, 0]); + +const concat = (...parts: Uint8Array[]) => + Uint8Array.from(parts.flatMap((part) => [...part])); + +describe('splitEncapsulatedFrames', () => { + it('takes frames where a populated offset table says they start', () => { + const frames = [ + [jpeg(1)], + [jpeg(2, 2).subarray(0, 3), jpeg(2, 2).subarray(3)], + ]; + + const split = splitEncapsulatedFrames( + encapsulatedPixelData({ frames, offsetTable: true }), + 2 + ); + + expect(bytesOf(split)).toEqual([[...jpeg(1)], [...jpeg(2, 2)]]); + }); + + it('takes one fragment per frame when the table is empty and the counts match', () => { + const frames = [[jpeg(1)], [jpeg(2)], [jpeg(3)]]; + + const split = splitEncapsulatedFrames(encapsulatedPixelData({ frames }), 3); + + expect(bytesOf(split)).toEqual(frames.map(([only]) => [...only])); + }); + + it('joins fragments up to each JPEG End Of Image when the table is empty', () => { + const first = jpeg(1, 1, 1, 1); + const second = jpeg(2, 2); + const frames = [ + [first.subarray(0, 2), first.subarray(2, 4), first.subarray(4)], + [second.subarray(0, 4), second.subarray(4)], + ]; + + const split = splitEncapsulatedFrames(encapsulatedPixelData({ frames }), 2); + + expect(bytesOf(split)).toEqual([[...first], [...second]]); + }); + + it('ends a frame at an End Of Image followed by one pad byte', () => { + const padded = Uint8Array.from([...jpeg(1), 0]); + const frames = [ + [padded.subarray(0, 2), padded.subarray(2)], + [jpeg(2, 2).subarray(0, 2), jpeg(2, 2).subarray(2)], + ]; + + const split = splitEncapsulatedFrames(encapsulatedPixelData({ frames }), 2); + + expect(bytesOf(split)).toEqual([[...padded], [...jpeg(2, 2)]]); + }); + + it('does not end a frame at an End Of Image followed by a nonzero byte', () => { + const trailed = Uint8Array.from([...jpeg(1), 7]); + const frames = [ + [trailed.subarray(0, 2), trailed.subarray(2)], + [jpeg(2, 2).subarray(0, 2), jpeg(2, 2).subarray(2)], + ]; + + expect(() => + splitEncapsulatedFrames(encapsulatedPixelData({ frames }), 2) + ).toThrow(/found 1 frames in 4 fragments/); + }); + + it('reads a value that ends after its last item without a delimiter', () => { + const value = concat( + pixelItem(new Uint8Array()), + pixelItem(jpeg(1)), + pixelItem(jpeg(2)) + ); + + expect(bytesOf(splitEncapsulatedFrames(value, 2))).toEqual([ + [...jpeg(1)], + [...jpeg(2)], + ]); + }); + + it('stops at the sequence delimiter and ignores what follows', () => { + const value = concat( + encapsulatedPixelData({ frames: [[jpeg(1)], [jpeg(2)]] }), + Uint8Array.from([0xfc, 0xff, 0xfc, 0xff, 4, 0, 0, 0, 9, 9, 9, 9]) + ); + + expect(splitEncapsulatedFrames(value, 2)).toHaveLength(2); + }); + + it('keeps an odd item length as written', () => { + const odd = jpeg(1, 2, 3).subarray(0, 6); + const value = concat( + pixelItem(new Uint8Array()), + pixelItem(odd), + pixelItem(jpeg(2)), + DELIMITER + ); + + expect(bytesOf(splitEncapsulatedFrames(value, 2))).toEqual([ + [...odd], + [...jpeg(2)], + ]); + }); + + it.each([ + [ + 'an item cut short', + encapsulatedPixelData({ frames: [[jpeg(1)], [jpeg(2)]] }).subarray(0, 20), + /needs 5 bytes; 4 remain/, + ], + [ + 'an item head cut short', + encapsulatedPixelData({ frames: [[jpeg(1)], [jpeg(2)]] }).subarray(0, 12), + /item head at byte 8 is cut short/, + ], + [ + 'a tag that is not an item', + concat( + pixelItem(new Uint8Array()), + Uint8Array.from([0xe0, 0x7f, 0x10, 0, 2, 0, 0, 0, 1, 2]) + ), + /expected an item at byte 8/, + ], + [ + 'an item of undefined length', + concat( + pixelItem(new Uint8Array()), + Uint8Array.from([0xfe, 0xff, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff]) + ), + /undefined length/, + ], + [ + 'an offset table whose length is not a multiple of four', + concat(pixelItem(Uint8Array.from([0, 0])), pixelItem(jpeg(1)), DELIMITER), + /Basic Offset Table holds 2 bytes/, + ], + [ + 'an offset that starts no fragment', + concat( + pixelItem(Uint8Array.from([0, 0, 0, 0, 3, 0, 0, 0])), + pixelItem(jpeg(1)), + pixelItem(jpeg(2)), + DELIMITER + ), + /entry 1 \(3\) starts no fragment/, + ], + [ + 'an offset table that skips the first fragment', + concat( + pixelItem(Uint8Array.from([13, 0, 0, 0, 26, 0, 0, 0])), + pixelItem(jpeg(1)), + pixelItem(jpeg(2)), + pixelItem(jpeg(3)), + DELIMITER + ), + /^Malformed encapsulated Pixel Data: Basic Offset Table entry 0 \(13\) skips the first fragment$/, + ], + ['no offset table item', DELIMITER, /no Basic Offset Table/], + [ + 'no fragments', + concat(pixelItem(new Uint8Array()), DELIMITER), + /no fragments/, + ], + ])('rejects %s', (_name, value, error) => { + expect(() => splitEncapsulatedFrames(value, 2)).toThrow(error); + }); + + it('rejects fragments that do not make the declared frame count', () => { + const value = encapsulatedPixelData({ + frames: [[jpeg(1)], [jpeg(2)], [jpeg(3)]], + }); + + expect(() => splitEncapsulatedFrames(value, 2)).toThrow( + /found 3 frames in 3 fragments; the header declares 2/ + ); + }); +}); diff --git a/packages/dicom/core/pixels/decoderTable.ts b/packages/dicom/core/pixels/decoderTable.ts index 8b8581b42..fee95ac7b 100644 --- a/packages/dicom/core/pixels/decoderTable.ts +++ b/packages/dicom/core/pixels/decoderTable.ts @@ -1,128 +1,104 @@ import type { Instance } from '../instance/readInstance'; -import { indexFrames, type FrameIndex } from './frameIndex'; -import { - decodeNativeFrame, - nativeCapability, - type NativePixelFormat, -} from './nativeFrame'; - -/** - * How one transfer syntax decodes: per frame without a codec, as a whole - * instance by the runtime's decoder, or not at all. - */ -export type DecoderEntry = - | Readonly<{ - kind: 'native'; - name: string; - capability: typeof nativeCapability; - decode: typeof decodeNativeFrame; - }> - | Readonly<{ kind: 'whole-instance'; name: string }> - | Readonly<{ kind: 'unsupported'; name: string }>; +import type { VolumeBufferConstructor } from '../volume/pixelFormat'; +import { nativeFrameDecoder } from './nativeFrame'; +import type { DecodeUnit, PixelDecoder } from './pixelDecoder'; +/** Candidates per transfer syntax in preference order; the first that does not decline wins. */ export type DecoderTable = Readonly<{ - byTransferSyntax: ReadonlyMap; + byTransferSyntax: ReadonlyMap; /** For transfer syntaxes the table does not list. */ - fallback: DecoderEntry; + fallback: readonly PixelDecoder[]; + /** Names of known transfer syntaxes, so an error can say which one has no decoder. */ + names: ReadonlyMap; }>; -const native = (name: string): DecoderEntry => ({ - kind: 'native', - name, - capability: nativeCapability, - decode: decodeNativeFrame, -}); -const wholeInstance = (name: string): DecoderEntry => ({ - kind: 'whole-instance', - name, -}); -const unsupported = (name: string): DecoderEntry => ({ - kind: 'unsupported', - name, +/** Every instance goes to `decoder`, whatever its transfer syntax. */ +export const singleDecoderTable = (decoder: PixelDecoder): DecoderTable => ({ + byTransferSyntax: new Map(), + fallback: [decoder], + names: new Map(), }); +type Codec = 'native' | 'gdcm' | 'none'; + // prettier-ignore -const ENTRIES: Array<[string, DecoderEntry]> = [ - ['1.2.840.10008.1.2', native('Implicit VR Little Endian')], - ['1.2.840.10008.1.2.1', native('Explicit VR Little Endian')], - ['1.2.840.10008.1.2.2', native('Explicit VR Big Endian')], - ['1.2.840.10008.1.2.1.99', wholeInstance('Deflated Explicit VR Little Endian')], - ['1.2.840.10008.1.2.4.50', wholeInstance('JPEG Baseline')], - ['1.2.840.10008.1.2.4.51', wholeInstance('JPEG Extended')], - ['1.2.840.10008.1.2.4.57', wholeInstance('JPEG Lossless')], - ['1.2.840.10008.1.2.4.70', wholeInstance('JPEG Lossless, First-Order Prediction')], - ['1.2.840.10008.1.2.4.80', wholeInstance('JPEG-LS Lossless')], - ['1.2.840.10008.1.2.4.81', wholeInstance('JPEG-LS Near-Lossless')], - ['1.2.840.10008.1.2.4.90', wholeInstance('JPEG 2000 Lossless')], - ['1.2.840.10008.1.2.4.91', wholeInstance('JPEG 2000')], - ['1.2.840.10008.1.2.5', wholeInstance('RLE Lossless')], - ['1.2.840.10008.1.2.4.94', unsupported('JPIP Referenced')], - ['1.2.840.10008.1.2.4.95', unsupported('JPIP Referenced Deflate')], - ['1.2.840.10008.1.2.4.100', unsupported('MPEG2 Main Profile')], - ['1.2.840.10008.1.2.4.101', unsupported('MPEG2 High Profile')], - ['1.2.840.10008.1.2.4.102', unsupported('MPEG-4 AVC/H.264 High Profile')], - ['1.2.840.10008.1.2.4.103', unsupported('MPEG-4 AVC/H.264 BD-compatible High Profile')], - ['1.2.840.10008.1.2.4.104', unsupported('MPEG-4 AVC/H.264 High Profile For 2D Video')], - ['1.2.840.10008.1.2.4.105', unsupported('MPEG-4 AVC/H.264 High Profile For 3D Video')], - ['1.2.840.10008.1.2.4.106', unsupported('MPEG-4 AVC/H.264 Stereo High Profile')], - ['1.2.840.10008.1.2.4.107', unsupported('HEVC/H.265 Main Profile')], - ['1.2.840.10008.1.2.4.108', unsupported('HEVC/H.265 Main 10 Profile')], - ['1.2.840.10008.1.2.4.110', unsupported('JPEG XL Lossless')], - ['1.2.840.10008.1.2.4.111', unsupported('JPEG XL JPEG Recompression')], - ['1.2.840.10008.1.2.4.112', unsupported('JPEG XL')], +const SYNTAXES: Array<[string, string, Codec]> = [ + ['1.2.840.10008.1.2', 'Implicit VR Little Endian', 'native'], + ['1.2.840.10008.1.2.1', 'Explicit VR Little Endian', 'native'], + ['1.2.840.10008.1.2.2', 'Explicit VR Big Endian', 'native'], + ['1.2.840.10008.1.2.1.99', 'Deflated Explicit VR Little Endian', 'gdcm'], + ['1.2.840.10008.1.2.4.50', 'JPEG Baseline', 'gdcm'], + ['1.2.840.10008.1.2.4.51', 'JPEG Extended', 'gdcm'], + ['1.2.840.10008.1.2.4.57', 'JPEG Lossless', 'gdcm'], + ['1.2.840.10008.1.2.4.70', 'JPEG Lossless, First-Order Prediction', 'gdcm'], + ['1.2.840.10008.1.2.4.80', 'JPEG-LS Lossless', 'gdcm'], + ['1.2.840.10008.1.2.4.81', 'JPEG-LS Near-Lossless', 'gdcm'], + ['1.2.840.10008.1.2.4.90', 'JPEG 2000 Lossless', 'gdcm'], + ['1.2.840.10008.1.2.4.91', 'JPEG 2000', 'gdcm'], + ['1.2.840.10008.1.2.5', 'RLE Lossless', 'gdcm'], + ['1.2.840.10008.1.2.4.94', 'JPIP Referenced', 'none'], + ['1.2.840.10008.1.2.4.95', 'JPIP Referenced Deflate', 'none'], + ['1.2.840.10008.1.2.4.100', 'MPEG2 Main Profile', 'none'], + ['1.2.840.10008.1.2.4.101', 'MPEG2 High Profile', 'none'], + ['1.2.840.10008.1.2.4.102', 'MPEG-4 AVC/H.264 High Profile', 'none'], + ['1.2.840.10008.1.2.4.103', 'MPEG-4 AVC/H.264 BD-compatible High Profile', 'none'], + ['1.2.840.10008.1.2.4.104', 'MPEG-4 AVC/H.264 High Profile For 2D Video', 'none'], + ['1.2.840.10008.1.2.4.105', 'MPEG-4 AVC/H.264 High Profile For 3D Video', 'none'], + ['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.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 syntaxes per frame; GDCM for every other syntax it may know. */ -export const defaultDecoderTable: DecoderTable = { - byTransferSyntax: new Map(ENTRIES), - fallback: wholeInstance('Unlisted transfer syntax'), -}; - -/** Hands every instance to the runtime's whole-instance decoder. */ -export const wholeInstanceDecoderTable: DecoderTable = { - byTransferSyntax: new Map(), - fallback: wholeInstance('Whole-instance decoder'), -}; +/** Native frames for uncompressed syntaxes, then GDCM for every syntax it may know. */ +export function defaultDecoderTable(gdcm: PixelDecoder): DecoderTable { + const candidates = { + native: [nativeFrameDecoder, gdcm], + gdcm: [gdcm], + none: [], + }; + return { + byTransferSyntax: new Map( + SYNTAXES.map(([uid, , codec]) => [uid, candidates[codec]]) + ), + fallback: [gdcm], + names: new Map(SYNTAXES.map(([uid, name]) => [uid, name])), + }; +} -type IndexedFrames = Extract; +function noDecoder( + table: DecoderTable, + syntax: string | null | undefined, + declines: string[] +) { + const name = syntax ? table.names.get(syntax) : undefined; + const what = name + ? `Known transfer syntax ${name} (${syntax})` + : `Transfer syntax ${syntax ?? 'unknown'}`; + const why = declines.length ? `: ${declines.join('; ')}` : ''; + return new Error(`${what} has no decoder${why}`); +} -export type DecodePlan = - | Readonly<{ - kind: 'frames'; - index: IndexedFrames; - format: NativePixelFormat; - decode: typeof decodeNativeFrame; - }> - /** `reason` says why a native syntax still needs the whole instance. */ - | Readonly<{ kind: 'whole-instance'; reason?: string }> - | Readonly<{ kind: 'unsupported'; error: Error }>; +type DecodePlan = + | Readonly<{ decoder: PixelDecoder; units: DecodeUnit[] }> + | Readonly<{ error: Error }>; -/** How `instance` should decode under `table`. Pure: reads only the header. */ +/** The units the first willing decoder loads `instance` in. Pure: reads only the header. */ export function planDecode( table: DecoderTable, - instance: Instance + instance: Instance, + target: VolumeBufferConstructor ): DecodePlan { const syntax = instance.transferSyntaxUid; - const entry = + const candidates = (syntax && table.byTransferSyntax.get(syntax)) || table.fallback; - if (entry.kind === 'unsupported') - return { - kind: 'unsupported', - error: new Error( - `Known transfer syntax ${entry.name} (${syntax}) has no decoder` - ), - }; - if (entry.kind === 'whole-instance') return { kind: 'whole-instance' }; - const index = indexFrames(instance); - if (index.kind === 'unindexed') - return { kind: 'whole-instance', reason: index.detail }; - const capability = entry.capability(instance, index.littleEndian); - if (capability.kind === 'declined') - return { kind: 'whole-instance', reason: capability.reason }; - return { - kind: 'frames', - index, - format: capability.format, - decode: entry.decode, - }; + const declines: string[] = []; + for (const decoder of candidates) { + const units = decoder.plan(instance, target); + if (!('declined' in units)) return { decoder, units }; + declines.push(`${decoder.name} declined (${units.declined})`); + } + return { error: noDecoder(table, syntax, declines) }; } diff --git a/packages/dicom/core/pixels/encapsulatedFrames.ts b/packages/dicom/core/pixels/encapsulatedFrames.ts new file mode 100644 index 000000000..ac77126e5 --- /dev/null +++ b/packages/dicom/core/pixels/encapsulatedFrames.ts @@ -0,0 +1,139 @@ +const ITEM = 0xe000; +const SEQUENCE_DELIMITER = 0xe0dd; +const ITEM_GROUP = 0xfffe; +const ITEM_HEAD_LENGTH = 8; +const UNDEFINED_LENGTH = 0xffffffff; + +type Fragment = Readonly<{ + /** Offset of the item tag from the first fragment item, as offset tables count. */ + offset: number; + bytes: Uint8Array; +}>; + +const malformed = (detail: string) => + new Error(`Malformed encapsulated Pixel Data: ${detail}`); + +/** The items of an encapsulated Pixel Data value, up to its delimiter or the end. */ +function readItems(value: Uint8Array) { + const view = new DataView(value.buffer, value.byteOffset, value.byteLength); + const items: Array<{ position: number; bytes: Uint8Array }> = []; + let position = 0; + while (position < value.length) { + if (position + ITEM_HEAD_LENGTH > value.length) + throw malformed(`an item head at byte ${position} is cut short`); + const group = view.getUint16(position, true); + const element = view.getUint16(position + 2, true); + const length = view.getUint32(position + 4, true); + if (group === ITEM_GROUP && element === SEQUENCE_DELIMITER) return items; + if (group !== ITEM_GROUP || element !== ITEM) + throw malformed( + `expected an item at byte ${position}, found tag (${group.toString(16)},${element.toString(16)})` + ); + if (length === UNDEFINED_LENGTH) + throw malformed(`the item at byte ${position} has an undefined length`); + const start = position + ITEM_HEAD_LENGTH; + if (start + length > value.length) + throw malformed( + `the item at byte ${position} needs ${length} bytes; ${value.length - start} remain` + ); + items.push({ position, bytes: value.subarray(start, start + length) }); + position = start + length; + } + // A value that ends exactly after its last item is read as if delimited. + return items; +} + +function readOffsetTable(table: Uint8Array) { + if (table.length % 4 !== 0) + throw malformed(`the Basic Offset Table holds ${table.length} bytes`); + const view = new DataView(table.buffer, table.byteOffset, table.byteLength); + return Array.from({ length: table.length / 4 }, (_, index) => + view.getUint32(index * 4, true) + ); +} + +const joinFragments = (fragments: readonly Fragment[]) => { + if (fragments.length === 1) return fragments[0].bytes; + const out = new Uint8Array( + fragments.reduce((total, { bytes }) => total + bytes.length, 0) + ); + fragments.reduce((offset, { bytes }) => { + out.set(bytes, offset); + return offset + bytes.length; + }, 0); + return out; +}; + +function framesFromOffsets(fragments: readonly Fragment[], offsets: number[]) { + const starts = offsets.map((offset, frame) => { + const index = fragments.findIndex((fragment) => fragment.offset === offset); + if (index < 0) + throw malformed( + `Basic Offset Table entry ${frame} (${offset}) starts no fragment` + ); + return index; + }); + if (starts[0] !== 0) + throw malformed( + `Basic Offset Table entry 0 (${offsets[0]}) skips the first fragment` + ); + return starts.map((start, frame) => { + const end = + frame + 1 < starts.length ? starts[frame + 1] : fragments.length; + if (end <= start) + throw malformed( + `Basic Offset Table entry ${frame + 1} does not increase` + ); + return fragments.slice(start, end); + }); +} + +const endsWithEoi = (bytes: Uint8Array) => + bytes.length >= 2 && + bytes[bytes.length - 2] === 0xff && + bytes[bytes.length - 1] === 0xd9; + +// One zero pad byte may follow the marker, since items have even length. +const endsJpegImage = ({ bytes }: Fragment) => + endsWithEoi(bytes) || + (bytes[bytes.length - 1] === 0 && endsWithEoi(bytes.subarray(0, -1))); + +const framesAtJpegEnds = (fragments: readonly Fragment[]) => + fragments.reduce((grouped, fragment, index) => { + if (index === 0 || endsJpegImage(fragments[index - 1])) + grouped.push([fragment]); + else grouped[grouped.length - 1].push(fragment); + return grouped; + }, []); + +/** + * Cuts an encapsulated Pixel Data value (the bytes after its element head) + * into `frameCount` frames. The first item is the Basic Offset Table; its + * offsets decide when it has one per frame. Otherwise one fragment per frame + * when the counts match. Otherwise a frame ends at each fragment ending in a + * JPEG End Of Image marker, so that last rule holds only for JPEG codecs. + * A frame of one fragment is a view into `value`; a frame of several is a copy. + */ +export function splitEncapsulatedFrames(value: Uint8Array, frameCount: number) { + const items = readItems(value); + if (items.length === 0) throw malformed('no Basic Offset Table item'); + const [table, ...rest] = items; + const base = rest[0]?.position ?? 0; + const fragments = rest.map(({ position, bytes }) => ({ + offset: position - base, + bytes, + })); + if (fragments.length === 0) throw malformed('no fragments'); + const offsets = readOffsetTable(table.bytes); + const frames = + offsets.length === frameCount + ? framesFromOffsets(fragments, offsets) + : fragments.length === frameCount + ? fragments.map((fragment) => [fragment]) + : framesAtJpegEnds(fragments); + if (frames.length !== frameCount) + throw malformed( + `found ${frames.length} frames in ${fragments.length} fragments; the header declares ${frameCount}` + ); + return frames.map(joinFragments); +} diff --git a/packages/dicom/core/pixels/frameIndex.ts b/packages/dicom/core/pixels/frameIndex.ts index 4b9031392..e0626080a 100644 --- a/packages/dicom/core/pixels/frameIndex.ts +++ b/packages/dicom/core/pixels/frameIndex.ts @@ -11,14 +11,14 @@ export const EXPLICIT_VR_BIG_ENDIAN = '1.2.840.10008.1.2.2'; export const DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1.99'; /** Transfer syntaxes whose Pixel Data is a plain run of fixed-size frames. */ -export const NATIVE_ENCODINGS: ReadonlyMap = +const NATIVE_ENCODINGS: ReadonlyMap = new Map([ [IMPLICIT_VR_LITTLE_ENDIAN, { littleEndian: true }], [EXPLICIT_VR_LITTLE_ENDIAN, { littleEndian: true }], [EXPLICIT_VR_BIG_ENDIAN, { littleEndian: false }], ]); -export type UnindexedReason = +type UnindexedReason = | 'no-pixel-data' | 'deflated' | 'encapsulated' @@ -31,7 +31,7 @@ export type UnindexedReason = * encapsulated index (offset tables, then a fragment scan) would add an * `encoding: 'encapsulated'` variant whose frames list fragment ranges. */ -export type FrameIndex = +type FrameIndex = | Readonly<{ kind: 'indexed'; encoding: 'native'; diff --git a/packages/dicom/core/pixels/nativeFrame.ts b/packages/dicom/core/pixels/nativeFrame.ts index a8de1696f..de8c73dfb 100644 --- a/packages/dicom/core/pixels/nativeFrame.ts +++ b/packages/dicom/core/pixels/nativeFrame.ts @@ -7,6 +7,8 @@ import { } from '../metadata/modalityRescale'; import { numberOr, trimDicomPadding } from '../utils'; import type { VolumeBufferConstructor } from '../volume/pixelFormat'; +import { indexFrames } from './frameIndex'; +import type { PixelDecoder } from './pixelDecoder'; /** What decides how one native frame's bytes become samples. */ export type NativePixelFormat = Readonly<{ @@ -25,7 +27,7 @@ export type NativePixelFormat = Readonly<{ rescaleIntercept: number; }>; -export type NativeCapability = +type NativeCapability = | Readonly<{ kind: 'native'; format: NativePixelFormat }> | Readonly<{ kind: 'declined'; reason: string }>; @@ -36,7 +38,7 @@ const number = (dataset: DicomDataset, tag: string) => numberOr(getDatasetTag(dataset, tag), NaN); /** The header's pixel description, read without judging it. */ -export function readNativePixelFormat( +function readNativePixelFormat( instance: Instance, littleEndian: boolean ): NativePixelFormat { @@ -234,3 +236,33 @@ export function decodeNativeFrame( ), }; } + +/** Decodes each frame of an instance it reproduces exactly from its own ranged read. */ +export const nativeFrameDecoder: PixelDecoder = { + name: 'Native frames', + plan: (instance, Target) => { + const index = indexFrames(instance); + if (index.kind === 'unindexed') return { declined: index.detail }; + const capability = nativeCapability(instance, index.littleEndian); + if (capability.kind === 'declined') return { declined: capability.reason }; + const { format } = capability; + return index.frames.map((range, frame) => ({ + firstFrame: frame, + frames: 1, + range, + decode: (bytes) => { + const { samples, range: values } = decodeNativeFrame( + bytes, + format, + Target + ); + return { + data: samples, + size: [format.columns, format.rows, 1], + components: format.samplesPerPixel, + range: values, + }; + }, + })); + }, +}; diff --git a/packages/dicom/core/pixels/pixelDecoder.ts b/packages/dicom/core/pixels/pixelDecoder.ts new file mode 100644 index 000000000..76ee33327 --- /dev/null +++ b/packages/dicom/core/pixels/pixelDecoder.ts @@ -0,0 +1,64 @@ +import type { Instance } from '../instance/readInstance'; +import type { ByteRange } from '../source/byteSource'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { numberOr, type Awaitable } from '../utils'; +import type { VolumeBufferConstructor } from '../volume/pixelFormat'; + +/** Samples for `size[2]` consecutive frames, interleaved by component. */ +export type DecodedPixels = Readonly<{ + data: ArrayLike; + /** Columns, rows, frames. */ + size: readonly [number, number, number]; + components: number; + /** + * Each component's [min, max] before conversion into `data`'s element + * type; computed from `data` when absent. + */ + range?: ReadonlyArray; +}>; + +/** One read and one decode. A whole instance is a unit covering every frame. */ +export type DecodeUnit = Readonly<{ + firstFrame: number; + frames: number; + /** Bytes of the instance's source to read; null for all of them. */ + range: ByteRange | null; + /** The returned pixels belong to the caller; `bytes` may be transferred away. */ + decode: (bytes: Uint8Array, signal: AbortSignal) => Awaitable; +}>; + +export type PixelDecoder = Readonly<{ + name: string; + /** + * From the header alone: the units this decoder loads `instance` in, or why + * it declines. `target` is the element type the samples are written into. + */ + plan: ( + instance: Instance, + target: VolumeBufferConstructor + ) => DecodeUnit[] | Readonly<{ declined: string }>; +}>; + +export type WholeInstanceDecode = ( + request: Readonly<{ instance: Instance; bytes: Uint8Array }>, + signal: AbortSignal +) => Awaitable; + +export const frameCount = (instance: Instance) => + numberOr(getDatasetTag(instance.dataset, '00280008'), 1); + +/** A decoder that reads and decodes every instance whole. */ +export const wholeInstanceDecoder = ( + name: string, + decode: WholeInstanceDecode +): PixelDecoder => ({ + name, + plan: (instance) => [ + { + firstFrame: 0, + frames: frameCount(instance), + range: null, + decode: (bytes, signal) => decode({ instance, bytes }, signal), + }, + ], +}); diff --git a/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts b/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts index cd59d41ad..63ed4cf6d 100644 --- a/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts +++ b/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts @@ -1,8 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { createDicomRuntime } from '../createDicomRuntime'; +import { createGdcmDecoder } from '../gdcmDecoder'; import { readDicomDataset } from '../../metadata/dicomDataset'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; -import { enhancedFixtureBytes } from '@/tests/fixtures/dicom-consumer/enhancedFixtures'; +import { instanceFor } from '@/tests/dicomDataset'; +import type { DecodeUnit } from '../../pixels/pixelDecoder'; +import { enhancedFixtureBytes } from '@/tests/fixtures/dicom-pages/enhancedFixtures'; const assets = { pipelineWorkerUrl: '/unused-worker.js', @@ -18,16 +19,21 @@ describe('Default DICOM decoder calibration', () => { [2, 0], ], }); - const runtime = createDicomRuntime({ assets, decodeConcurrency: 1 }); - try { - await expect( - runtime.decode( - { instance: instanceFor(readDicomDataset(bytes)), bytes }, - new AbortController().signal - ) - ).rejects.toThrow('differing modality rescale'); - } finally { - runtime.dispose(); - } + const runs: Uint8Array[] = []; + const gdcm = createGdcmDecoder(assets, 1, () => ({ + run: async (_name: string, data: Uint8Array) => { + runs.push(data); + throw new Error('GDCM ran'); + }, + reset: () => {}, + })); + const instance = instanceFor(readDicomDataset(bytes)); + const [unit] = gdcm.decoder.plan(instance, Float32Array) as DecodeUnit[]; + + await expect( + Promise.resolve(unit.decode(bytes, new AbortController().signal)) + ).rejects.toThrow('differing modality rescale'); + expect(runs).toEqual([]); + gdcm.dispose(new Error('done')); }); }); diff --git a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts index a00fb1fe4..333f294c9 100644 --- a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts +++ b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts @@ -2,26 +2,72 @@ import { describe, expect, it } from 'vitest'; import { createDicomRuntime, defaultDecodeConcurrency, - type PixelDecoder, } from '../createDicomRuntime'; +import { createGdcmDecoder, type GdcmLane } from '../gdcmDecoder'; import { defer } from '../../utils'; import { getDatasetTag } from '../../metadata/datasetAccess'; import { fromBlob } from '../../source/byteSource'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; import { sliceDataset } from '../../collections/__tests__/sliceFixture'; +import type { DecodedPixels, DecodeUnit } from '../../pixels/pixelDecoder'; import { syntheticSlice } from '@/tests/dicomSourceFixtures'; -const request = () => ({ - instance: instanceFor(sliceDataset()), - bytes: new Uint8Array(1), -}); -const decodedImage = { +const assets = { + pipelineWorkerUrl: '/unused-worker.js', + imageIOUrl: '/unused-image-io', +}; +const decodedPixels: DecodedPixels = { size: [1, 1, 1], data: new Uint16Array(1), - imageType: { components: 1 }, + components: 1, }; const signal = () => new AbortController().signal; +/** Lanes whose runs settle when the test says, rejecting on reset like a worker. */ +function controlledLanes() { + let active = 0; + let peak = 0; + const gate = defer(); + const runs: Array<() => void> = []; + const resets: unknown[] = []; + const createLane = (): GdcmLane => { + let rejectRun: ((reason: unknown) => void) | undefined; + return { + run: () => + new Promise((resolve, reject) => { + active += 1; + peak = Math.max(peak, active); + rejectRun = reject; + runs.forEach((started) => started()); + gate.promise.then(() => { + active -= 1; + resolve(decodedPixels); + }); + }), + reset: (reason) => { + resets.push(reason); + rejectRun?.(reason); + }, + }; + }; + const started = (count: number) => + new Promise((resolve) => { + const check = () => active >= count && resolve(); + runs.push(check); + check(); + }); + return { createLane, gate, started, resets, peak: () => peak }; +} + +const decodeWith = ( + gdcm: ReturnType, + abort = signal() +) => { + const instance = instanceFor(sliceDataset()); + const [unit] = gdcm.decoder.plan(instance, Uint16Array) as DecodeUnit[]; + return Promise.resolve(unit.decode(new Uint8Array(1), abort)); +}; + describe('DICOM runtime', () => { it.each([ [undefined, 1], @@ -35,59 +81,48 @@ describe('DICOM runtime', () => { } ); - it('runs at most decodeConcurrency decodes at once', async () => { - let active = 0; - let peak = 0; - const gate = defer(); - const twoStarted = defer(); - const decoder: PixelDecoder = async () => { - active += 1; - peak = Math.max(peak, active); - if (active === 2) twoStarted.resolve(); - await gate.promise; - active -= 1; - return decodedImage; - }; - const runtime = createDicomRuntime({ decoder, decodeConcurrency: 2 }); + it('runs at most its concurrency of GDCM decodes at once', async () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 2, lanes.createLane); - const decodes = [0, 1, 2].map(() => runtime.decode(request(), signal())); - await twoStarted.promise; - gate.resolve(); + const decodes = [0, 1, 2].map(() => decodeWith(gdcm)); + await lanes.started(2); + lanes.gate.resolve(); await Promise.all(decodes); - expect(peak).toBe(2); - runtime.dispose(); + expect(lanes.peak()).toBe(2); + gdcm.dispose(new Error('done')); }); - it('settles running and queued work when disposed', async () => { - const decoder: PixelDecoder = () => new Promise(() => {}); - const runtime = createDicomRuntime({ decoder, decodeConcurrency: 1 }); + it('settles running and queued GDCM decodes when disposed', async () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 1, lanes.createLane); - const running = runtime.decode(request(), signal()); - const queued = runtime.decode(request(), signal()); - runtime.dispose(); + const running = decodeWith(gdcm); + const queued = decodeWith(gdcm); + const reason = new DOMException('disposed', 'AbortError'); + gdcm.dispose(reason); - await expect(running).rejects.toMatchObject({ name: 'AbortError' }); - await expect(queued).rejects.toMatchObject({ name: 'AbortError' }); - await expect( - runtime.readInstance(fromBlob(new Blob([])), signal()) - ).rejects.toMatchObject({ name: 'AbortError' }); + await expect(running).rejects.toBe(reason); + await expect(queued).rejects.toBe(reason); }); - it('settles a decode whose signal aborts', async () => { - const runtime = createDicomRuntime({ - decoder: () => new Promise(() => {}), - }); + it('terminates the GDCM worker of a decode whose signal aborts', async () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 1, lanes.createLane); const controller = new AbortController(); - const decoding = runtime.decode(request(), controller.signal); - controller.abort(new DOMException('stop', 'AbortError')); + const decoding = decodeWith(gdcm, controller.signal); + await lanes.started(1); + const reason = new DOMException('stop', 'AbortError'); + controller.abort(reason); - await expect(decoding).rejects.toMatchObject({ name: 'AbortError' }); - runtime.dispose(); + await expect(decoding).rejects.toBe(reason); + expect(lanes.resets).toEqual([reason]); + gdcm.dispose(reason); }); - it('reads instances with its own metadata reader', async () => { + it('reads instances with its own metadata reader, needing no decoder assets', async () => { const runtime = createDicomRuntime(); const bytes = syntheticSlice({ patientName: 'DOE^JOHN' }); @@ -97,9 +132,17 @@ describe('DICOM runtime', () => { ); expect(getDatasetTag(instance.dataset, '00100010')).toBe('DOE^JOHN'); - await expect(runtime.decode(request(), signal())).rejects.toThrow( - 'Provide DICOM decoder assets or a decoder' - ); runtime.dispose(); + await expect( + runtime.readInstance(fromBlob(new Blob([])), signal()) + ).rejects.toMatchObject({ name: 'AbortError' }); + }); + + it('fails a GDCM decode without assets', async () => { + const gdcm = createGdcmDecoder(undefined, 1); + + await expect(decodeWith(gdcm)).rejects.toThrow( + 'GDCM decoding needs createDicomRuntime({ assets })' + ); }); }); diff --git a/packages/dicom/core/streaming/__tests__/requestPool.spec.ts b/packages/dicom/core/runtime/__tests__/requestPool.spec.ts similarity index 100% rename from packages/dicom/core/streaming/__tests__/requestPool.spec.ts rename to packages/dicom/core/runtime/__tests__/requestPool.spec.ts diff --git a/packages/dicom/core/runtime/createDicomRuntime.ts b/packages/dicom/core/runtime/createDicomRuntime.ts index 81efc5be8..8722b309d 100644 --- a/packages/dicom/core/runtime/createDicomRuntime.ts +++ b/packages/dicom/core/runtime/createDicomRuntime.ts @@ -1,46 +1,30 @@ import type { ByteSource } from '../source/byteSource'; -import { readInstance, type Instance } from '../instance/readInstance'; -import type { ImageImportPolicy } from '../streaming/dicom/readDicomHeader'; -import { RequestPool } from '../streaming/requestPool'; -import { assertUniformModalityRescale } from '../metadata/modalityRescale'; -import { abortError, linkedController, untilAborted } from '../utils/abort'; +import { readInstance } from '../instance/readInstance'; +import type { ImageImportPolicy } from '../header/readDicomHeader'; +import { RequestPool } from './requestPool'; +import { abortError, linkedController, untilAborted } from '../utils'; import { createMetadataReader, type MetadataReaderOptions, } from './metadataReader'; +import { defaultDecoderTable, type DecoderTable } from '../pixels/decoderTable'; +import type { PixelDecoder } from '../pixels/pixelDecoder'; import { - defaultDecoderTable, - wholeInstanceDecoderTable, - type DecoderTable, -} from '../pixels/decoderTable'; -import { - createGdcmLane, - type DecodedDicomImage, + createGdcmDecoder, + type CreateGdcmLane, type DicomAssets, -} from './decoder'; - -/** The unit handed to a decoder: one whole instance and all of its bytes. */ -export type DecodeRequest = { instance: Instance; bytes: Uint8Array }; - -/** Returned pixels belong to the caller; `bytes` may be transferred away. */ -export type PixelDecoder = ( - request: DecodeRequest, - signal: AbortSignal -) => Promise; +} from './gdcmDecoder'; export type DicomRuntimeOptions = MetadataReaderOptions & { fetch?: typeof fetch; requestConcurrency?: number; assets?: DicomAssets; - /** Replaces the GDCM decoder; it owns its own resources. */ - decoder?: PixelDecoder; + /** Builds the decoder table around the runtime's GDCM decoder. */ + decoders?: (gdcm: PixelDecoder) => DecoderTable; /** - * Which transfer syntaxes decode natively per frame. Defaults to native - * frames for uncompressed syntaxes, or, with a supplied `decoder`, to that - * decoder for everything. + * GDCM workers, and the decodes one volume runs at once. Each worker + * carries its own WASM heap. */ - decoders?: DecoderTable; - /** Concurrent decodes. Each GDCM worker carries its own WASM heap. */ decodeConcurrency?: number; imageImportPolicy?: ImageImportPolicy; }; @@ -56,73 +40,15 @@ export const defaultDecodeConcurrency = ( Math.min(MAX_DEFAULT_DECODERS, Math.floor((hardwareConcurrency || 2) / 2)) ); -/** 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 }; -} - -function gdcmDecoder(assets: DicomAssets, count: number) { - const lanes = Array.from({ length: count }, () => createGdcmLane(assets)); - const decodeOn = async ( - index: number, - { instance, bytes }: DecodeRequest, - signal: AbortSignal - ) => { - signal.throwIfAborted(); - assertUniformModalityRescale(instance.dataset); - const lane = lanes[index]; - // 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)).image; - } finally { - signal.removeEventListener('abort', stop); - } - }; - const dispose = (reason: unknown) => - lanes.forEach((lane) => lane.reset(reason)); - return { decodeOn, dispose }; -} - -const missingDecoder = async (): Promise => { - throw new Error('Provide DICOM decoder assets or a decoder'); -}; - /** - * Owns the request pool, the metadata workers and the decode pool. Nothing + * Owns the request pool, the metadata workers and the GDCM 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 = {}) { +export function createDicomRuntime( + options: DicomRuntimeOptions = {}, + createGdcmLane?: CreateGdcmLane +) { const decodeConcurrency = options.decodeConcurrency ?? defaultDecodeConcurrency(globalThis.navigator?.hardwareConcurrency); @@ -131,19 +57,11 @@ export function createDicomRuntime(options: DicomRuntimeOptions = {}) { const lifetime = new AbortController(); const requests = new RequestPool(options.requestConcurrency, options.fetch); const metadata = createMetadataReader(options); - const slots = createSlots(decodeConcurrency); - const gdcm = - options.assets && !options.decoder - ? gdcmDecoder(options.assets, decodeConcurrency) - : null; - const decodeOn = ( - index: number, - request: DecodeRequest, - signal: AbortSignal - ) => - gdcm - ? gdcm.decodeOn(index, request, signal) - : (options.decoder ?? missingDecoder)(request, signal); + const gdcm = createGdcmDecoder( + options.assets, + decodeConcurrency, + createGdcmLane + ); const withLifetime = async ( signal: AbortSignal, @@ -157,16 +75,6 @@ export function createDicomRuntime(options: DicomRuntimeOptions = {}) { } }; - const decode = (request: DecodeRequest, signal: AbortSignal) => - withLifetime(signal, async (linked) => { - const index = await slots.acquire(linked); - try { - return await decodeOn(index, request, linked); - } finally { - slots.release(index); - } - }); - const read = (source: ByteSource, signal: AbortSignal) => withLifetime(signal, (linked) => readInstance(source, linked, { @@ -181,7 +89,7 @@ export function createDicomRuntime(options: DicomRuntimeOptions = {}) { lifetime.abort(reason); requests.dispose(); metadata.dispose(); - gdcm?.dispose(reason); + gdcm.dispose(reason); }; return { @@ -190,13 +98,10 @@ export function createDicomRuntime(options: DicomRuntimeOptions = {}) { /** Aborts when the runtime is disposed. */ signal: lifetime.signal, decodeConcurrency, - decoders: - options.decoders ?? - (options.decoder ? wholeInstanceDecoderTable : defaultDecoderTable), + decoders: (options.decoders ?? defaultDecoderTable)(gdcm.decoder), /** Concurrent requests, which also bounds how far reads run ahead of decoding. */ readConcurrency: requests.poolSize, readInstance: read, - decode, dispose, }; } diff --git a/packages/dicom/core/runtime/decoder.ts b/packages/dicom/core/runtime/decoder.ts deleted file mode 100644 index 3b908070e..000000000 --- a/packages/dicom/core/runtime/decoder.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { - InterfaceTypes, - runPipeline, - type Image, - type TypedArray, -} from 'itk-wasm'; - -export type DecodedDicomImage = { - size: number[]; - data: Exclude; - imageType: { components: number }; -}; -export type DicomAssets = { pipelineWorkerUrl: string; imageIOUrl: string }; - -function decodedImage(result: Awaited>) { - if (result.returnValue !== 0 || !result.outputs[0]?.data) - throw new Error(result.stderr || 'Could not decode DICOM image'); - const image = result.outputs[1]?.data as Image; - if (!image?.data) throw new Error('No pixel data decoded from DICOM image'); - if ( - image.data instanceof BigInt64Array || - image.data instanceof BigUint64Array - ) - throw new Error('DICOM pixel arrays must contain numbers'); - return { - image: { - size: image.size, - data: image.data, - imageType: { components: image.imageType.components }, - }, - }; -} - -/** - * One GDCM pipeline worker, created on first use. A worker error rejects the - * running decode and drops the worker, so the next decode starts a fresh one. - */ -export function createGdcmLane(assets: DicomAssets) { - let worker: Worker | null = null; - let rejectActive: ((reason: unknown) => void) | undefined; - const reset = (reason: unknown) => { - if (worker) { - worker.removeEventListener('error', onError); - worker.removeEventListener('messageerror', onMessageError); - worker.terminate(); - worker = null; - } - rejectActive?.(reason); - }; - const onError = () => reset(new Error('DICOM decoder worker failed')); - const onMessageError = () => - reset(new Error('DICOM decoder worker message failed')); - const startWorker = () => { - const ownedWorker = new Worker(assets.pipelineWorkerUrl, { - type: 'module', - }); - worker = ownedWorker; - const addEventListener = ownedWorker.addEventListener.bind(ownedWorker); - // ITK attaches its message listener asynchronously, after creation. - ownedWorker.addEventListener = ( - ...args: Parameters - ) => { - if (worker !== ownedWorker) - throw new DOMException('DICOM decoder worker stopped', 'AbortError'); - addEventListener(...args); - }; - ownedWorker.addEventListener('error', onError); - ownedWorker.addEventListener('messageerror', onMessageError); - return ownedWorker; - }; - const run = async (name: string, data: Uint8Array) => { - const active = worker ?? startWorker(); - const failed = new Promise((_, rejectFailure) => { - rejectActive = rejectFailure; - }); - try { - const result = await Promise.race([ - runPipeline( - 'gdcm-read-image', - [name, '0', '1', '--memory-io'], - [ - { type: InterfaceTypes.JsonCompatible }, - { type: InterfaceTypes.Image }, - ], - [{ type: InterfaceTypes.BinaryFile, data: { path: name, data } }], - { - webWorker: active, - pipelineWorkerUrl: assets.pipelineWorkerUrl, - pipelineBaseUrl: assets.imageIOUrl, - noCopy: true, - } - ), - failed, - ]); - return decodedImage(result); - } finally { - rejectActive = undefined; - } - }; - return { run, reset }; -} diff --git a/packages/dicom/core/runtime/gdcmDecoder.ts b/packages/dicom/core/runtime/gdcmDecoder.ts new file mode 100644 index 000000000..783d9c099 --- /dev/null +++ b/packages/dicom/core/runtime/gdcmDecoder.ts @@ -0,0 +1,203 @@ +import type { Image, runPipeline, TypedArray } from 'itk-wasm'; +import type { Instance } from '../instance/readInstance'; +import { assertUniformModalityRescale } from '../metadata/modalityRescale'; +import { linkedController, untilAborted } from '../utils'; +import { + wholeInstanceDecoder, + type DecodedPixels, +} from '../pixels/pixelDecoder'; + +export type DicomAssets = { pipelineWorkerUrl: string; imageIOUrl: string }; + +const numeric = (data: TypedArray) => { + if (data instanceof BigInt64Array || data instanceof BigUint64Array) + throw new Error('DICOM pixel arrays must contain numbers'); + return data; +}; + +function decodedPixels( + result: Awaited> +): DecodedPixels { + if (result.returnValue !== 0 || !result.outputs[0]?.data) + throw new Error(result.stderr || 'Could not decode DICOM image'); + const image = result.outputs[1]?.data as Image; + if (!image?.data) throw new Error('No pixel data decoded from DICOM image'); + const [columns, rows, frames = 1] = image.size; + return { + data: numeric(image.data), + size: [columns, rows, frames], + components: image.imageType.components, + }; +} + +/** + * One GDCM pipeline 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 createGdcmLane(assets: DicomAssets) { + let worker: Worker | null = null; + let rejectActive: ((reason: unknown) => void) | undefined; + const reset = (reason: unknown) => { + if (worker) { + worker.removeEventListener('error', onError); + worker.removeEventListener('messageerror', onMessageError); + worker.terminate(); + worker = null; + } + rejectActive?.(reason); + }; + const onError = () => reset(new Error('DICOM decoder worker failed')); + const onMessageError = () => + reset(new Error('DICOM decoder worker message failed')); + const startWorker = () => { + const ownedWorker = new Worker(assets.pipelineWorkerUrl, { + type: 'module', + }); + worker = ownedWorker; + const addEventListener = ownedWorker.addEventListener.bind(ownedWorker); + // ITK attaches its message listener asynchronously, after creation. + ownedWorker.addEventListener = ( + ...args: Parameters + ) => { + if (worker !== ownedWorker) + throw new DOMException('DICOM decoder worker stopped', 'AbortError'); + addEventListener(...args); + }; + ownedWorker.addEventListener('error', onError); + ownedWorker.addEventListener('messageerror', onMessageError); + return ownedWorker; + }; + const run = async (name: string, data: Uint8Array) => { + const failed = new Promise((_, rejectFailure) => { + rejectActive = rejectFailure; + }); + try { + // Loaded on first decode so the core entry point imports outside a browser. + const itk = await Promise.race([import('itk-wasm'), failed]); + const { InterfaceTypes } = itk; + const result = await Promise.race([ + itk.runPipeline( + 'gdcm-read-image', + [name, '0', '1', '--memory-io'], + [ + { type: InterfaceTypes.JsonCompatible }, + { type: InterfaceTypes.Image }, + ], + [{ type: InterfaceTypes.BinaryFile, data: { path: name, data } }], + { + webWorker: worker ?? startWorker(), + pipelineWorkerUrl: assets.pipelineWorkerUrl, + pipelineBaseUrl: assets.imageIOUrl, + noCopy: true, + } + ), + failed, + ]); + return decodedPixels(result); + } finally { + rejectActive = undefined; + } + }; + return { run, reset }; +} + +export type GdcmLane = ReturnType; +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. + */ +export function createGdcmDecoder( + assets: DicomAssets | undefined, + count: number, + createLane: CreateGdcmLane = createGdcmLane +) { + const lifetime = new AbortController(); + const slots = createSlots(count); + const lanes = assets + ? Array.from({ length: count }, () => createLane(assets)) + : []; + + const decodeOn = async ( + index: number, + instance: Instance, + bytes: Uint8Array, + signal: AbortSignal + ) => { + signal.throwIfAborted(); + const lane = lanes[index]; + if (!lane) + throw new Error('GDCM decoding needs createDicomRuntime({ assets })'); + assertUniformModalityRescale(instance.dataset); + // 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 decoder = wholeInstanceDecoder( + 'GDCM', + async ({ instance, bytes }, signal) => { + 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, instance, bytes, 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 { decoder, dispose }; +} diff --git a/packages/dicom/core/streaming/requestPool.ts b/packages/dicom/core/runtime/requestPool.ts similarity index 100% rename from packages/dicom/core/streaming/requestPool.ts rename to packages/dicom/core/runtime/requestPool.ts diff --git a/packages/dicom/core/source/__tests__/byteSource.spec.ts b/packages/dicom/core/source/__tests__/byteSource.spec.ts index 6db993f0b..ea0dd040f 100644 --- a/packages/dicom/core/source/__tests__/byteSource.spec.ts +++ b/packages/dicom/core/source/__tests__/byteSource.spec.ts @@ -1,6 +1,16 @@ import { describe, expect, it } from 'vitest'; import { fromBlob, fromUrl, type ByteRange } from '../byteSource'; -import { readBytes } from './sourceFixtures'; +import { concatBytes } from '../../utils'; + +const readStream = async (stream: ReadableStream) => { + const parts: Uint8Array[] = []; + const reader = stream.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) return concatBytes(parts); + parts.push(value); + } +}; const bytes = Uint8Array.from({ length: 1000 }, (_, index) => index % 251); const expected = (range?: ByteRange) => @@ -64,7 +74,7 @@ describe('blob byte source', () => { ])('reads %j', async (range) => { const source = fromBlob(new Blob([bytes])); expect(source.size).toBe(bytes.length); - expect(await readBytes(source.read(signal(), range))).toEqual( + expect(await readStream(source.read(signal(), range))).toEqual( expected( range && { ...range, @@ -78,7 +88,7 @@ describe('blob byte source', () => { const controller = new AbortController(); const stream = fromBlob(new Blob([bytes])).read(controller.signal); controller.abort(new DOMException('stop', 'AbortError')); - await expect(readBytes(stream)).rejects.toMatchObject({ + await expect(readStream(stream)).rejects.toMatchObject({ name: 'AbortError', }); }); @@ -88,7 +98,7 @@ describe('URL byte source', () => { it('reads the whole resource without a Range header', async () => { const http = server(); const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); - expect(await readBytes(source.read(signal()))).toEqual(bytes); + expect(await readStream(source.read(signal()))).toEqual(bytes); expect(http.requests).toEqual([null]); }); @@ -100,10 +110,10 @@ describe('URL byte source', () => { const http = server(options); const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); - const bounded = await readBytes( + const bounded = await readStream( source.read(signal(), { start: 100, end: 300 }) ); - const open = await readBytes(source.read(signal(), { start: 900 })); + const open = await readStream(source.read(signal(), { start: 900 })); expect(bounded).toEqual(expected({ start: 100, end: 300 })); expect(open).toEqual(expected({ start: 900 })); @@ -121,9 +131,9 @@ describe('URL byte source', () => { fetch: http.fetch, }); expect(source.rangeSupport?.()).toBe('unknown'); - await readBytes(source.read(signal())); + await readStream(source.read(signal())); expect(source.rangeSupport?.()).toBe('unknown'); - await readBytes(source.read(signal(), { start: 10, end: 20 })); + await readStream(source.read(signal(), { start: 10, end: 20 })); expect(source.rangeSupport?.()).toBe(support); expect(http.caches).toEqual([undefined, 'no-store']); } @@ -132,15 +142,15 @@ describe('URL byte source', () => { it('stops the ignored-Range body once the range is read', async () => { const http = server({ honorRange: false }); const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); - await readBytes(source.read(signal(), { start: 0, end: 10 })); + await readStream(source.read(signal(), { start: 0, end: 10 })); expect(http.bodies[0].cancelled).toBe(true); }); it('opens a fresh request for every read', async () => { const http = server(); const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); - await readBytes(source.read(signal(), { start: 0, end: 4 })); - await readBytes(source.read(signal(), { start: 0, end: 4 })); + await readStream(source.read(signal(), { start: 0, end: 4 })); + await readStream(source.read(signal(), { start: 0, end: 4 })); expect(http.requests).toHaveLength(2); }); @@ -151,7 +161,7 @@ describe('URL byte source', () => { const http = server({ status }); const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); await expect( - readBytes(source.read(signal(), { start: 0, end: 4 })) + readStream(source.read(signal(), { start: 0, end: 4 })) ).rejects.toThrow(message); }); diff --git a/packages/dicom/core/utils/__tests__/parseContentRangeHeader.spec.ts b/packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts similarity index 100% rename from packages/dicom/core/utils/__tests__/parseContentRangeHeader.spec.ts rename to packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts diff --git a/packages/dicom/core/source/byteSource.ts b/packages/dicom/core/source/byteSource.ts index 4099deea6..419e7472b 100644 --- a/packages/dicom/core/source/byteSource.ts +++ b/packages/dicom/core/source/byteSource.ts @@ -3,10 +3,10 @@ import { HTTP_STATUS_PARTIAL_CONTENT, HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, HttpNotFound, -} from '../streaming/httpCodes'; -import { linkedController } from '../utils/abort'; +} from './httpCodes'; +import { linkedController } from '../utils'; import { concatBytes } from '../utils'; -import { parseContentRangeHeader } from '../utils/parseContentRangeHeader'; +import { parseContentRangeHeader } from './parseContentRangeHeader'; /** Half-open byte interval; an absent end reads to the last byte. */ export type ByteRange = { start: number; end?: number }; @@ -58,7 +58,7 @@ export const fromBlob = (blob: Blob): ByteSource => ({ }); /** Drops `skip` leading bytes and stops after `length` bytes. */ -export function sliceStream( +function sliceStream( stream: ReadableStream, skip: number, length = Infinity diff --git a/packages/dicom/core/streaming/httpCodes.ts b/packages/dicom/core/source/httpCodes.ts similarity index 100% rename from packages/dicom/core/streaming/httpCodes.ts rename to packages/dicom/core/source/httpCodes.ts diff --git a/packages/dicom/core/utils/parseContentRangeHeader.ts b/packages/dicom/core/source/parseContentRangeHeader.ts similarity index 94% rename from packages/dicom/core/utils/parseContentRangeHeader.ts rename to packages/dicom/core/source/parseContentRangeHeader.ts index c0a00e02f..4e798f127 100644 --- a/packages/dicom/core/utils/parseContentRangeHeader.ts +++ b/packages/dicom/core/source/parseContentRangeHeader.ts @@ -18,7 +18,6 @@ export function parseContentRangeHeader( headerValue: string | null ): ContentRange { if (headerValue == null) return { type: 'empty-range' }; - if (headerValue.length === 0) return { type: 'invalid-range' }; const match = CONTENT_RANGE_REGEXP.exec(headerValue); const groups = match?.groups; diff --git a/packages/dicom/core/utils.ts b/packages/dicom/core/utils.ts index 304ef325a..392900d2e 100644 --- a/packages/dicom/core/utils.ts +++ b/packages/dicom/core/utils.ts @@ -75,3 +75,38 @@ export const numberOr = (value: string | undefined, fallback: number) => { const number = Number(text); return text && Number.isFinite(number) ? number : fallback; }; + +/** + * A controller that aborts as soon as any parent signal does, with its reason. + * `release` detaches it from long-lived parents once its work is done. + */ +export function linkedController(...signals: AbortSignal[]) { + const controller = new AbortController(); + const onAbort = (event: Event) => + controller.abort((event.target as AbortSignal).reason); + const release = () => + signals.forEach((signal) => signal.removeEventListener('abort', onAbort)); + const aborted = signals.find((signal) => signal.aborted); + if (aborted) controller.abort(aborted.reason); + else + signals.forEach((signal) => + signal.addEventListener('abort', onAbort, { once: true }) + ); + controller.signal.addEventListener('abort', release, { once: true }); + return { controller, release }; +} + +export const abortError = (message: string) => + new DOMException(message, 'AbortError'); + +/** Settles with the signal's reason on abort, without stopping the work itself. */ +export function untilAborted(operation: Promise, signal: AbortSignal) { + return new Promise((resolve, reject) => { + const aborted = () => reject(signal.reason); + signal.addEventListener('abort', aborted, { once: true }); + operation + .then(resolve, reject) + .finally(() => signal.removeEventListener('abort', aborted)); + if (signal.aborted) aborted(); + }); +} diff --git a/packages/dicom/core/utils/abort.ts b/packages/dicom/core/utils/abort.ts deleted file mode 100644 index dc0859366..000000000 --- a/packages/dicom/core/utils/abort.ts +++ /dev/null @@ -1,37 +0,0 @@ -/** - * A controller that aborts as soon as any parent signal does, with its reason. - * `release` detaches it from long-lived parents once its work is done. - */ -export function linkedController(...signals: AbortSignal[]) { - const controller = new AbortController(); - const onAbort = (event: Event) => - controller.abort((event.target as AbortSignal).reason); - const release = () => - signals.forEach((signal) => signal.removeEventListener('abort', onAbort)); - const aborted = signals.find((signal) => signal.aborted); - if (aborted) controller.abort(aborted.reason); - else - signals.forEach((signal) => - signal.addEventListener('abort', onAbort, { once: true }) - ); - controller.signal.addEventListener('abort', release, { once: true }); - return { controller, release }; -} - -export const abortError = (message: string) => - new DOMException(message, 'AbortError'); - -export const isAbortError = (error: unknown) => - error instanceof Error && error.name === 'AbortError'; - -/** Settles with the signal's reason on abort, without stopping the work itself. */ -export function untilAborted(operation: Promise, signal: AbortSignal) { - return new Promise((resolve, reject) => { - const aborted = () => reject(signal.reason); - signal.addEventListener('abort', aborted, { once: true }); - operation - .then(resolve, reject) - .finally(() => signal.removeEventListener('abort', aborted)); - if (signal.aborted) aborted(); - }); -} diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts index 4993e33f7..3710e4706 100644 --- a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; -import { sliceDataset } from '../../collections/__tests__/sliceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; import { allocateVolume } from '../allocateVolume'; -import { allocated, pixelSlice, plannedUpdate } from './volumeFixture'; +import { allocated, pixelSlice } from './volumeFixture'; +import { plannedUpdate } from '@/tests/dicomVolumeFixtures'; describe('allocateVolume', () => { it('allocates an empty buffer placed by the planned stack', () => { @@ -57,14 +57,14 @@ describe('allocateVolume', () => { slots: [0, 2], }; - const result = allocateVolume({ + const volume = allocateVolume({ ...update, collection: { ...update.collection, reconstruction }, }); - expect(result).toMatchObject({ - kind: 'volume', - volume: { dimensions: [4, 4, 3], spacing: [0.5, 0.5, 9] }, + expect(volume).toMatchObject({ + dimensions: [4, 4, 3], + spacing: [0.5, 0.5, 9], }); }); @@ -84,17 +84,6 @@ describe('allocateVolume', () => { ).toThrow('slice slot'); }); - it.each(['SEG', 'SEG\u0000'])( - 'reports SEG modality %j as a segmentation outcome instead of allocating it', - (modality) => { - const seg = instanceFor(sliceDataset({ modality })); - - const result = allocateVolume(plannedUpdate([seg])); - - expect(result).toMatchObject({ kind: 'segmentation', members: [seg] }); - } - ); - it('applies the first ultrasound region as display spacing', () => { const { dataset, source } = pixelSlice(0, { modality: 'US' }); const ultrasound = { diff --git a/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts b/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts index fcf33005d..80b6bccd3 100644 --- a/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts +++ b/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts @@ -12,20 +12,13 @@ import { type DicomCollection, } from '../../collections/planDicomCollections'; import type { Reconstruction } from '../../collections/reconstructVolume'; -import { - emptyRegistry, - registerInstances, -} from '../../collections/instanceRegistry'; import { getFrameTag } from '../../metadata/functionalGroups'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; import { createDicomRuntime } from '../../runtime/createDicomRuntime'; import { fromBlob } from '../../source/byteSource'; -import { - allocateVolume, - type Volume, - type VolumeAllocation, -} from '../allocateVolume'; +import { allocateVolume, type Volume } from '../allocateVolume'; import { loadVolume } from '../loadVolume'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import type { IrregularGeometryPolicy } from '../volumeLayout'; import { datasetFromTags } from '../../../../../tests/dicomDataset'; @@ -78,11 +71,6 @@ const ONE_SLOT: Reconstruction = { slots: [0], }; -const asVolume = (allocation: VolumeAllocation) => { - if (allocation.kind !== 'volume') throw new Error('Expected a volume'); - return allocation.volume; -}; - /** Allocates one instance against a supplied plan, as a planner would hand it. */ const allocate = ( metadata: DicomDataset, @@ -91,15 +79,14 @@ const allocate = ( Pick > ) => - asVolume( - allocateVolume( - { - id: 'frames', - collection: { orientation, reconstruction } as DicomCollection, - members: [instanceFor(metadata)], - }, - { irregularGeometry: policy } - ) + allocateVolume( + { + kind: 'image', + id: 'frames', + collection: { orientation, reconstruction } as DicomCollection, + members: [instanceFor(metadata)], + }, + { irregularGeometry: policy } ); const indexToWorld = (volume: Volume, index: number[]) => @@ -177,14 +164,13 @@ describe('enhanced volume Functional Groups', () => { let suppliedMetadata: DicomDataset | undefined; const runtime = createDicomRuntime({ decodeConcurrency: 1, - decoder: async ({ instance }) => { + ...decodingWith(async ({ instance }) => { suppliedMetadata = instance.dataset; - return { size: [2, 2, 2], imageType: { components: 1 }, data: decoded }; - }, + return { size: [2, 2, 2], components: 1, data: decoded }; + }), }); const instance = instanceFor(metadata, fromBlob(new Blob(['pixels']))); - const [update] = registerInstances(emptyRegistry, [instance]).updates; - const volume = asVolume(allocateVolume(update)); + const volume = allocateVolume(plannedUpdate([instance])); for await (const loaded of loadVolume(volume, { runtime, signal: new AbortController().signal, @@ -313,7 +299,7 @@ describe('intra-instance frame planning', () => { it.each([1, -1])( 'preserves stored frame direction %s through registration and image allocation', - async (direction) => { + (direction) => { const positions = [0, 1, 2].map((index) => 10 + direction * index * 3); const instance = instanceFor( enhanced( @@ -321,8 +307,7 @@ describe('intra-instance frame planning', () => { positions.map((z) => positioned(`1\\2\\${z}`)) ) ); - const { updates } = registerInstances(emptyRegistry, [instance]); - const volume = asVolume(allocateVolume(updates[0])); + const volume = allocateVolume(plannedUpdate([instance])); expect(volume.spacing[2]).toBe(3); positions.forEach((z, index) => expect(indexToWorld(volume, [0, 0, index])).toEqual([1, 2, z]) @@ -373,7 +358,7 @@ describe('intra-instance frame planning', () => { [[0, 0, 2], 'repeated-position', REPEATED_POSITIONS_WARNING], ] as const)( 'reports intra-instance geometry %s while retaining one source slot', - async (positions, reason, warning) => { + (positions, reason, warning) => { const metadata = enhanced( ctShared(), positions.map((z) => positioned(`0\\0\\${z}`)) diff --git a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts index 0f3808dac..1560d2ede 100644 --- a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -9,10 +9,13 @@ import { fromUrl, type ByteRange, type ByteSource, + type RangeSupport, } from '../../source/byteSource'; import { loadVolume, type VolumeUpdate } from '../loadVolume'; +import { defaultDecoderTable } from '../../pixels/decoderTable'; +import type { DecodeUnit, PixelDecoder } from '../../pixels/pixelDecoder'; import { allocated } from './volumeFixture'; -import { hangingSource } from '../../source/__tests__/sourceFixtures'; +import { hangingSource } from '@/tests/byteSourceFixtures'; import { nativePixelDicom, patternWords, @@ -51,12 +54,16 @@ const blobOf = (bytes: Uint8Array) => const load = async ( members: Awaited>[], - options: { readAhead?: number; abort?: AbortSignal } = {} + options: { + readAhead?: number; + abort?: AbortSignal; + runtime?: DicomRuntime; + } = {} ) => { const volume = allocated(members); const updates: VolumeUpdate[] = []; for await (const update of loadVolume(volume, { - runtime: nativeOnly(), + runtime: options.runtime ?? nativeOnly(), signal: options.abort ?? signal(), readAhead: options.readAhead, })) @@ -79,6 +86,39 @@ const multiframe = (options: NativePixelOptions = {}) => { }; }; +/** Frame `frame` of `multiframe()`, read from its own range. */ +const frameUnit = (valueOffset: number, frame: number): DecodeUnit => { + const start = valueOffset + frame * 12; + return { + firstFrame: frame, + frames: 1, + range: { start, end: start + 12 }, + decode: (frameBytes) => ({ + data: new Uint16Array(frameBytes.slice().buffer), + size: [3, 2, 1], + components: 1, + }), + }; +}; + +/** 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); + return { + ...table, + byTransferSyntax: new Map([ + ...table.byTransferSyntax, + [codec, [decoder, gdcm]], + ]), + }; + }, + }); + runtimes.push(runtime); + return runtime; +}; + describe('loadVolume with native frames', () => { it('loads each frame of a multiframe instance from its own ranged read', async () => { const { bytes, words } = multiframe(); @@ -212,7 +252,7 @@ describe('loadVolume with native frames', () => { { slot: 0, extent: [0, 2, 0, 1, 0, FRAMES - 1], - error: new Error('Provide DICOM decoder assets or a decoder'), + error: new Error('GDCM decoding needs createDicomRuntime({ assets })'), }, ]); }); @@ -236,4 +276,154 @@ describe('loadVolume with native frames', () => { expect((await loading).updates).toEqual([]); expect(await hanging.cancelled).toBe(reason); }); + + it('loads frame by frame through a per-frame decoder added to the table', async () => { + const codec = '1.2.3.4'; + const { bytes, words } = multiframe({ transferSyntaxUid: codec }); + const { source, ranges } = recorded(blobOf(bytes)); + const instance = await readInstance(source, signal()); + const runtime = runtimeFor(codec, { + name: 'Per-frame codec', + plan: ({ pixelData }) => + Array.from({ length: FRAMES }, (_, frame) => + frameUnit(pixelData!.valueOffset, frame) + ), + }); + + const { volume, updates } = await load([instance], { + readAhead: 1, + runtime, + }); + + const start = instance.pixelData!.valueOffset; + expect(updates.map((update) => update.slot)).toEqual([0, 4, 2, 1, 3]); + expect(ranges.slice(1)).toEqual( + [0, 4, 2, 1, 3].map((frame) => ({ + start: start + frame * 12, + end: start + (frame + 1) * 12, + })) + ); + expect(Array.from(volume.data)).toEqual(words); + }); + + it.each([ + ['no units', () => []], + [ + 'overlapping units', + (offset: number) => + [0, 1, 2, 2, 3, 4].map((frame) => frameUnit(offset, frame)), + ], + [ + 'units that skip a frame', + (offset: number) => [0, 1, 3, 4].map((frame) => frameUnit(offset, frame)), + ], + [ + 'a unit past the last frame', + (offset: number) => + [1, 2, 3, 4, 5].map((frame) => frameUnit(offset, frame)), + ], + ])( + 'fails every slice of an instance whose decoder plans %s', + async (_, units: (offset: number) => DecodeUnit[]) => { + const codec = '1.2.3.4'; + const { bytes } = multiframe({ transferSyntaxUid: codec }); + const { source, ranges } = recorded(blobOf(bytes)); + const instance = await readInstance(source, signal()); + const runtime = runtimeFor(codec, { + name: 'Partial codec', + plan: ({ pixelData }) => units(pixelData!.valueOffset), + }); + + const { volume, updates } = await load([instance], { runtime }); + + expect(updates).toEqual([ + { + slot: 0, + extent: [0, 2, 0, 1, 0, FRAMES - 1], + error: expect.objectContaining({ + message: expect.stringMatching( + /^Partial codec planned units that do not cover frames 0 to 4 of File .* exactly once$/ + ), + }), + }, + ]); + expect(ranges).toEqual([undefined]); + expect(volume.loaded).toEqual(new Uint8Array(FRAMES)); + } + ); + + it.each([ + ['honours', FRAMES], + ['ignores', 2], + ] as const)( + 'probes a source that %s Range with one frame, then makes %i frame reads in all', + async (behaviour, frameReads) => { + const { bytes, words } = multiframe(); + const blob = recorded(blobOf(bytes)); + let support: RangeSupport = 'unknown'; + const source: ByteSource = { + read: (readSignal, range) => { + if (range) support = behaviour === 'honours' ? 'honoured' : 'ignored'; + return blob.source.read(readSignal, range); + }, + rangeSupport: () => support, + }; + const instance = await readInstance(source, signal()); + + const { volume } = await load([instance]); + + const start = instance.pixelData!.valueOffset; + const frame = (index: number, count = 1) => ({ + start: start + index * 12, + end: start + (index + count) * 12, + }); + const [header, probe, ...rest] = blob.ranges; + expect(header).toBeUndefined(); + expect(probe).toEqual(frame(0)); + expect(rest).toHaveLength(frameReads - 1); + expect(rest).toEqual( + behaviour === 'honours' + ? expect.arrayContaining([1, 2, 3, 4].map((index) => frame(index))) + : [frame(1, FRAMES - 1)] + ); + expect(Array.from(volume.data)).toEqual(words); + } + ); + + it('reads frame calibrations in time linear in the frame count', async () => { + const datasetReads = async (frames: number) => { + const bytes = nativePixelDicom({ + rows: 2, + columns: 3, + frames, + words: patternWords(frames * 6, 16), + rescale: [0.1, 0.3], + }); + const instance = await readInstance(blobOf(bytes), signal()); + const { dataset } = instance; + let reads = 0; + const counted = { + ...instance, + dataset: { + ...dataset, + get elements() { + reads += 1; + return dataset.elements; + }, + }, + }; + const { volume, updates } = await load([counted]); + expect(volume.data).toBeInstanceOf(Float32Array); + expect(updates).toHaveLength(frames); + return reads; + }; + + const [ten, twenty, forty] = [ + await datasetReads(10), + await datasetReads(20), + await datasetReads(40), + ]; + + expect(forty - twenty).toBe(2 * (twenty - ten)); + }); }); diff --git a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts index 134685fa4..6393381be 100644 --- a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -2,10 +2,12 @@ import { afterEach, describe, expect, it } from 'vitest'; import { createDicomRuntime, type DicomRuntime, - type PixelDecoder, } from '../../runtime/createDicomRuntime'; +import type { WholeInstanceDecode } from '../../pixels/pixelDecoder'; +import { singleDecoderTable } from '../../pixels/decoderTable'; +import type { GdcmLane } from '../../runtime/gdcmDecoder'; import { defer } from '../../utils'; -import { hangingSource } from '../../source/__tests__/sourceFixtures'; +import { hangingSource } from '@/tests/byteSourceFixtures'; import { loadedRange, type Volume } from '../allocateVolume'; import type { ByteSource } from '../../source/byteSource'; import { @@ -16,15 +18,20 @@ import { import { allocated, pixelSlice, + slicePixels, sliceValues, valueDecoder, } from './volumeFixture'; +import { decodingWith } from '@/tests/dicomVolumeFixtures'; const runtimes: DicomRuntime[] = []; afterEach(() => runtimes.splice(0).forEach((runtime) => runtime.dispose())); -const runtimeWith = (decoder: PixelDecoder, decodeConcurrency = 1) => { - const runtime = createDicomRuntime({ decoder, decodeConcurrency }); +const runtimeWith = (decoder: WholeInstanceDecode, decodeConcurrency = 1) => { + const runtime = createDicomRuntime({ + ...decodingWith(decoder), + decodeConcurrency, + }); runtimes.push(runtime); return runtime; }; @@ -96,10 +103,10 @@ describe('loadVolume', () => { it('reports a failed slice and keeps loading the rest', async () => { const decode = valueDecoder(); - const decoder: PixelDecoder = async (request, signal) => { + const decoder: WholeInstanceDecode = async (request, signal) => { const image = await decode(request, signal); if (image.data[0] === 1) throw new Error('corrupt pixel data'); - if (image.data[0] === 3) return { ...image, size: [2, 8, 1] }; + if (image.data[0] === 3) return { ...image, size: [2, 8, 1] as const }; return image; }; const volume = stack(5); @@ -120,7 +127,7 @@ describe('loadVolume', () => { const decoded: number[] = []; const decode = valueDecoder(decoded); const resume = defer(); - const decoder: PixelDecoder = async (request, signal) => { + const decoder: WholeInstanceDecode = async (request, signal) => { const image = await decode(request, signal); if (decoded.length === 1) await resume.promise; return image; @@ -149,7 +156,7 @@ describe('loadVolume', () => { const { volume, reads, readStarted } = recordedStack(8); let mostOutstanding = 0; const ahead = readStarted(1 + readAhead); - const decoder: PixelDecoder = async (request, signal) => { + const decoder: WholeInstanceDecode = async (request, signal) => { decodesStarted.push(0); mostOutstanding = Math.max( mostOutstanding, @@ -167,6 +174,29 @@ describe('loadVolume', () => { expect(mostOutstanding).toBeLessThanOrEqual(readAhead); }); + it('runs at most decodeConcurrency decodes at once', async () => { + let active = 0; + let peak = 0; + const gate = defer(); + const twoStarted = defer(); + const decode = valueDecoder(); + const decoder: WholeInstanceDecode = async (request, signal) => { + active += 1; + peak = Math.max(peak, active); + if (active === 2) twoStarted.resolve(); + await gate.promise; + active -= 1; + return decode(request, signal); + }; + + const loading = loadAll(stack(5), runtimeWith(decoder, 2)); + await twoStarted.promise; + gate.resolve(); + + expect(await loading).toHaveLength(5); + expect(peak).toBe(2); + }); + it('reports a failed read and keeps loading the rest', async () => { const failing: ByteSource = { read: () => @@ -219,7 +249,7 @@ describe('loadVolume', () => { it('ends when the runtime is disposed during a decode', async () => { const started = defer(); - const decoder: PixelDecoder = () => { + const decoder: WholeInstanceDecode = () => { started.resolve(); return new Promise(() => {}); }; @@ -232,6 +262,90 @@ describe('loadVolume', () => { expect(await loading).toEqual([]); }); + it('keeps decoding while the consumer waits, marking slices loaded only as they are yielded', async () => { + const decoded: number[] = []; + const decode = valueDecoder(decoded); + const lastStarted = defer(); + const decoder: WholeInstanceDecode = (request, signal) => { + if (decoded.length === 4) lastStarted.resolve(); + return decode(request, signal); + }; + const volume = stack(5); + const updates = loadVolume(volume, { + runtime: runtimeWith(decoder), + signal: new AbortController().signal, + })[Symbol.asyncIterator](); + + const first = await updates.next(); + // One decode at a time, so the fifth starts only after four were written. + await lastStarted.promise; + + expect(first.value).toMatchObject({ slot: 2 }); + expect(decoded.slice(0, 4).map((slice) => volume.data[slice * 16])).toEqual( + decoded.slice(0, 4) + ); + expect(sliceValues(volume)).toEqual([null, null, 2, null, null]); + const rest: VolumeUpdate[] = []; + for ( + let next = await updates.next(); + !next.done; + next = await updates.next() + ) + rest.push(next.value); + expect(rest.map((update) => update.slot)).toEqual(decoded.slice(1)); + expect(sliceValues(volume)).toEqual([0, 1, 2, 3, 4]); + }); + + it('writes nothing into the buffer once aborted', async () => { + const controller = new AbortController(); + // Returning synchronously queues any write ahead of the load's own return. + const decoder: WholeInstanceDecode = ({ bytes }) => { + controller.abort(); + return slicePixels(bytes); + }; + const volume = stack(3); + + const updates = await collect( + loadVolume(volume, { + runtime: runtimeWith(decoder), + signal: controller.signal, + }) + ); + + expect(updates).toEqual([]); + expect(volume.data.every((sample) => sample === 0)).toBe(true); + expect(sliceValues(volume)).toEqual([null, null, null]); + }); + + it('ends and stops the GDCM worker when the runtime is disposed mid-decode', async () => { + const started = defer(); + const resets: unknown[] = []; + const hangingLane = (): GdcmLane => ({ + run: () => { + started.resolve(); + return new Promise(() => {}); + }, + reset: (reason) => resets.push(reason), + }); + const runtime = createDicomRuntime( + { + assets: { pipelineWorkerUrl: '/unused', imageIOUrl: '/unused' }, + decoders: singleDecoderTable, + decodeConcurrency: 1, + }, + hangingLane + ); + runtimes.push(runtime); + + const loading = loadAll(stack(2), runtime); + await started.promise; + runtime.dispose(); + + expect(await loading).toEqual([]); + expect(resets).not.toHaveLength(0); + expect(resets[0]).toMatchObject({ name: 'AbortError' }); + }); + it('carries decoded slices into a grown volume without decoding them again', async () => { const decoded: number[] = []; const runtime = runtimeWith(valueDecoder(decoded)); diff --git a/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts b/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts index cd64f65f1..c03609e9b 100644 --- a/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts +++ b/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts @@ -8,7 +8,10 @@ const intoFloat32 = new Float64Array([min, max]), { min, max }, new Float32Array(1), - { where: 'File 1.2.3', rescales: [{ rescaleSlope, rescaleIntercept }] } + { + where: 'File 1.2.3', + rescales: () => [{ rescaleSlope, rescaleIntercept }], + } ); describe('assertSamplesRepresentable into a Float32 volume', () => { @@ -36,7 +39,7 @@ describe('assertSamplesRepresentable into a Float32 volume', () => { new Float32Array(1), { where: 'File 1.2.3', - rescales: [ + rescales: () => [ { rescaleSlope: 1, rescaleIntercept: 0 }, { rescaleSlope: 0.25, rescaleIntercept: 0.5 }, ], diff --git a/packages/dicom/core/volume/__tests__/volumeFixture.ts b/packages/dicom/core/volume/__tests__/volumeFixture.ts index 22242a29e..5391f87d7 100644 --- a/packages/dicom/core/volume/__tests__/volumeFixture.ts +++ b/packages/dicom/core/volume/__tests__/volumeFixture.ts @@ -1,14 +1,11 @@ -import { - emptyRegistry, - registerInstances, -} from '../../collections/instanceRegistry'; import { sliceDataset, type SliceOptions, } from '../../collections/__tests__/sliceFixture'; -import { instanceFor } from '../../instance/__tests__/instanceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; +import { plannedUpdate } from '@/tests/dicomVolumeFixtures'; import type { Instance } from '../../instance/readInstance'; -import type { PixelDecoder } from '../../runtime/createDicomRuntime'; +import type { WholeInstanceDecode } from '../../pixels/pixelDecoder'; import { fromBlob } from '../../source/byteSource'; import { allocateVolume, @@ -36,30 +33,30 @@ export const pixelSlice = (value: number, options: SliceOptions = {}) => fromBlob(new Blob([String(value)])) ); -export const plannedUpdate = (members: Instance[]) => - registerInstances(emptyRegistry, members).updates[0]; - -export function allocated( +export const allocated = ( members: Instance[], previous?: Volume, options: AllocateVolumeOptions = {} -) { - const result = allocateVolume(plannedUpdate(members), options, previous); - if (result.kind !== 'volume') throw new Error(`Allocated ${result.kind}`); - return result.volume; -} +) => allocateVolume(plannedUpdate(members), options, previous); + +/** The slice a source written by `pixelSlice` decodes to. */ +export const slicePixels = (bytes: Uint8Array) => { + const value = Number(new TextDecoder().decode(bytes)); + return { + value, + size: [4, 4, 1] as const, + data: new Uint16Array(PIXELS_PER_SLICE).fill(value), + components: 1, + }; +}; /** Decodes a source written by `pixelSlice`, recording each value it decodes. */ export const valueDecoder = - (decoded: number[] = []): PixelDecoder => + (decoded: number[] = []): WholeInstanceDecode => async ({ bytes }) => { - const value = Number(new TextDecoder().decode(bytes)); + const { value, ...pixels } = slicePixels(bytes); decoded.push(value); - return { - size: [4, 4, 1], - data: new Uint16Array(PIXELS_PER_SLICE).fill(value), - imageType: { components: 1 }, - }; + return pixels; }; /** The first sample of every slice, or null where none is loaded yet. */ diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts index 49f17d1bf..117f2c40c 100644 --- a/packages/dicom/core/volume/allocateVolume.ts +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -1,5 +1,5 @@ import type { Instance } from '../instance/readInstance'; -import type { InstanceCollectionUpdate } from '../collections/instanceRegistry'; +import type { ImageCollectionUpdate } from '../collections/instanceRegistry'; import type { DicomCollection } from '../collections/planDicomCollections'; import type { Reconstruction } from '../collections/reconstructVolume'; import type { SpatialMetadata } from '../metadata/spatialMetadata'; @@ -36,18 +36,6 @@ export type Volume = Readonly<{ loaded: Uint8Array; }>; -/** SEG pixels are labels that a segmentation reader turns into its own image. */ -export type SegmentationAllocation = { - kind: 'segmentation'; - id: string; - members: readonly Instance[]; - reconstruction: Reconstruction; -}; - -export type VolumeAllocation = - | { kind: 'volume'; volume: Volume } - | SegmentationAllocation; - export type AllocateVolumeOptions = { irregularGeometry?: IrregularGeometryPolicy; }; @@ -105,25 +93,22 @@ function copyDecoded(volume: Volume, previous: Volume) { } /** - * Allocates the volume a planned collection fills. With `previous`, slices - * already decoded there are copied across, so growth never decodes again. + * Allocates the volume a planned image collection fills. With `previous`, + * slices already decoded there are copied across, so growth never decodes + * again. */ export function allocateVolume( - update: Pick, + update: Pick, options: AllocateVolumeOptions = {}, previous?: Volume -): VolumeAllocation { +) { const { id, collection, members } = update; - const planned = planVolumeAllocation( + const { reconstruction, layout, warnings } = planVolumeAllocation( members, collection.orientation, collection.reconstruction, options.irregularGeometry ?? 'preserve-order' ); - const { reconstruction } = planned; - if (planned.kind === 'segmentation') - return { kind: 'segmentation', id, members, reconstruction }; - const { layout } = planned; const { columns, rows, slices, samplesPerPixel } = layout; const volume: Volume = Object.freeze({ id, @@ -138,12 +123,12 @@ export function allocateVolume( (axis) => axis.value ) as unknown as Vector3, spatialMetadata: layout.spatialMetadata, - warnings: planned.warnings, + warnings, data: new layout.bufferType(columns * rows * slices * samplesPerPixel), loaded: new Uint8Array(slices), }); if (previous) copyDecoded(volume, previous); - return { kind: 'volume', volume }; + return volume; } /** Per-component [min, max] over the loaded slices; empty when none are. */ diff --git a/packages/dicom/core/volume/loadVolume.ts b/packages/dicom/core/volume/loadVolume.ts index d5b7a7a73..3630fc1d6 100644 --- a/packages/dicom/core/volume/loadVolume.ts +++ b/packages/dicom/core/volume/loadVolume.ts @@ -1,22 +1,17 @@ -import type { DecodedDicomImage } from '../runtime/decoder'; import type { DicomRuntime } from '../runtime/createDicomRuntime'; +import type { Instance } from '../instance/readInstance'; import { getDatasetTag } from '../metadata/datasetAccess'; import { Tags } from '../metadata/dicomTags'; -import { abortError, linkedController } from '../utils/abort'; +import { numberOr } from '../utils'; +import { abortError, linkedController } from '../utils'; +import { readBytes } from '../source/byteSource'; +import { planDecode, type DecoderTable } from '../pixels/decoderTable'; import { - readBytes, - type ByteRange, - type ByteSource, -} from '../source/byteSource'; -import { - planDecode, - type DecodePlan, - type DecoderTable, -} from '../pixels/decoderTable'; -import { - instancePixelFormats, - type VolumeBufferConstructor, -} from './pixelFormat'; + frameCount, + type DecodedPixels, + type DecodeUnit, +} from '../pixels/pixelDecoder'; +import { getPixelFormat, type VolumeBufferConstructor } from './pixelFormat'; import { componentRanges, memberLoaded, @@ -25,10 +20,10 @@ import { type Volume, } from './allocateVolume'; import { - assertChunkFitsSlot, assertSamplesRepresentable, assertSingleFramePerFile, - type DecodedChunkImage, + assertUnitFits, + type UnitShape, } from './pixelValidation'; import { pickNextSlot } from './slotOrder'; @@ -46,7 +41,7 @@ export type VolumeUpdate = export type LoadVolumeOptions = { runtime: Pick< DicomRuntime, - 'decode' | 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' + 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' >; signal: AbortSignal; /** Read before every read and decode; defaults to the middle member's slot. */ @@ -59,6 +54,10 @@ export type LoadVolumeOptions = { readAhead?: number; }; +/** A planned unit placed in the volume; `slot` is its first slice. */ +type Unit = DecodeUnit & + Readonly<{ member: number; slices: readonly number[]; slot: number }>; + const ensureError = (error: unknown) => error instanceof Error ? error : new Error(String(error)); @@ -71,6 +70,16 @@ const sliceExtent = (volume: Volume, slices: readonly number[]): Extent => [ Math.max(...slices), ]; +const failure = ( + volume: Volume, + slices: readonly number[], + error: unknown +): VolumeUpdate => ({ + slot: Math.min(...slices), + extent: sliceExtent(volume, slices), + error: ensureError(error), +}); + const memberName = (volume: Volume, member: number) => { const sop = getDatasetTag( volume.members[member].dataset, @@ -79,347 +88,306 @@ const memberName = (volume: Volume, member: number) => { return `File ${sop ?? 'without SOP Instance UID'} (member ${member})`; }; -function assertMemberFits( - volume: Volume, - member: number, - image: DecodedChunkImage -) { - const { dimensions, components, members } = volume; - const where = memberName(volume, member); - assertSingleFramePerFile(image.size[2], members.length, where); - assertChunkFitsSlot( - image, - { - dims: [...dimensions], - componentCount: components, - count: members.length, - }, - where - ); +const unitName = (volume: Volume, unit: Unit) => { + const name = memberName(volume, unit.member); + return unit.frames === memberSlices(volume, unit.member).length + ? name + : `${name}, frame ${unit.firstFrame}`; +}; + +function headerShape(instance: Instance): UnitShape { + const value = (tag: string, fallback: number) => + numberOr(getDatasetTag(instance.dataset, tag), fallback); + const [columns, rows] = [value(Tags.Columns, 0), value(Tags.Rows, 0)]; + const components = value(Tags.SamplesPerPixel, 1); + const frames = frameCount(instance); + return { + size: [columns, rows, frames], + components, + samples: columns * rows * frames * components, + }; } -type Rescale = { rescaleSlope: number; rescaleIntercept: number }; +const roomFor = (volume: Volume, frames: number) => ({ + dims: volume.dimensions, + components: volume.components, + frames, + multiFile: volume.members.length > 1, +}); -function assertRepresentable( +/** A Float32 volume holds rounded values, so the range it reports is rounded too. */ +const storedRange = ( volume: Volume, - { - samples, - range, - }: { samples: ArrayLike; range: Array<[number, number]> }, - where: string, - rescales: readonly Rescale[] -) { + range: ReadonlyArray +) => { + const stored = volume.data instanceof Float32Array ? Math.fround : Number; + return range.map(([min, max]): [number, number] => [ + stored(min), + stored(max), + ]); +}; + +/** Validates decoded pixels and writes them into the buffer. */ +function write(volume: Volume, unit: Unit, pixels: DecodedPixels) { + const where = unitName(volume, unit); + const { data, size, components } = pixels; + assertUnitFits( + { size, components, samples: data.length }, + roomFor(volume, unit.frames), + where + ); + const range = pixels.range ?? componentRanges(data, volume.components); + const { dataset } = volume.members[unit.member]; assertSamplesRepresentable( - samples, + data, { min: Math.min(...range.map(([min]) => min)), max: Math.max(...range.map(([, max]) => max)), }, volume.data, - { where, rescales } - ); -} - -/** A Float32 volume holds rounded values, so the range it reports is rounded too. */ -const storedRange = (volume: Volume, range: Array<[number, number]>) => - volume.data instanceof Float32Array - ? range.map(([min, max]): [number, number] => [ - Math.fround(min), - Math.fround(max), - ]) - : range; - -function writeMember(volume: Volume, member: number, image: DecodedDicomImage) { - assertMemberFits(volume, member, image); - const range = componentRanges(image.data, volume.components); - assertRepresentable( - volume, - { samples: image.data, range }, - memberName(volume, member), - instancePixelFormats(volume.members[member].dataset) + { + where, + rescales: () => + Array.from({ length: unit.frames }, (_, index) => + getPixelFormat(dataset, unit.firstFrame + index) + ), + } ); - const slices = memberSlices(volume, member); - volume.data.set(image.data, sliceLength(volume) * slices[0]); - slices.forEach((slice) => { - volume.loaded[slice] = 1; - }); + volume.data.set(data, sliceLength(volume) * unit.slot); return { - slot: slices[0], - extent: sliceExtent(volume, slices), + slot: unit.slot, + extent: sliceExtent(volume, unit.slices), range: storedRange(volume, range), }; } -type FramePlan = Extract; - -function writeFrame( - volume: Volume, - unit: FrameUnit, - plan: FramePlan, - bytes: Uint8Array -) { - const { samples, range } = plan.decode( - bytes, - plan.format, - volume.data.constructor as VolumeBufferConstructor +/** Whether the units cover frames 0 to `frames - 1` exactly once, in any order. */ +const tiles = (units: readonly DecodeUnit[], frames: number) => { + const covered = units.flatMap((unit) => + Array.from({ length: unit.frames }, (_, index) => unit.firstFrame + index) ); - const where = `${memberName(volume, unit.member)}, frame ${unit.frame}`; - assertRepresentable(volume, { samples, range }, where, [plan.format]); - volume.data.set(samples, sliceLength(volume) * unit.slot); - volume.loaded[unit.slot] = 1; - return { - slot: unit.slot, - extent: sliceExtent(volume, [unit.slot]), - range: storedRange(volume, range), - }; -} + return ( + units.every((unit) => Number.isInteger(unit.frames) && unit.frames >= 1) && + covered.length === frames && + covered.every( + (frame) => Number.isInteger(frame) && frame >= 0 && frame < frames + ) && + new Set(covered).size === frames + ); +}; -type WholeUnit = Readonly<{ kind: 'instance'; slot: number; member: number }>; -type FrameUnit = Readonly<{ - kind: 'frame'; - slot: number; - member: number; - frame: number; - range: ByteRange; -}>; -type Unit = WholeUnit | FrameUnit; +function planMember(volume: Volume, member: number, decoders: DecoderTable) { + const instance = volume.members[member]; + const slices = memberSlices(volume, member); + const target = volume.data.constructor as VolumeBufferConstructor; + const planned = planDecode(decoders, instance, target); + if ('error' in planned) throw planned.error; + const where = memberName(volume, member); + const header = headerShape(instance); + assertSingleFramePerFile(header.size[2], volume.members.length, where); + assertUnitFits(header, roomFor(volume, slices.length), where); + if (!tiles(planned.units, slices.length)) + throw new Error( + `${planned.decoder.name} planned units that do not cover frames 0 to ${slices.length - 1} of ${where} exactly once` + ); + return planned.units.map((unit): Unit => { + const covered = slices.slice( + unit.firstFrame, + unit.firstFrame + unit.frames + ); + return { ...unit, member, slices: covered, slot: covered[0] }; + }); +} -/** - * Units still to load and failures known from headers alone. An indexable - * instance contributes a unit per frame; any other one is a single unit. - */ -function planUnits( - volume: Volume, - decoders: DecoderTable -): { units: Unit[]; plans: DecodePlan[]; failures: VolumeUpdate[] } { +/** Units still to load, and failures known from headers alone. */ +function planUnits(volume: Volume, decoders: DecoderTable) { const units: Unit[] = []; const failures: VolumeUpdate[] = []; - const plans = volume.members.map((instance, member) => { - const plan = planDecode(decoders, instance); - const slices = memberSlices(volume, member); - const fail = (error: Error) => - failures.push({ - slot: slices[0], - extent: sliceExtent(volume, slices), - error, - }); - if (memberLoaded(volume, member)) return plan; - if (plan.kind === 'unsupported') fail(plan.error); - else if (plan.kind === 'whole-instance') - units.push({ kind: 'instance', slot: slices[0], member }); - else { - try { - const { rows, columns, samplesPerPixel } = plan.format; - const frames = plan.index.frames.length; - assertMemberFits(volume, member, { - size: [columns, rows, frames], - data: { length: columns * rows * frames * samplesPerPixel }, - imageType: { components: samplesPerPixel }, - }); - plan.index.frames.forEach((range, frame) => { - const slot = slices[frame]; - if (!volume.loaded[slot]) - units.push({ kind: 'frame', slot, member, frame, range }); - }); - } catch (error) { - fail(ensureError(error)); - } + volume.members.forEach((_, member) => { + if (memberLoaded(volume, member)) return; + try { + units.push( + ...planMember(volume, member, decoders).filter((unit) => + unit.slices.some((slice) => !volume.loaded[slice]) + ) + ); + } catch (error) { + failures.push(failure(volume, memberSlices(volume, member), error)); } - return plan; }); - return { units, plans, failures }; + return { units, failures }; } /** The first slice of the middle member, the default focus. */ export const middleSlot = (volume: Volume) => memberSlices(volume, Math.floor(volume.members.length / 2))[0]; -/** Wakes every waiter on any change; checks and waits happen in one turn. */ -function changes() { - const waiters: Array<() => void> = []; - return { - notify: () => waiters.splice(0).forEach((wake) => wake()), - next: () => - new Promise((resolve) => { - waiters.push(resolve); - }), - }; -} - -type Lanes = { +type Loader = { volume: Volume; runtime: LoadVolumeOptions['runtime']; stopped: AbortSignal; focus: () => number; + readAhead: number; }; -const rangeSupport = (source: ByteSource) => - source.rangeSupport?.() ?? 'honoured'; +/** An update waiting to be yielded, with the slices it marks loaded then. */ +type Settled = Readonly<{ update: VolumeUpdate; slices: readonly number[] }>; -function createLanes({ volume, runtime, stopped, focus }: Lanes) { - const { units, plans, failures } = planUnits(volume, runtime.decoders); - const unitAt = new Map(units.map((unit) => [unit.slot, unit])); - const framesOf = (member: number) => - units.filter((unit) => unit.kind === 'frame' && unit.member === member); - const claimed = new Set(); - /** Multiframe members whose source has not yet shown it honours ranges. */ +/** + * Starts reads and decodes whenever one settles: decodes first, up to the + * decode concurrency, then reads while fewer than `readAhead` units are being + * read or wait to decode. A decoded unit is written at once, so decoding never + * waits for the consumer. + */ +function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { + const { units, failures } = planUnits(volume, runtime.decoders); + const waiting = new Map(units.map((unit) => [unit.slot, unit])); + const ready = new Map(); + /** Members whose source has not yet shown it honours ranges. */ const probing = new Set(); - const fetched = new Map(); - const updates: VolumeUpdate[] = [...failures]; - const changed = changes(); + const updates: Settled[] = failures.map((update) => ({ + update, + slices: [], + })); let reading = 0; - let readers = 0; - stopped.addEventListener('abort', changed.notify, { once: true }); - - const loaded = (unit: Unit) => - unit.kind === 'frame' - ? volume.loaded[unit.slot] === 1 - : memberLoaded(volume, unit.member); - const failure = (slots: number[], error: unknown): VolumeUpdate => ({ - slot: Math.min(...slots), - extent: sliceExtent( + let decoding = 0; + let wake: (() => void) | undefined; + + const notify = () => { + wake?.(); + wake = undefined; + }; + const changed = () => + new Promise((resolve) => { + wake = resolve; + }); + stopped.addEventListener('abort', notify, { once: true }); + + const settle = (settled: Settled) => { + if (!stopped.aborted) updates.push(settled); + notify(); + }; + const failed = (lost: Unit[], error: unknown): Settled => ({ + update: failure( volume, - slots.flatMap((slot) => { - const unit = unitAt.get(slot)!; - return unit.kind === 'frame' - ? [slot] - : memberSlices(volume, unit.member); - }) + lost.flatMap((unit) => unit.slices), + error ), - error: ensureError(error), + slices: [], }); - const unclaimed = () => - units - .filter( - (unit) => - !claimed.has(unit.slot) && !probing.has(unit.member) && !loaded(unit) - ) - .map((unit) => unit.slot); + const next = (slots: Iterable) => pickNextSlot(slots, focus()); + const sourceOf = (unit: Unit) => volume.members[unit.member].source; + const rangeSupport = (unit: Unit) => + sourceOf(unit).rangeSupport?.() ?? 'honoured'; - // A server that ignores Range would resend the file for every frame, so - // such a member's remaining frames come from one read of its pixel data. - const pending = (unit: FrameUnit) => - rangeSupport(volume.members[unit.member].source) === 'ignored' - ? framesOf(unit.member).filter( + // A server that ignores Range would resend the file for every unit, so the + // remaining ranged units of that member come from one read. + const batchOf = (unit: Unit) => + unit.range?.end !== undefined && rangeSupport(unit) === 'ignored' + ? [...waiting.values()].filter( (other) => - other === unit || (!claimed.has(other.slot) && !loaded(other)) + other.member === unit.member && other.range?.end !== undefined ) : [unit]; - const readFrames = async (frames: Unit[]) => { - const ranges = frames.map((unit) => (unit as FrameUnit).range); - const start = Math.min(...ranges.map((range) => range.start)); - const end = Math.max(...ranges.map((range) => range.end!)); - const bytes = await readBytes( - volume.members[frames[0].member].source, - stopped, - { start, end } - ); - ranges.forEach((range, index) => - fetched.set( - frames[index].slot, - bytes.subarray(range.start - start, range.end! - start) - ) + const readUnits = async (batch: Unit[]) => { + const [first] = batch; + if (batch.length === 1) + return [ + await readBytes(sourceOf(first), stopped, first.range ?? undefined), + ]; + const start = Math.min(...batch.map((unit) => unit.range!.start)); + const end = Math.max(...batch.map((unit) => unit.range!.end!)); + const bytes = await readBytes(sourceOf(first), stopped, { start, end }); + return batch.map(({ range }) => + bytes.subarray(range!.start - start, range!.end! - start) ); }; - const read = async (unit: Unit) => { - const { source } = volume.members[unit.member]; - const frames = unit.kind === 'frame' ? pending(unit) : [unit]; - frames.forEach((each) => claimed.add(each.slot)); - const plan = plans[unit.member]; + const startRead = (unit: Unit) => { + const batch = batchOf(unit); + batch.forEach((each) => waiting.delete(each.slot)); const probe = - plan.kind === 'frames' && - plan.index.frames.length > 1 && - rangeSupport(source) === 'unknown'; + unit.range !== null && + rangeSupport(unit) === 'unknown' && + [...waiting.values()].some((other) => other.member === unit.member); if (probe) probing.add(unit.member); reading += 1; - try { - if (unit.kind === 'frame') await readFrames(frames); - else fetched.set(unit.slot, await readBytes(source, stopped)); - } catch (error) { - if (!stopped.aborted) - updates.push( - failure( - frames.map((each) => each.slot), - error - ) - ); - } finally { - if (probe) probing.delete(unit.member); - reading -= 1; - changed.notify(); - } - }; - const decode = async (slot: number, bytes: Uint8Array) => { - const unit = unitAt.get(slot)!; - if (unit.kind === 'frame') { - stopped.throwIfAborted(); - return writeFrame(volume, unit, plans[unit.member] as FramePlan, bytes); - } - const instance = volume.members[unit.member]; - const image = await runtime.decode({ instance, bytes }, stopped); - stopped.throwIfAborted(); - return writeMember(volume, unit.member, image); + readUnits(batch) + .then( + (bytes) => + batch.forEach((each, index) => + ready.set(each.slot, { unit: each, bytes: bytes[index] }) + ), + (error) => settle(failed(batch, error)) + ) + .finally(() => { + if (probe) probing.delete(unit.member); + reading -= 1; + pump(); + }); }; - const settle = async (slot: number, bytes: Uint8Array) => { + + const written = (unit: Unit, pixels: DecodedPixels): Settled => { try { - updates.push(await decode(slot, bytes)); + return { update: write(volume, unit, pixels), slices: unit.slices }; } catch (error) { - if (!stopped.aborted) updates.push(failure([slot], error)); + return failed([unit], error); } }; - const reader = async (readAhead: number) => { - while (!stopped.aborted) { - if (reading + fetched.size >= readAhead) await changed.next(); - else { - const slot = pickNextSlot(unclaimed(), focus()); - if (slot !== undefined) await read(unitAt.get(slot)!); - else if (probing.size === 0) return; - else await changed.next(); - } - } + const startDecode = (slot: number) => { + const { unit, bytes } = ready.get(slot)!; + ready.delete(slot); + decoding += 1; + (async () => unit.decode(bytes, stopped))() + .then( + (pixels) => (stopped.aborted ? undefined : written(unit, pixels)), + (error) => failed([unit], error) + ) + .then((settled) => { + decoding -= 1; + if (settled) settle(settled); + pump(); + }); }; - const decoder = async () => { - while (!stopped.aborted) { - const slot = pickNextSlot(fetched.keys(), focus()); - if (slot !== undefined) { - const bytes = fetched.get(slot)!; - fetched.delete(slot); - changed.notify(); - await settle(slot, bytes); - changed.notify(); - } else if (readers === 0) return; - else await changed.next(); - } - }; + const claimable = () => + [...waiting.values()] + .filter((unit) => !probing.has(unit.member)) + .map((unit) => unit.slot); - const start = (readAhead: number) => { - readers = readAhead; - Array.from({ length: readAhead }).forEach(() => - reader(readAhead).finally(() => { - readers -= 1; - changed.notify(); - }) - ); - return Promise.all( - Array.from({ length: runtime.decodeConcurrency }, decoder) - ); - }; + const nextDecode = () => + !stopped.aborted && decoding < runtime.decodeConcurrency + ? next(ready.keys()) + : undefined; + const nextRead = () => + !stopped.aborted && reading + ready.size < readAhead + ? next(claimable()) + : undefined; - return { start, updates, changed }; + function pump() { + for (let slot = nextDecode(); slot !== undefined; slot = nextDecode()) + startDecode(slot); + for (let slot = nextRead(); slot !== undefined; slot = nextRead()) + startRead(waiting.get(slot)!); + notify(); + } + + const done = () => waiting.size + ready.size + reading + decoding === 0; + + return { start: pump, updates, changed, done }; } /** * Decodes the slices not yet loaded, the focused slot first and then coarse - * to fine, writing each into the volume's buffer. An uncompressed instance - * loads frame by frame from ranged reads; any other one is read and decoded - * whole. Reads run ahead of decoding in the same order. A failed unit yields - * an error update and loading goes on. Aborting `signal`, disposing the runtime or leaving the loop stops reads - * and decodes; the iteration then returns rather than throwing, and yields - * nothing more. + * to fine, writing each into the volume's buffer as it decodes and marking it + * loaded as its update is yielded. Each instance loads in the + * units its first willing decoder in the runtime's table plans. Reads run + * ahead of decoding in the same order. A failed unit yields an error update + * and loading goes on. Aborting `signal`, disposing the runtime or leaving + * the loop stops reads and decodes; the iteration then returns rather than + * throwing, and yields nothing more. */ export async function* loadVolume( volume: Volume, @@ -434,18 +402,18 @@ export async function* loadVolume( throw new Error('Read ahead must be a positive integer'); const { controller, release } = linkedController(signal, runtime.signal); const stopped = controller.signal; - const lanes = createLanes({ volume, runtime, stopped, focus }); - let finished = false; - lanes.start(readAhead).finally(() => { - finished = true; - lanes.changed.notify(); - }); + const loader = createLoader({ volume, runtime, stopped, focus, readAhead }); + loader.start(); try { for (;;) { - const next = stopped.aborted ? undefined : lanes.updates.shift(); - if (next) yield next; - else if (stopped.aborted || finished) return; - else await lanes.changed.next(); + const next = stopped.aborted ? undefined : loader.updates.shift(); + if (next) { + next.slices.forEach((slice) => { + volume.loaded[slice] = 1; + }); + yield next.update; + } else if (stopped.aborted || loader.done()) return; + else await loader.changed(); } } finally { controller.abort(abortError('DICOM volume loading stopped')); diff --git a/packages/dicom/core/volume/pixelValidation.ts b/packages/dicom/core/volume/pixelValidation.ts index ea972203c..9cb9676ea 100644 --- a/packages/dicom/core/volume/pixelValidation.ts +++ b/packages/dicom/core/volume/pixelValidation.ts @@ -5,12 +5,12 @@ import { samplesAreIntegral, } from './pixelFormat'; -/** What a whole-instance decode returns, before it is written into a volume. */ -export type DecodedChunkImage = { - size: number[]; - data: { length: number } | null | undefined; - imageType: { components: number }; -}; +/** What a unit decodes to, or what its header says it will. */ +export type UnitShape = Readonly<{ + size: readonly number[]; + components: number; + samples: number; +}>; export function assertSamplesRepresentable( decoded: ArrayLike, @@ -21,13 +21,16 @@ export function assertSamplesRepresentable( rescales, }: { where: string; - /** Every frame calibration the samples went through. */ - rescales: ReadonlyArray<{ rescaleSlope: number; rescaleIntercept: number }>; + /** Every frame calibration the samples went through; read only for Float32. */ + rescales: () => ReadonlyArray<{ + rescaleSlope: number; + rescaleIntercept: number; + }>; } ) { const unheld = buffer instanceof Float32Array - ? rescales.find((rescale) => !float32Holds(range, rescale)) + ? rescales().find((rescale) => !float32Holds(range, rescale)) : undefined; if (unheld) { throw new Error( @@ -62,7 +65,6 @@ export function assertSingleFramePerFile( where: string ) { if (frames > 1 && count > 1) { - // we're trying to load multiple chunks where individual chunks have multiple frames throw new Error( `Loading a single volume from multiple DICOM files where individual files contain multiple frames is not supported. ` + `${where} contains ${frames} frames.` @@ -70,46 +72,46 @@ export function assertSingleFramePerFile( } } -// Each chunk gets a fixed slot: one frame per chunk in a multi-file volume, -// or the whole volume when a single multi-frame chunk fills it. A decoded -// chunk has to fill its slot exactly. -export function assertChunkFitsSlot( - image: DecodedChunkImage, - volume: { dims: number[]; componentCount: number; count: number }, +// One frame per file in a multi-file volume, or any run of a lone instance's +// frames. A decoded unit has to fill its slices exactly. +export function assertUnitFits( + unit: UnitShape, + volume: Readonly<{ + dims: readonly number[]; + components: number; + frames: number; + multiFile: boolean; + }>, where: string ) { - const { dims, componentCount, count } = volume; - const multiFile = count > 1; - const framesPerChunk = multiFile ? 1 : dims[2]; - const [chunkWidth, chunkHeight] = image.size; - const chunkFrames = image.size[2] ?? 1; - const chunkComponents = image.imageType.components; - assertSampleCount(image, where); + const { dims, components, frames, multiFile } = volume; + const [width, height, unitFrames = 1] = unit.size; + assertSampleCount(unit, where); if ( - chunkWidth !== dims[0] || - chunkHeight !== dims[1] || - chunkFrames !== framesPerChunk || - chunkComponents !== componentCount + width !== dims[0] || + height !== dims[1] || + unitFrames !== frames || + unit.components !== components ) { - // A lone chunk defines the volume it fails to fit, so advice about + // A lone instance defines the volume it fails to fit, so advice about // agreeing with the other files only makes sense for a multi-file volume. const advice = multiFile ? ' Every file in a volume must have the same Rows, Columns, and SamplesPerPixel.' : ''; throw new Error( `${where} does not fit the volume it belongs to. ` + - `It decoded to ${chunkWidth}x${chunkHeight}x${chunkFrames} with ${chunkComponents} component(s), ` + - `but the volume has room for ${dims[0]}x${dims[1]}x${framesPerChunk} with ${componentCount} component(s).` + + `It decoded to ${width}x${height}x${unitFrames} with ${unit.components} component(s), ` + + `but the volume has room for ${dims[0]}x${dims[1]}x${frames} with ${components} component(s).` + advice ); } } -function assertSampleCount(image: DecodedChunkImage, where: string) { - const [width, height, frames = 1] = image.size; - const expected = width * height * frames * image.imageType.components; - if (image.data?.length !== expected) +function assertSampleCount(unit: UnitShape, where: string) { + const [width, height, frames = 1] = unit.size; + const expected = width * height * frames * unit.components; + if (unit.samples !== expected) throw new Error( - `${where} decoded ${image.data?.length ?? 0} samples; expected ${expected}` + `${where} decoded ${unit.samples} samples; expected ${expected}` ); } diff --git a/packages/dicom/core/volume/ultrasoundSpacing.ts b/packages/dicom/core/volume/ultrasoundSpacing.ts index cea2f8e0e..cdeb59d38 100644 --- a/packages/dicom/core/volume/ultrasoundSpacing.ts +++ b/packages/dicom/core/volume/ultrasoundSpacing.ts @@ -1,5 +1,5 @@ import { getDatasetModality } from '../metadata/datasetAccess'; -import { unitToMm } from '../streaming/dicom/ultrasoundRegion'; +import { unitToMm } from '../metadata/ultrasoundRegion'; import { physicalSpacing, type SpatialMetadata, diff --git a/packages/dicom/core/volume/volumeLayout.ts b/packages/dicom/core/volume/volumeLayout.ts index 1d449444d..1116cae65 100644 --- a/packages/dicom/core/volume/volumeLayout.ts +++ b/packages/dicom/core/volume/volumeLayout.ts @@ -1,11 +1,10 @@ import type { DicomDataset } from '../metadata/dicomDataset'; -import { getDatasetTag, getDatasetModality } from '../metadata/datasetAccess'; +import { getDatasetTag } from '../metadata/datasetAccess'; import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; import { reconstructInstances, type Reconstruction, } from '../collections/reconstructVolume'; -import { multiframeGeometry } from '../collections/multiframeGeometry'; import { readDatasetDetails } from '../collections/datasetDetails'; import { declaredSpacing, @@ -14,7 +13,7 @@ import { type SpatialMetadata, } from '../metadata/spatialMetadata'; import { getFrameTag } from '../metadata/functionalGroups'; -import type { UltrasoundRegions } from '../streaming/dicom/ultrasoundRegion'; +import type { UltrasoundRegions } from '../metadata/ultrasoundRegion'; import { numberOr } from '../utils'; import { nmGeometry } from './nmGeometry'; import { getVolumeBufferType, instancePixelFormats } from './pixelFormat'; @@ -55,9 +54,6 @@ const instanceGeometry = (dataset: DicomDataset, count: number) => { const nm = nmGeometry(dataset); if (nm) return nm; if (count < 2) return null; - // SEG planning does not judge segment-major frames as one spatial stack. - if (getDatasetModality(dataset) === 'SEG') - return multiframeGeometry(dataset, count); return readDatasetDetails(dataset).frameGeometry; }; @@ -100,7 +96,7 @@ function assertSliceSlots(slots: number[], count: number) { (count > 0 && slots[0] !== 0) ) throw new Error( - 'Reconstruction must map each chunk to one distinct nonnegative slice slot, starting at zero' + 'Reconstruction must map each instance to one distinct nonnegative slice slot, starting at zero' ); } @@ -112,7 +108,7 @@ function allocationShape( const numberOfFrames = numberOr(valueOf(NumberOfFrames), 1); if (numberOfFrames > 1 && sources.length > 1) throw new Error( - 'First chunk in a group of chunks (size > 1) is a multi-frame chunk' + 'A multi-frame instance cannot share a volume with other instances' ); return { rows: numberOr(valueOf(RowsTag), 0), @@ -199,7 +195,7 @@ export function volumeLayout( irregularGeometry: IrregularGeometryPolicy = 'preserve-order' ) { if (sources.length === 0) - throw new Error('Cannot allocate an image from zero chunks'); + throw new Error('Cannot allocate an image from zero instances'); assertRegularGeometry(reconstruction, irregularGeometry); assertSliceSlots(reconstruction.slots, sources.length); const shape = allocationShape(sources, reconstruction); @@ -220,8 +216,6 @@ export function volumeLayout( }; } -export type VolumeLayout = ReturnType; - const reconstructionFor = ( sources: readonly VolumeSource[], orientation: number[] | null, @@ -238,10 +232,7 @@ const reconstructionFor = ( ); }; -/** - * Plans an allocation for planned members. SEG yields no layout, since its - * pixels are labels that a segmentation reader turns into its own image. - */ +/** Plans an allocation for the planned members of an image collection. */ export function planVolumeAllocation( sources: readonly VolumeSource[], orientation: number[] | null, @@ -249,11 +240,9 @@ export function planVolumeAllocation( policy: IrregularGeometryPolicy ) { if (sources.length === 0) - throw new Error('Cannot allocate an image from zero chunks'); + throw new Error('Cannot allocate an image from zero instances'); const reconstruction = reconstructionFor(sources, orientation, supplied); const warnings: Array<[string, string]> = []; - if (getDatasetModality(sources[0].dataset) === 'SEG') - return { kind: 'segmentation' as const, reconstruction, warnings }; const layout = volumeLayout(sources, orientation, reconstruction, policy); const spatialMetadata = applyUltrasoundSpacing( layout.spatialMetadata, @@ -261,7 +250,6 @@ export function planVolumeAllocation( (...warning) => warnings.push(warning) ); return { - kind: 'volume' as const, reconstruction, layout: { ...layout, spatialMetadata }, warnings, diff --git a/packages/dicom/package.json b/packages/dicom/package.json deleted file mode 100644 index 601a90293..000000000 --- a/packages/dicom/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "@volview/dicom", - "version": "0.0.0", - "private": true, - "type": "module", - "files": [ - "dist", - "core", - "vtk" - ], - "exports": { - "./core/*": { - "types": "./dist/core/*.d.ts", - "import": "./dist/core/*.js" - }, - "./vtk/*": { - "types": "./dist/vtk/*.d.ts", - "import": "./dist/vtk/*.js" - }, - "./assets/*": "./dist/assets/*" - }, - "dependencies": { - "@itk-wasm/image-io": "1.6.1", - "comlink": "^4.4.2", - "dcmjs": "^0.52.0", - "gl-matrix": "3.4.3", - "itk-wasm": "^1.0.0-b.199", - "mitt": "^3.0.1" - }, - "peerDependencies": { - "@kitware/vtk.js": "^38.0.0" - }, - "peerDependenciesMeta": { - "@kitware/vtk.js": { - "optional": true - } - } -} diff --git a/packages/dicom/scripts/build.mjs b/packages/dicom/scripts/build.mjs deleted file mode 100644 index ce251206e..000000000 --- a/packages/dicom/scripts/build.mjs +++ /dev/null @@ -1,95 +0,0 @@ -import { execFileSync } from 'node:child_process'; -import { cp, mkdir, readFile, readdir } from 'node:fs/promises'; -import { createRequire } from 'node:module'; -import { dirname, relative, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { build } from 'vite'; - -const packageRoot = fileURLToPath(new URL('..', import.meta.url)); -const root = resolve(packageRoot, '../..'); -const require = createRequire(import.meta.url); -const outDir = resolve(packageRoot, process.argv[2] ?? 'dist'); -const manifest = JSON.parse( - await readFile(resolve(packageRoot, 'package.json'), 'utf8') -); -const dependencies = Object.keys({ - ...manifest.dependencies, - ...manifest.peerDependencies, -}); -const external = (id) => - dependencies.some((name) => id === name || id.startsWith(`${name}/`)); - -async function sourceFiles(directory) { - const entries = await readdir(directory, { withFileTypes: true }); - const files = await Promise.all( - entries.map((entry) => { - const file = resolve(directory, entry.name); - if (entry.isDirectory()) - return entry.name === '__tests__' ? [] : sourceFiles(file); - return entry.name.endsWith('.ts') && !/\.(d|worker)\.ts$/.test(entry.name) - ? [file] - : []; - }) - ); - return files.flat(); -} - -const sources = ( - await Promise.all( - ['core', 'vtk'].map((dir) => sourceFiles(resolve(packageRoot, dir))) - ) -).flat(); - -await build({ - configFile: false, - root: packageRoot, - publicDir: false, - base: './', - build: { - outDir, - emptyOutDir: true, - sourcemap: true, - lib: { - entry: Object.fromEntries( - sources.map((file) => [ - relative(packageRoot, file) - .replaceAll('\\', '/') - .replace(/\.ts$/, ''), - file, - ]) - ), - formats: ['es'], - fileName: (_format, entry) => `${entry}.js`, - }, - rollupOptions: { external }, - }, - worker: { format: 'es' }, -}); -execFileSync( - process.execPath, - [ - require.resolve('typescript/bin/tsc'), - '-p', - 'packages/dicom/tsconfig.build.json', - '--outDir', - outDir, - ], - { cwd: root, stdio: 'inherit' } -); - -const moduleRoot = (name) => resolve(dirname(require.resolve(name)), '..'); -const assets = resolve(outDir, 'assets'); -await mkdir(resolve(assets, 'image-io'), { recursive: true }); -await cp( - resolve( - moduleRoot('itk-wasm'), - 'dist/pipeline/web-workers/bundles/itk-wasm-pipeline.min.worker.js' - ), - resolve(assets, 'itk-wasm-pipeline.min.worker.js') -); -const pipelines = resolve(moduleRoot('@itk-wasm/image-io'), 'dist/pipelines'); -for (const name of await readdir(pipelines)) { - if (/^gdcm-read-image\.(js|wasm|wasm\.zst)$/.test(name)) { - await cp(resolve(pipelines, name), resolve(assets, 'image-io', name)); - } -} diff --git a/packages/dicom/scripts/check-consumers.mjs b/packages/dicom/scripts/check-consumers.mjs deleted file mode 100644 index 31a0411c2..000000000 --- a/packages/dicom/scripts/check-consumers.mjs +++ /dev/null @@ -1,97 +0,0 @@ -import { execFileSync } from 'node:child_process'; -import { cp, mkdtemp, rm, writeFile } from 'node:fs/promises'; -import { createRequire } from 'node:module'; -import { tmpdir } from 'node:os'; -import { resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; -import { build } from 'vite'; - -const root = resolve(fileURLToPath(new URL('../../..', import.meta.url))); -const packageRoot = resolve(root, 'packages/dicom'); -const fixture = resolve(root, 'tests/fixtures/dicom-consumer'); -const require = createRequire(import.meta.url); - -const forbiddenModule = (id, kind) => { - const path = id.replaceAll('\\', '/'); - return ( - path.startsWith(`${root.replaceAll('\\', '/')}/src/`) || - /\/node_modules\/(vue|pinia|@vue\/|@vueuse\/)/.test(path) || - (kind === 'core' && path.includes('/node_modules/@kitware/vtk.js/')) - ); -}; - -export async function buildConsumer( - kind, - outDir, - packageDist = resolve(packageRoot, 'dist') -) { - await build({ - configFile: false, - root: fixture, - publicDir: false, - base: './', - resolve: { - alias: { - '@volview/dicom': packageDist, - }, - }, - plugins: [ - { - name: 'independent-dicom-consumer', - generateBundle() { - for (const id of this.getModuleIds()) { - if (forbiddenModule(id, kind)) - this.error(`Unexpected ${kind} consumer dependency: ${id}`); - } - }, - }, - ], - build: { - outDir, - emptyOutDir: true, - rollupOptions: { input: resolve(fixture, `${kind}.html`) }, - }, - worker: { format: 'es' }, - }); - await cp(resolve(packageDist, 'assets'), resolve(outDir, 'assets'), { - recursive: true, - }); -} - -async function checkDeclarations(directory) { - const config = { - extends: resolve(root, 'tsconfig.json'), - compilerOptions: { - baseUrl: root, - types: ['node'], - typeRoots: [resolve(root, 'node_modules/@types')], - paths: { - '@volview/dicom/core/*': ['packages/dicom/dist/core/*'], - '@volview/dicom/vtk/*': ['packages/dicom/dist/vtk/*'], - }, - }, - include: [`${fixture}/*.ts`], - exclude: [], - }; - const configPath = resolve(directory, 'tsconfig.json'); - await writeFile(configPath, JSON.stringify(config)); - execFileSync( - process.execPath, - [require.resolve('typescript/bin/tsc'), '-p', configPath], - { cwd: root, stdio: 'inherit' } - ); -} - -if ( - process.argv[1] && - import.meta.url === pathToFileURL(resolve(process.argv[1])).href -) { - const directory = await mkdtemp(resolve(tmpdir(), 'dicom-consumers-')); - try { - await checkDeclarations(directory); - for (const kind of ['core', 'vtk']) - await buildConsumer(kind, resolve(directory, kind)); - } finally { - await rm(directory, { recursive: true, force: true }); - } -} diff --git a/packages/dicom/tsconfig.build.json b/packages/dicom/tsconfig.build.json deleted file mode 100644 index 0a535382c..000000000 --- a/packages/dicom/tsconfig.build.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "noEmit": false, - "allowImportingTsExtensions": true, - "emitDeclarationOnly": true, - "declaration": true, - "declarationMap": true, - "outDir": "./dist", - "rootDir": ".", - "types": [], - "baseUrl": ".", - "paths": {} - }, - "include": [ - "core/**/*.ts", - "vtk/**/*.ts" - ], - "exclude": [ - "**/__tests__/**", - "dist" - ] -} diff --git a/src/core/streaming/__tests__/dicomThumbnail.spec.ts b/packages/dicom/vtk/__tests__/thumbnail.spec.ts similarity index 97% rename from src/core/streaming/__tests__/dicomThumbnail.spec.ts rename to packages/dicom/vtk/__tests__/thumbnail.spec.ts index e1c97c170..2975ed3c7 100644 --- a/src/core/streaming/__tests__/dicomThumbnail.spec.ts +++ b/packages/dicom/vtk/__tests__/thumbnail.spec.ts @@ -1,8 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { - sliceToThumbnail, - THUMBNAIL_MAX_SIZE, -} from '@/packages/dicom/vtk/thumbnail'; +import { sliceToThumbnail, THUMBNAIL_MAX_SIZE } from '../thumbnail'; const bytes = (slice: { data: Uint8Array }) => Array.from(slice.data); diff --git a/packages/dicom/vtk/__tests__/volumeImage.spec.ts b/packages/dicom/vtk/__tests__/volumeImage.spec.ts index 0b2eff89e..18f7e08d5 100644 --- a/packages/dicom/vtk/__tests__/volumeImage.spec.ts +++ b/packages/dicom/vtk/__tests__/volumeImage.spec.ts @@ -8,6 +8,7 @@ import { pixelSlice, valueDecoder, } from '../../core/volume/__tests__/volumeFixture'; +import { decodingWith } from '@/tests/dicomVolumeFixtures'; import type { Volume } from '../../core/volume/allocateVolume'; import { applyVolumeUpdate, @@ -29,7 +30,7 @@ const rangeOf = (image: vtkImageData) => [ async function loadRanges(volume: Volume) { const image = toVtkImageData(volume); const runtime = createDicomRuntime({ - decoder: valueDecoder(), + ...decodingWith(valueDecoder()), decodeConcurrency: 1, }); const ranges: number[][] = []; @@ -80,7 +81,7 @@ describe('vtk volume adapter', () => { it('replaces the placeholder even when every slice loaded before the first update applies', async () => { const volume = stack([300, 301, 302]); const image = toVtkImageData(volume); - const runtime = createDicomRuntime({ decoder: valueDecoder() }); + const runtime = createDicomRuntime(decodingWith(valueDecoder())); const updates = []; for await (const update of loadVolume(volume, { runtime, diff --git a/packages/dicom/vtk/index.ts b/packages/dicom/vtk/index.ts new file mode 100644 index 000000000..2b9dc7179 --- /dev/null +++ b/packages/dicom/vtk/index.ts @@ -0,0 +1,9 @@ +// Volume image +export { + toVtkImageData, + applyVolumeUpdate, + sliceThumbnail, +} from './volumeImage'; + +// Thumbnails +export { encodeThumbnailToUri, type ThumbnailSlice } from './thumbnail'; diff --git a/packages/dicom/vtk/thumbnail.ts b/packages/dicom/vtk/thumbnail.ts index 5aa48b7ea..8433aa63f 100644 --- a/packages/dicom/vtk/thumbnail.ts +++ b/packages/dicom/vtk/thumbnail.ts @@ -5,7 +5,7 @@ export type ThumbnailSlice = { data: Uint8Array; }; -export type SliceToThumbnailInput = { +type SliceToThumbnailInput = { data: ArrayLike; width: number; height: number; diff --git a/src/components/__tests__/ControlsStripTools.enFace.spec.ts b/src/components/__tests__/ControlsStripTools.enFace.spec.ts index cbe15d840..943a8ec0f 100644 --- a/src/components/__tests__/ControlsStripTools.enFace.spec.ts +++ b/src/components/__tests__/ControlsStripTools.enFace.spec.ts @@ -98,7 +98,7 @@ describe('En face contrast toolbar availability', () => { ).toMatch(/scan pattern.*reconstruction/); }); - it('shows the Paint panel reason on the disabled toolbar action', async () => { + it('shows the Paint panel reason on the disabled toolbar action', () => { const wrapper = mountToolbar('missing'); const selector = 'button[data-testid^="control-button-Paint "]'; const action = wrapper diff --git a/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts index f7b337742..24de812ed 100644 --- a/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts +++ b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts @@ -12,22 +12,21 @@ import { defineComponent, h } from 'vue'; import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import PatientStudyVolumeBrowser from '@/src/components/PatientStudyVolumeBrowser.vue'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { plannedUpdate } from '@/packages/dicom/core/volume/__tests__/volumeFixture'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import type { DecodedDicomImage } from '@/packages/dicom/core/runtime/decoder'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import { allocateVolume, + createDicomRuntime, + fromBlob, + type DecodedPixels, type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; +} from '@/packages/dicom/core'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { LoadedVtkImage } from '@/src/core/progressiveImage'; import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useMessageStore } from '@/src/store/messages'; import { seatVolume } from '@/src/store/__tests__/datasetFixtures'; -import { datasetFromTags } from '@/tests/dicomDataset'; import { defer } from '@/src/utils'; const messageTitles = () => @@ -73,10 +72,10 @@ function mountBrowser() { return mount(Host, { global: { stubs } }); } -const decoded = () => ({ +const decoded = (): DecodedPixels => ({ size: [1, 1, 1], data: new Uint16Array([1]), - imageType: { components: 1 }, + components: 1, }); const sliceInstance = (z = 0) => @@ -103,20 +102,20 @@ const sliceInstance = (z = 0) => ); // The thumbnail is read from the volume, so it waits on the volume's decode. -async function importPendingThumbnail() { - const decode = defer(); +function importPendingThumbnail() { + const decode = defer(); const started = defer(); - const runtime = createDicomRuntime({ - decoder: () => { + const runtime = createDicomRuntime( + decodingWith(() => { started.resolve(); return decode.promise; - }, - }); + }) + ); const image = new DicomVolumeImage({ runtime, encodeThumbnail: () => 'data:image/png;base64,current', }); - const result = await useDICOMStore().importInstances([sliceInstance()], { + const result = useDICOMStore().importInstances([sliceInstance()], { createImage: () => image, }); onTestFinished(() => { @@ -153,7 +152,7 @@ describe('volume browser thumbnail lifetime', () => { }); it('shows a decoded thumbnail', async () => { - const { started, decode } = await importPendingThumbnail(); + const { started, decode } = importPendingThumbnail(); const wrapper = mountBrowser(); await started.promise; expect(wrapper.find('[role="progressbar"]').exists()).toBe(true); @@ -177,7 +176,7 @@ describe('volume browser thumbnail lifetime', () => { it('reports a failed decode once, as a load error, and shows the modality', async () => { vi.spyOn(console, 'error').mockImplementation(() => {}); - const { started, decode } = await importPendingThumbnail(); + const { started, decode } = importPendingThumbnail(); const wrapper = mountBrowser(); await started.promise; @@ -192,7 +191,7 @@ describe('volume browser thumbnail lifetime', () => { it.each([false, true])( 'keeps Delete quiet during decoding when another volume remains: %s', async (keepBrowser) => { - const { id, started, decode } = await importPendingThumbnail(); + const { id, started, decode } = importPendingThumbnail(); if (keepBrowser) { seatVolume('remaining'); cacheImage('remaining'); @@ -225,20 +224,13 @@ describe('volume browser thumbnail lifetime', () => { ); it('settles a thumbnail after a growth is undone while it decodes', async () => { - const { image, started, decode } = await importPendingThumbnail(); + const { image, started, decode } = importPendingThumbnail(); const wrapper = mountBrowser(); await started.promise; const original = image.getVolume()!; - const volumeOf = (members: Volume['members'], previous?: Volume) => { - const allocation = allocateVolume( - plannedUpdate([...members]), - {}, - previous - ); - if (allocation.kind !== 'volume') throw new Error('Expected a volume'); - return allocation.volume; - }; + const volumeOf = (members: Volume['members'], previous?: Volume) => + allocateVolume(plannedUpdate([...members]), {}, previous); const grown = volumeOf([...original.members, sliceInstance(1)]); image.setVolume(grown); image.setVolume(volumeOf(original.members, grown)); @@ -250,7 +242,7 @@ describe('volume browser thumbnail lifetime', () => { }); it('reports no thumbnail failure after the browser unmounts', async () => { - const { started, decode } = await importPendingThumbnail(); + const { started, decode } = importPendingThumbnail(); const wrapper = mountBrowser(); await started.promise; diff --git a/src/components/__tests__/PlayControls.spec.ts b/src/components/__tests__/PlayControls.spec.ts index 51afe8c76..407bb6c14 100644 --- a/src/components/__tests__/PlayControls.spec.ts +++ b/src/components/__tests__/PlayControls.spec.ts @@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { ComponentPublicInstance, nextTick } from 'vue'; import PlayControls from '@/src/components/PlayControls.vue'; import { seatCineImage } from '@/src/core/cine/__tests__/cineFixtures'; +import { Tags } from '@/packages/dicom/core'; type PlayControlsProps = { viewId: string; imageId: string | null }; type PlayControlsWrapper = VueWrapper< @@ -15,8 +16,8 @@ describe('PlayControls', () => { setActivePinia(createPinia()); vi.useFakeTimers(); // Frame time drives the default FPS: 50ms is 20fps, 25ms is 40fps. - seatCineImage('image-1', { frameTimeMs: 50 }); - seatCineImage('image-2', { frameTimeMs: 25 }); + seatCineImage('image-1', { [Tags.FrameTime]: '50' }); + seatCineImage('image-2', { [Tags.FrameTime]: '25' }); }); afterEach(() => { diff --git a/src/components/vtk/VtkBaseVolumeRepresentation.vue b/src/components/vtk/VtkBaseVolumeRepresentation.vue index 2b9ff899b..a2f39ca3b 100644 --- a/src/components/vtk/VtkBaseVolumeRepresentation.vue +++ b/src/components/vtk/VtkBaseVolumeRepresentation.vue @@ -38,7 +38,7 @@ import { useCroppingEffect } from '@/src/composables/useCroppingEffect'; import { useCropStore } from '@/src/store/tools/crop'; import { useEventListener } from '@vueuse/core'; import type DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; -import type { Extent } from '@/packages/dicom/core/volume/loadVolume'; +import type { Extent } from '@/packages/dicom/core'; interface Props { viewId: string; diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index e5e540abe..581dad92e 100644 --- a/src/core/cine/DicomCineImage.ts +++ b/src/core/cine/DicomCineImage.ts @@ -1,6 +1,6 @@ // Backing image for multi-frame ultrasound DICOM clips. Owns a single 2D -// vtkImageData with 3-component RGB scalars; the per-frame compressed bytes -// stay in this object and decoded frames live in an LRU cache. +// vtkImageData with 3-component RGB scalars; the per-frame stored bytes are +// read once loading starts and decoded frames live in an LRU cache. import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; @@ -12,11 +12,20 @@ import { ProgressiveImageEvents, } from '@/src/core/progressiveImage'; import { - CineHeader, - CineParseResult, + fallbackSpacing, + physicalSpacing, + unitToMm, + type Instance, + type SpatialMetadata, +} from '@/packages/dicom/core'; +import { abortError } from '@/src/utils'; +import { + type CineHeader, isNativeTransferSyntax, isSupportedCineTransferSyntax, -} from './parseCineDicom'; + readCineFrames, + readCineHeader, +} from './cineInstance'; import { DecodedFrame, FrameCache, @@ -24,16 +33,10 @@ import { decodeJpegFrame, decodeNativeFrame, } from './frameCache'; -import { unitToMm } from '@/packages/dicom/core/streaming/dicom/ultrasoundRegion'; -import { - physicalSpacing, - fallbackSpacing, - type SpatialMetadata, -} from '@/packages/dicom/core/metadata/spatialMetadata'; function spatialRegionSpacing(r: CineHeader['regions'][number]) { - const sx = r.physicalUnitsX != null ? unitToMm(r.physicalUnitsX) : null; - const sy = r.physicalUnitsY != null ? unitToMm(r.physicalUnitsY) : null; + const sx = unitToMm(r.physicalUnitsXDirection); + const sy = unitToMm(r.physicalUnitsYDirection); if (sx == null || sy == null) return null; const { physicalDeltaX: dx, physicalDeltaY: dy } = r; if (!dx || !dy || !Number.isFinite(dx) || !Number.isFinite(dy)) return null; @@ -90,26 +93,52 @@ function pickSpacing(header: CineHeader): SpatialMetadata { }; } +/** Encodes an RGB frame as a PNG data URI, or null without a 2D canvas. */ +function encodeFrameToUri({ width, height, rgb }: DecodedFrame) { + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext('2d'); + if (!context) return null; + const image = context.createImageData(width, height); + const rgba = image.data; + for (let pixel = 0; pixel < width * height; pixel++) { + rgba[pixel * 4] = rgb[pixel * 3]; + rgba[pixel * 4 + 1] = rgb[pixel * 3 + 1]; + rgba[pixel * 4 + 2] = rgb[pixel * 3 + 2]; + rgba[pixel * 4 + 3] = 255; + } + context.putImageData(image, 0, 0); + return canvas.toDataURL('image/png'); +} + export default class DicomCineImage extends BaseProgressiveImage { public readonly header: CineHeader; - private readonly frames: Uint8Array[]; - private readonly encapsulated: boolean; + private readonly instance: Instance; + private frames: Promise | null = null; + private readonly reads = new AbortController(); private readonly cache: FrameCache; private readonly inFlightFrames: Map>; private readonly events: Emitter; private readonly scalarBuffer: Uint8Array; + private readonly reported = new WeakSet(); + + private readonly encodeThumbnail: (frame: DecodedFrame) => string | null; private thumbnailPromise: Promise | null = null; private disposed = false; - constructor(init: CineParseResult) { + constructor( + instance: Instance, + header = readCineHeader(instance), + encodeThumbnail: (frame: DecodedFrame) => string | null = encodeFrameToUri + ) { super(); - const { header, frames, encapsulated } = init; + this.encodeThumbnail = encodeThumbnail; this.header = header; - this.frames = frames; - this.encapsulated = encapsulated; + this.instance = instance; this.cache = new FrameCache(); this.inFlightFrames = new Map(); this.events = mitt(); @@ -202,11 +231,12 @@ export default class DicomCineImage extends BaseProgressiveImage { dispose(): void { if (this.disposed) return; this.disposed = true; + this.reads.abort(abortError('Image disposed')); super.dispose(); this.events.all.clear(); this.cache.clear(); this.inFlightFrames.clear(); - this.frames.length = 0; + this.frames = null; this.vtkImageData.value.delete(); } @@ -217,34 +247,20 @@ export default class DicomCineImage extends BaseProgressiveImage { getThumbnail(): Promise { if (this.disposed) return Promise.resolve(null); if (this.thumbnailPromise) return this.thumbnailPromise; - this.thumbnailPromise = (async () => { + const thumbnail = (async () => { try { - const frame = await this.getFrame(0); - const { cols, rows } = this.header; - const canvas = document.createElement('canvas'); - canvas.width = cols; - canvas.height = rows; - const ctx = canvas.getContext('2d'); - if (!ctx) return null; - const imageData = ctx.createImageData(cols, rows); - const dst = imageData.data; - const { rgb } = frame; - const pixels = cols * rows; - for (let i = 0; i < pixels; i++) { - const s = i * 3; - const d = i * 4; - dst[d] = rgb[s]; - dst[d + 1] = rgb[s + 1]; - dst[d + 2] = rgb[s + 2]; - dst[d + 3] = 255; - } - ctx.putImageData(imageData, 0, 0); - return canvas.toDataURL('image/png'); + return this.encodeThumbnail(await this.getFrame(0)); } catch { return null; } })(); - return this.thumbnailPromise; + this.thumbnailPromise = thumbnail; + // A failed read is not cached, so a later call tries again. + thumbnail.then((uri) => { + if (uri === null && this.thumbnailPromise === thumbnail) + this.thumbnailPromise = null; + }); + return thumbnail; } // Concurrent requests for the same uncached frame share a single decode. @@ -304,16 +320,32 @@ export default class DicomCineImage extends BaseProgressiveImage { // first-frame decode. private reportError(err: unknown): void { const error = err instanceof Error ? err : new Error(String(err)); + // Every frame waiting on one failed read rejects with the same error. + if (this.reported.has(error)) return; + this.reported.add(error); this.events.emit('error', error); if (this.loading.value) { this.events.emit('loading', false); } } + // A failed read is forgotten, so the next load reads again. + private readFrames() { + this.frames ??= readCineFrames( + this.instance, + this.header, + this.reads.signal + ).catch((err) => { + this.frames = null; + throw err; + }); + return this.frames; + } + private async decode(frameIndex: number) { - const bytes = this.frames[frameIndex]; + const bytes = (await this.readFrames())[frameIndex]; if (!bytes) throw new Error(`Frame ${frameIndex} is missing`); - if (this.encapsulated) { + if (!isNativeTransferSyntax(this.header.transferSyntaxUID)) { return decodeJpegFrame(bytes, this.header.cols, this.header.rows); } return decodeNativeFrame(bytes, { @@ -324,17 +356,4 @@ export default class DicomCineImage extends BaseProgressiveImage { planarConfiguration: this.header.planarConfiguration, }); } - - static isSupported(header: CineHeader): boolean { - if (!isSupportedCineTransferSyntax(header.transferSyntaxUID)) return false; - if (isNativeTransferSyntax(header.transferSyntaxUID)) { - // Native pixel data: only support 8-bit RGB or grayscale for v1. - if (header.bitsAllocated !== 8) return false; - const photometric = header.photometricInterpretation.trim(); - if (header.samplesPerPixel === 1) return photometric === 'MONOCHROME2'; - if (header.samplesPerPixel === 3) return photometric === 'RGB'; - return false; - } - return true; - } } diff --git a/src/core/cine/__tests__/DicomCineImage.spec.ts b/src/core/cine/__tests__/DicomCineImage.spec.ts index 1e89175e6..ac38e8a78 100644 --- a/src/core/cine/__tests__/DicomCineImage.spec.ts +++ b/src/core/cine/__tests__/DicomCineImage.spec.ts @@ -1,135 +1,216 @@ import { describe, expect, it } from 'vitest'; - +import { + fromBlob, + readInstance, + Tags, + type ByteSource, + type DicomDataset, +} from '@/packages/dicom/core'; +import { buildSyntheticCineDicom } from '@/tests/specs/syntheticDicom'; +import { datasetFromTags } from '@/tests/dicomDataset'; import DicomCineImage from '../DicomCineImage'; -import { cineHeader, cineParseResult as parseResult } from './cineFixtures'; - -const TS_JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; -const TS_JPEG_EXTENDED = '1.2.840.10008.1.2.4.51'; -const TS_UNSUPPORTED = '1.2.840.10008.1.2.5'; - -describe('DicomCineImage.isSupported', () => { - it('accepts only MONOCHROME2 for native one-sample 8-bit pixels', () => { - expect(DicomCineImage.isSupported(cineHeader())).toBe(true); - - ['MONOCHROME1', 'PALETTE COLOR', 'RGB', 'YBR_FULL', 'YBR_FULL_422'].forEach( - (photometricInterpretation) => { - expect( - DicomCineImage.isSupported(cineHeader({ photometricInterpretation })) - ).toBe(false); - } - ); +import { cineInstance, TS_JPEG_BASELINE } from './cineFixtures'; + +type Region = Record<'deltaX' | 'deltaY' | 'unitsX' | 'unitsY', string>; + +const regionSequence = (regions: Region[]): DicomDataset['elements'] => [ + { + tag: '00186011', + group: 0x0018, + element: 0x6011, + vr: 'SQ', + values: { + kind: 'sequence', + items: regions.map((region) => + datasetFromTags([ + [Tags.PhysicalDeltaX, region.deltaX], + [Tags.PhysicalDeltaY, region.deltaY], + [Tags.PhysicalUnitsXDirection, region.unitsX], + [Tags.PhysicalUnitsYDirection, region.unitsY], + ]) + ), + }, + }, +]; + +const spacingOf = (image: DicomCineImage) => + Array.from(image.getVtkImageData().getSpacing()); + +/** Starts loading and settles with the first error or completion. */ +const load = (image: DicomCineImage) => { + const errors: Error[] = []; + const settled = new Promise((resolve) => { + image.addEventListener('error', (error) => { + errors.push(error); + resolve(); + }); + image.addEventListener('status', (status) => { + if (status === 'complete') resolve(); + }); }); + image.startLoad(); + return settled.then(() => errors); +}; + +const scalarsOf = (image: DicomCineImage) => + Array.from(image.getVtkImageData().getPointData().getScalars().getData()); - it('accepts only RGB for native three-sample 8-bit pixels', () => { - expect( - DicomCineImage.isSupported( - cineHeader({ - samplesPerPixel: 3, - photometricInterpretation: 'RGB', - }) +describe('DicomCineImage spacing', () => { + it('uses the first spatial 2D ultrasound region instead of the first region overall', () => { + const image = new DicomCineImage( + cineInstance( + { [Tags.PixelSpacing]: '1.8\\0.45' }, + { + elements: regionSequence([ + { deltaX: '10', deltaY: '10', unitsX: '1', unitsY: '3' }, + { deltaX: '-0.05', deltaY: '0.125', unitsX: '3', unitsY: '3' }, + ]), + } ) - ).toBe(true); - - [ - 'MONOCHROME2', - 'MONOCHROME1', - 'PALETTE COLOR', - 'YBR_FULL', - 'YBR_FULL_422', - ].forEach((photometricInterpretation) => { - expect( - DicomCineImage.isSupported( - cineHeader({ - samplesPerPixel: 3, - photometricInterpretation, - }) - ) - ).toBe(false); - }); + ); + + expect(spacingOf(image)).toEqual([0.5, 1.25, 1]); + image.dispose(); }); - it('rejects native pixels unless BitsAllocated is 8', () => { - expect(DicomCineImage.isSupported(cineHeader({ bitsAllocated: 16 }))).toBe( - false + it('falls back to DICOM PixelSpacing in VTK axis order when no spatial ultrasound region is available', () => { + const image = new DicomCineImage( + cineInstance({ [Tags.PixelSpacing]: '1.8\\0.45' }) ); + + expect(spacingOf(image)).toEqual([0.45, 1.8, 1]); + image.dispose(); }); +}); - it('keeps encapsulated support scoped to transfer syntax acceptance', () => { - expect( - DicomCineImage.isSupported( - cineHeader({ - transferSyntaxUID: TS_JPEG_BASELINE, - bitsAllocated: 16, - samplesPerPixel: 3, - photometricInterpretation: 'YBR_FULL_422', - }) - ) - ).toBe(true); - - expect( - DicomCineImage.isSupported( - cineHeader({ - transferSyntaxUID: TS_UNSUPPORTED, - photometricInterpretation: 'RGB', - }) - ) - ).toBe(false); - - expect( - DicomCineImage.isSupported( - cineHeader({ - transferSyntaxUID: TS_JPEG_EXTENDED, - photometricInterpretation: 'YBR_FULL_422', - }) +describe('DicomCineImage loading', () => { + it('shows the first frame of a Part 10 clip once loading starts', async () => { + const bytes = buildSyntheticCineDicom({ + studyUid: '1.2.3', + seriesUid: '1.2.3.4', + sopUid: '1.2.3.4.5', + numberOfFrames: 3, + rows: 2, + cols: 3, + }); + const image = new DicomCineImage( + await readInstance( + fromBlob(new Blob([bytes as BlobPart])), + new AbortController().signal ) - ).toBe(false); + ); + + expect(await load(image)).toEqual([]); + expect(image.getVtkImageData().getDimensions()).toEqual([3, 2, 1]); + // The synthetic clip's samples count up from zero; gray replicates to RGB. + expect(scalarsOf(image)).toEqual( + [0, 1, 2, 3, 4, 5].flatMap((value) => [value, value, value]) + ); + expect(image.getStatus()).toBe('complete'); + image.dispose(); }); -}); -describe('DicomCineImage spacing', () => { - it('uses the first spatial 2D ultrasound region instead of the first region overall', () => { + it('reports pixel data it cannot cut into frames as one load error', async () => { const image = new DicomCineImage( - parseResult( - cineHeader({ - pixelSpacing: [1.8, 0.45], - regions: [ - { - physicalDeltaX: 10, - physicalDeltaY: 10, - physicalUnitsX: 1, - physicalUnitsY: 3, - }, - { - physicalDeltaX: -0.05, - physicalDeltaY: 0.125, - physicalUnitsX: 3, - physicalUnitsY: 3, - }, - ], - }) + cineInstance( + {}, + { + transferSyntaxUid: TS_JPEG_BASELINE, + pixels: Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]), + } ) ); - expect(Array.from(image.getVtkImageData().getSpacing())).toEqual([ - 0.5, 1.25, 1, - ]); + const errors = await load(image); + expect(errors.map(({ message }) => message)).toEqual([ + expect.stringMatching(/Malformed encapsulated Pixel Data/), + ]); + expect(image.isLoading()).toBe(false); + expect(image.getStatus()).toBe('incomplete'); image.dispose(); }); - it('falls back to DICOM PixelSpacing in VTK axis order when no spatial ultrasound region is available', () => { + it('reports native pixel data shorter than its frames', async () => { const image = new DicomCineImage( - parseResult( - cineHeader({ - pixelSpacing: [1.8, 0.45], - }) - ) + cineInstance({}, { pixels: new Uint8Array(4) }) ); - expect(Array.from(image.getVtkImageData().getSpacing())).toEqual([ - 0.45, 1.8, 1, + const errors = await load(image); + + expect(errors.map(({ message }) => message)).toEqual([ + expect.stringMatching(/Pixel Data holds 4 bytes; its frames need 8/), + ]); + image.dispose(); + }); + + it('reads the pixels again when a load is retried after a failed read', async () => { + const pixels = fromBlob( + new Blob([Uint8Array.from([9, 9, 9, 9, 8, 8, 8, 8])]) + ); + const reads: AbortSignal[] = []; + const source: ByteSource = { + read: (signal, range) => { + reads.push(signal); + if (reads.length === 1) + return new ReadableStream({ + start: (controller) => controller.error(new Error('offline')), + }); + return pixels.read(signal, range); + }, + }; + const image = new DicomCineImage({ ...cineInstance(), source }); + + expect((await load(image)).map(({ message }) => message)).toEqual([ + 'offline', ]); + expect(await load(image)).toEqual([]); + expect(scalarsOf(image)).toEqual(Array(12).fill(9)); + image.dispose(); + }); + + it('makes a thumbnail once a read that failed succeeds on retry', async () => { + const pixels = fromBlob( + new Blob([Uint8Array.from([9, 9, 9, 9, 8, 8, 8, 8])]) + ); + let reads = 0; + const source: ByteSource = { + read: (signal, range) => { + reads += 1; + if (reads === 1) + return new ReadableStream({ + start: (controller) => controller.error(new Error('offline')), + }); + return pixels.read(signal, range); + }, + }; + const image = new DicomCineImage( + { ...cineInstance(), source }, + undefined, + ({ width, height, rgb }) => `${width}x${height}:${rgb.join(',')}` + ); + image.addEventListener('error', () => {}); + + expect(await image.getThumbnail()).toBeNull(); + expect(await load(image)).toEqual([]); + expect(await image.getThumbnail()).toBe(`2x2:${Array(12).fill(9)}`); + image.dispose(); + }); + it('aborts its pixel read when disposed', () => { + const reads: AbortSignal[] = []; + const source: ByteSource = { + read: (signal) => { + reads.push(signal); + return new ReadableStream({ pull: () => new Promise(() => {}) }); + }, + }; + const image = new DicomCineImage({ ...cineInstance(), source }); + + image.startLoad(); image.dispose(); + + expect(reads).toHaveLength(1); + expect(reads[0].aborted).toBe(true); }); }); diff --git a/src/core/cine/__tests__/cineFixtures.ts b/src/core/cine/__tests__/cineFixtures.ts index b278bf831..a2f0d613e 100644 --- a/src/core/cine/__tests__/cineFixtures.ts +++ b/src/core/cine/__tests__/cineFixtures.ts @@ -1,12 +1,74 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { + fromBlob, + SOP_CLASS_ULTRASOUND_MULTIFRAME, + Tags, + type DicomDataset, + type Instance, +} from '@/packages/dicom/core'; import { useImageCacheStore } from '@/src/store/image-cache'; import { seatVolume } from '@/src/store/__tests__/datasetFixtures'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; -import type { - CineHeader, - CineParseResult, -} from '@/src/core/cine/parseCineDicom'; -const TS_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; +export const TS_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; +export const TS_JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; + +/** A two-frame 2x2 native grayscale clip, keyed 'gggg|eeee'. */ +const CINE_TAGS: Record = { + [Tags.SOPClassUID]: SOP_CLASS_ULTRASOUND_MULTIFRAME, + [Tags.SOPInstanceUID]: 'cine-sop', + [Tags.NumberOfFrames]: '2', + [Tags.Rows]: '2', + [Tags.Columns]: '2', + [Tags.SamplesPerPixel]: '1', + [Tags.BitsAllocated]: '8', + [Tags.BitsStored]: '8', + [Tags.PixelRepresentation]: '0', + [Tags.PhotometricInterpretation]: 'MONOCHROME2', + [Tags.Modality]: 'US', + [Tags.PatientID]: 'patient-1', + [Tags.PatientName]: 'Test Patient', + [Tags.StudyID]: 'study-1', + [Tags.StudyInstanceUID]: 'study-uid', + [Tags.SeriesInstanceUID]: 'series-uid', + [Tags.SeriesNumber]: '1', + [Tags.SeriesDescription]: 'Cine', +}; + +type CineInstanceOptions = { + transferSyntaxUid?: string; + /** The Pixel Data value; the source holds nothing else. */ + pixels?: Uint8Array; + /** Elements added after the tags, such as sequences. */ + elements?: DicomDataset['elements']; +}; + +/** + * A clip header as `readInstance` returns it from a Part 10 file whose Pixel + * Data value is the whole source. + */ +export const cineInstance = ( + tags: Record = {}, + { + transferSyntaxUid = TS_EXPLICIT_VR_LE, + pixels = Uint8Array.from([10, 20, 30, 40, 50, 60, 70, 80]), + elements = [], + }: CineInstanceOptions = {} +): Instance => { + const dataset = datasetFromTags(Object.entries({ ...CINE_TAGS, ...tags })); + return Object.freeze({ + source: fromBlob(new Blob([pixels as BlobPart])), + dataset: { ...dataset, elements: [...dataset.elements, ...elements] }, + layout: { preamble: true, fileMeta: true } as const, + ultrasoundRegions: null, + transferSyntaxUid, + pixelData: { + offset: 0, + valueOffset: 0, + length: transferSyntaxUid === TS_JPEG_BASELINE ? null : pixels.length, + }, + }); +}; /** * Seats a volume the real `isCineImage` reports as cine. Requires an active @@ -15,49 +77,6 @@ const TS_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; export const markCine = (imageID: string) => seatVolume(imageID, { kind: 'cine' }); -export const cineHeader = ( - overrides: Partial = {} -): CineHeader => ({ - transferSyntaxUID: TS_EXPLICIT_VR_LE, - rows: 2, - cols: 2, - numberOfFrames: 2, - samplesPerPixel: 1, - bitsAllocated: 8, - planarConfiguration: 0, - photometricInterpretation: 'MONOCHROME2', - pixelSpacing: null, - frameTimeMs: null, - patient: { - PatientID: 'patient-1', - PatientName: 'Test Patient', - PatientBirthDate: '', - PatientSex: '', - }, - study: { - StudyID: 'study-1', - StudyInstanceUID: 'study-uid', - StudyDate: '', - StudyTime: '', - AccessionNumber: '', - StudyDescription: '', - }, - series: { - SeriesInstanceUID: 'series-uid', - SeriesNumber: '1', - SeriesDescription: 'Cine', - Modality: 'US', - }, - regions: [], - ...overrides, -}); - -export const cineParseResult = (header: CineHeader): CineParseResult => ({ - header, - frames: [new Uint8Array(4), new Uint8Array(4)], - encapsulated: false, -}); - /** * Seats a real two-frame clip under `imageID`, both in the DICOM store (so * `isCineImage` says yes) and in the image cache (so `getCineImage` hands the @@ -65,10 +84,10 @@ export const cineParseResult = (header: CineHeader): CineParseResult => ({ */ export const seatCineImage = ( imageID: string, - header: Partial = {} + tags: Record = {} ) => { markCine(imageID); - const image = new DicomCineImage(cineParseResult(cineHeader(header))); + const image = new DicomCineImage(cineInstance(tags)); useImageCacheStore().addProgressiveImage(image, { id: imageID }); return image; }; diff --git a/src/core/cine/__tests__/cineInstance.spec.ts b/src/core/cine/__tests__/cineInstance.spec.ts new file mode 100644 index 000000000..0acb12b0e --- /dev/null +++ b/src/core/cine/__tests__/cineInstance.spec.ts @@ -0,0 +1,253 @@ +import { describe, expect, it } from 'vitest'; +import { + fromBlob, + readInstance, + SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, + Tags, +} from '@/packages/dicom/core'; +import { + buildSyntheticCineDicom, + rawElement, + sequenceItem, + type SyntheticCineOptions, +} from '@/tests/specs/syntheticDicom'; +import { + isCineInstance, + readCineFrames, + readCineHeader, +} from '../cineInstance'; +import { + cineInstance, + TS_EXPLICIT_VR_LE, + TS_JPEG_BASELINE, +} from './cineFixtures'; + +const TS_JPEG_EXTENDED = '1.2.840.10008.1.2.4.51'; +const TS_RLE = '1.2.840.10008.1.2.5'; + +const PHOTOMETRICS = [ + 'MONOCHROME1', + 'MONOCHROME2', + 'PALETTE COLOR', + 'RGB', + 'YBR_FULL', + 'YBR_FULL_422', +]; + +const accepted = (tags: Record, transferSyntaxUid?: string) => + isCineInstance(cineInstance(tags, { transferSyntaxUid })); + +describe('isCineInstance', () => { + it('accepts current and retired ultrasound multi-frame SOP classes', () => { + expect(accepted({})).toBe(true); + expect( + accepted({ [Tags.SOPClassUID]: SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED }) + ).toBe(true); + }); + + it('rejects other SOP classes and single frames', () => { + expect(accepted({ [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2' })).toBe( + false + ); + expect(accepted({ [Tags.NumberOfFrames]: '1' })).toBe(false); + }); + + it('accepts only MONOCHROME2 for native one-sample pixels', () => { + expect( + PHOTOMETRICS.filter((photometric) => + accepted({ [Tags.PhotometricInterpretation]: photometric }) + ) + ).toEqual(['MONOCHROME2']); + }); + + it('accepts only RGB for native three-sample pixels', () => { + expect( + PHOTOMETRICS.filter((photometric) => + accepted({ + [Tags.SamplesPerPixel]: '3', + [Tags.PhotometricInterpretation]: photometric, + }) + ) + ).toEqual(['RGB']); + }); + + it('rejects native pixels unless Bits Allocated is 8, reading an empty value as 8', () => { + expect(accepted({ [Tags.BitsAllocated]: '16' })).toBe(false); + expect(accepted({ [Tags.BitsAllocated]: '' })).toBe(true); + }); + + it('accepts JPEG Baseline whatever its pixel format and no other compression', () => { + const anyFormat = { + [Tags.BitsAllocated]: '16', + [Tags.SamplesPerPixel]: '3', + [Tags.PhotometricInterpretation]: 'YBR_FULL_422', + }; + expect(accepted(anyFormat, TS_JPEG_BASELINE)).toBe(true); + expect(accepted(anyFormat, TS_JPEG_EXTENDED)).toBe(false); + expect(accepted({}, TS_RLE)).toBe(false); + }); + + it('rejects a header without a Part 10 preamble or without Pixel Data', () => { + const clip = cineInstance(); + expect( + isCineInstance({ ...clip, layout: { preamble: false, fileMeta: true } }) + ).toBe(false); + expect(isCineInstance({ ...clip, pixelData: null })).toBe(false); + }); +}); + +const signal = () => new AbortController().signal; + +const readClip = (options: Partial) => { + const bytes = buildSyntheticCineDicom({ + studyUid: '1.2.3', + seriesUid: '1.2.3.4', + sopUid: '1.2.3.4.5', + ...options, + }); + return readInstance(fromBlob(new Blob([bytes as BlobPart])), signal()); +}; + +const binary = (write: (view: DataView) => void, length: number) => { + const bytes = new Uint8Array(length); + write(new DataView(bytes.buffer)); + return bytes; +}; +const unsigned16 = (value: number) => + binary((view) => view.setUint16(0, value, true), 2); +const double = (value: number) => + binary((view) => view.setFloat64(0, value, true), 8); + +/** A Sequence of Ultrasound Regions item in centimeters, or in seconds on x. */ +const regionItem = (deltaX: number, deltaY: number, unitsX = 3) => + sequenceItem( + Uint8Array.from([ + ...rawElement(0x0018, 0x6024, 'US', unsigned16(unitsX)), + ...rawElement(0x0018, 0x6026, 'US', unsigned16(3)), + ...rawElement(0x0018, 0x602c, 'FD', double(deltaX)), + ...rawElement(0x0018, 0x602e, 'FD', double(deltaY)), + ]) + ); + +describe('readCineHeader', () => { + it('reads a Part 10 clip header without reading its pixels', async () => { + const instance = await readClip({ + numberOfFrames: 5, + rows: 4, + cols: 3, + pixelSpacing: [1.8, 0.45], + patientName: 'DOE^JANE', + patientId: 'P-77', + seriesNumber: 12, + studyDate: '20250304', + extraElements: [ + rawElement( + 0x0018, + 0x6011, + 'SQ', + Uint8Array.from([ + ...regionItem(0.5, 0.25, 4), + ...regionItem(0.0125, 0.025), + ]) + ), + ], + }); + + expect(isCineInstance(instance)).toBe(true); + expect(readCineHeader(instance)).toEqual({ + transferSyntaxUID: TS_EXPLICIT_VR_LE, + rows: 4, + cols: 3, + numberOfFrames: 5, + samplesPerPixel: 1, + bitsAllocated: 8, + planarConfiguration: 0, + photometricInterpretation: 'MONOCHROME2', + pixelSpacing: [1.8, 0.45], + frameTimeMs: null, + patient: { + PatientID: 'P-77', + PatientName: 'DOE^JANE', + PatientBirthDate: '19700101', + PatientSex: 'O', + }, + study: { + StudyID: '1', + StudyInstanceUID: '1.2.3', + StudyDate: '20250304', + StudyTime: '', + AccessionNumber: '', + StudyDescription: '', + }, + series: { + SeriesInstanceUID: '1.2.3.4', + SeriesNumber: '12', + SeriesDescription: 'Synthetic cine', + Modality: 'US', + }, + regions: [ + { + physicalDeltaX: 0.5, + physicalDeltaY: 0.25, + physicalUnitsXDirection: 4, + physicalUnitsYDirection: 3, + }, + { + physicalDeltaX: 0.0125, + physicalDeltaY: 0.025, + physicalUnitsXDirection: 3, + physicalUnitsYDirection: 3, + }, + ], + }); + }); + + it('reads planar configuration and frame time', () => { + expect( + readCineHeader( + cineInstance({ + [Tags.SamplesPerPixel]: '3', + [Tags.PhotometricInterpretation]: 'RGB', + '0028|0006': '1', + [Tags.FrameTime]: '33.3', + }) + ) + ).toMatchObject({ + samplesPerPixel: 3, + planarConfiguration: 1, + frameTimeMs: 33.3, + }); + }); +}); + +describe('a Part 10 JPEG Baseline clip', () => { + const jpeg = (...body: number[]) => + Uint8Array.from([0xff, 0xd8, ...body, 0xff, 0xd9]); + const first = jpeg(1, 2, 3); + const second = jpeg(4, 5, 6, 7, 8); + + it.each([true, false])( + 'reads each frame from its value with a populated offset table: %s', + async (offsetTable) => { + const instance = await readClip({ + encapsulated: { + frames: [[first], [second.subarray(0, 4), second.subarray(4)]], + offsetTable, + }, + }); + + expect(isCineInstance(instance)).toBe(true); + expect(instance.pixelData?.valueOffset).toBeGreaterThan(0); + const header = readCineHeader(instance); + expect(header).toMatchObject({ + transferSyntaxUID: TS_JPEG_BASELINE, + numberOfFrames: 2, + }); + const frames = await readCineFrames(instance, header, signal()); + expect(frames.map((frame) => [...frame])).toEqual([ + [...first], + [...second], + ]); + } + ); +}); diff --git a/src/core/cine/__tests__/parseCineDicom.spec.ts b/src/core/cine/__tests__/parseCineDicom.spec.ts deleted file mode 100644 index b072f70e7..000000000 --- a/src/core/cine/__tests__/parseCineDicom.spec.ts +++ /dev/null @@ -1,330 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { parseCineDicom } from '../parseCineDicom'; - -// ================================================================= -// Synthetic DICOM builder (Explicit VR LE) -// ================================================================= -// -// Lets the parser smoke tests run anywhere without committing real ultrasound -// fixtures. Produces the minimum byte layout the parser cares about: 128-byte -// preamble, DICM magic, a TransferSyntaxUID file-meta element, and a hand- -// rolled dataset. - -const TS_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; -const TS_JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; - -function ascii(s: string): Uint8Array { - const out = new Uint8Array(s.length); - for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i); - return out; -} - -function evenPad(bytes: Uint8Array): Uint8Array { - if (bytes.byteLength % 2 === 0) return bytes; - const out = new Uint8Array(bytes.byteLength + 1); - out.set(bytes); - out[bytes.byteLength] = 0x20; - return out; -} - -function concat(parts: Uint8Array[]): Uint8Array { - const total = parts.reduce((s, p) => s + p.byteLength, 0); - const out = new Uint8Array(total); - let off = 0; - for (const p of parts) { - out.set(p, off); - off += p.byteLength; - } - return out; -} - -const VR4 = new Set([ - 'OB', - 'OW', - 'OF', - 'OD', - 'OL', - 'SQ', - 'UC', - 'UR', - 'UT', - 'UN', -]); - -function elementShort( - group: number, - element: number, - vr: string, - value: Uint8Array -): Uint8Array { - const padded = evenPad(value); - const header = new Uint8Array(8); - const dv = new DataView(header.buffer); - dv.setUint16(0, group, true); - dv.setUint16(2, element, true); - header[4] = vr.charCodeAt(0); - header[5] = vr.charCodeAt(1); - dv.setUint16(6, padded.byteLength, true); - return concat([header, padded]); -} - -function elementLong( - group: number, - element: number, - vr: string, - value: Uint8Array -): Uint8Array { - if (!VR4.has(vr)) throw new Error(`VR ${vr} is not 4-byte length`); - const header = new Uint8Array(12); - const dv = new DataView(header.buffer); - dv.setUint16(0, group, true); - dv.setUint16(2, element, true); - header[4] = vr.charCodeAt(0); - header[5] = vr.charCodeAt(1); - // header[6..8] reserved zero - dv.setUint32(8, value.byteLength, true); - return concat([header, value]); -} - -function u16Bytes(value: number): Uint8Array { - const out = new Uint8Array(2); - new DataView(out.buffer).setUint16(0, value, true); - return out; -} - -function fileMeta(transferSyntaxUID: string): Uint8Array { - return elementShort(0x0002, 0x0010, 'UI', ascii(transferSyntaxUID)); -} - -const COMMON_TAGS = ( - numberOfFrames: number, - rows: number, - cols: number, - options: { - samplesPerPixel?: number; - photometricInterpretation?: string; - planarConfiguration?: number; - pixelSpacing?: readonly [number, number]; - } = {} -) => { - const samplesPerPixel = options.samplesPerPixel ?? 1; - const photometricInterpretation = - options.photometricInterpretation ?? 'MONOCHROME2'; - - return concat([ - elementShort(0x0008, 0x0016, 'UI', ascii('1.2.840.10008.5.1.4.1.1.3.1')), - elementShort(0x0008, 0x0018, 'UI', ascii('1.2.3.4.5.6.7.8.9')), - elementShort(0x0008, 0x0060, 'CS', ascii('US')), - elementShort(0x0020, 0x000d, 'UI', ascii('1.2.3.4.5.6.7.8.9.1')), - elementShort(0x0020, 0x000e, 'UI', ascii('1.2.3.4.5.6.7.8.9.2')), - elementShort(0x0028, 0x0002, 'US', u16Bytes(samplesPerPixel)), - elementShort(0x0028, 0x0004, 'CS', ascii(photometricInterpretation)), - ...(options.planarConfiguration == null - ? [] - : [ - elementShort( - 0x0028, - 0x0006, - 'US', - u16Bytes(options.planarConfiguration) - ), - ]), - elementShort(0x0028, 0x0008, 'IS', ascii(String(numberOfFrames))), - elementShort(0x0028, 0x0010, 'US', u16Bytes(rows)), - elementShort(0x0028, 0x0011, 'US', u16Bytes(cols)), - ...(options.pixelSpacing == null - ? [] - : [ - elementShort( - 0x0028, - 0x0030, - 'DS', - ascii(options.pixelSpacing.map((n) => String(n)).join('\\')) - ), - ]), - elementShort(0x0028, 0x0100, 'US', u16Bytes(8)), - elementShort(0x0028, 0x0101, 'US', u16Bytes(8)), - ]); -}; - -function buildNativeDicom(opts: { - numberOfFrames: number; - rows: number; - cols: number; - fillByte?: number; - samplesPerPixel?: number; - photometricInterpretation?: string; - planarConfiguration?: number; - pixelSpacing?: readonly [number, number]; -}): Uint8Array { - const { - numberOfFrames, - rows, - cols, - fillByte = 0x42, - samplesPerPixel = 1, - } = opts; - const preamble = new Uint8Array(128); - const dicm = ascii('DICM'); - const meta = fileMeta(TS_EXPLICIT_VR_LE); - const dataset = COMMON_TAGS(numberOfFrames, rows, cols, opts); - - const pixelBytes = new Uint8Array( - numberOfFrames * rows * cols * samplesPerPixel - ); - pixelBytes.fill(fillByte); - const pixelData = elementLong(0x7fe0, 0x0010, 'OB', pixelBytes); - - return concat([preamble, dicm, meta, dataset, pixelData]); -} - -function buildEncapsulatedDicom(opts: { - rows: number; - cols: number; - frameJpegBytes: Uint8Array[]; - populateBot: boolean; -}): Uint8Array { - const { rows, cols, frameJpegBytes, populateBot } = opts; - const preamble = new Uint8Array(128); - const dicm = ascii('DICM'); - const meta = fileMeta(TS_JPEG_BASELINE); - const dataset = COMMON_TAGS(frameJpegBytes.length, rows, cols); - - // Build the encapsulated PixelData: undefined length (0xFFFFFFFF), BOT item, - // one fragment item per frame, sequence delimitation item. - const fragmentItems = frameJpegBytes.map((bytes) => { - const padded = evenPad(bytes); - const header = new Uint8Array(8); - const dv = new DataView(header.buffer); - dv.setUint16(0, 0xfffe, true); - dv.setUint16(2, 0xe000, true); - dv.setUint32(4, padded.byteLength, true); - return concat([header, padded]); - }); - - const botEntries = new Uint8Array( - populateBot ? frameJpegBytes.length * 4 : 0 - ); - if (populateBot) { - const dv = new DataView(botEntries.buffer); - let relOffset = 0; - frameJpegBytes.forEach((bytes, i) => { - dv.setUint32(i * 4, relOffset, true); - relOffset += 8 + evenPad(bytes).byteLength; - }); - } - const botHeader = new Uint8Array(8); - const botDv = new DataView(botHeader.buffer); - botDv.setUint16(0, 0xfffe, true); - botDv.setUint16(2, 0xe000, true); - botDv.setUint32(4, botEntries.byteLength, true); - const botItem = concat([botHeader, botEntries]); - - const seqDelim = new Uint8Array(8); - const sdv = new DataView(seqDelim.buffer); - sdv.setUint16(0, 0xfffe, true); - sdv.setUint16(2, 0xe0dd, true); - sdv.setUint32(4, 0, true); - - const pdHeader = new Uint8Array(12); - const pdDv = new DataView(pdHeader.buffer); - pdDv.setUint16(0, 0x7fe0, true); - pdDv.setUint16(2, 0x0010, true); - pdHeader[4] = 'O'.charCodeAt(0); - pdHeader[5] = 'B'.charCodeAt(0); - pdDv.setUint32(8, 0xffffffff, true); - - const pdBody = concat([botItem, ...fragmentItems, seqDelim]); - return concat([preamble, dicm, meta, dataset, pdHeader, pdBody]); -} - -// Marker bytes that look like a JPEG SOI/EOI. The parser doesn't actually -// decode them, so any payload with the right framing works. -const fakeJpegFrame = (n: number): Uint8Array => - Uint8Array.from([0xff, 0xd8, 0xff, 0xe0, n & 0xff, 0xff, 0xd9]); - -// ================================================================= -// In-test (synthetic) fixtures — run everywhere -// ================================================================= - -describe('parseCineDicom on synthetic fixtures', () => { - it('parses Explicit VR LE native multi-frame', () => { - const bytes = buildNativeDicom({ - numberOfFrames: 5, - rows: 4, - cols: 3, - fillByte: 0x7f, - }); - const { header, frames, encapsulated } = parseCineDicom(bytes); - expect(encapsulated).toBe(false); - expect(header.numberOfFrames).toBe(5); - expect(header.rows).toBe(4); - expect(header.cols).toBe(3); - expect(header.transferSyntaxUID).toBe(TS_EXPLICIT_VR_LE); - expect(header.photometricInterpretation).toBe('MONOCHROME2'); - expect(header.pixelSpacing).toBeNull(); - expect(frames.length).toBe(5); - expect(frames[0].byteLength).toBe(4 * 3); - expect(frames[0][0]).toBe(0x7f); - }); - - it('parses PixelSpacing row and column values', () => { - const bytes = buildNativeDicom({ - numberOfFrames: 2, - rows: 4, - cols: 3, - pixelSpacing: [1.8, 0.45], - }); - const { header } = parseCineDicom(bytes); - - expect(header.pixelSpacing).toEqual([1.8, 0.45]); - }); - - it('parses native RGB planar-configuration metadata', () => { - const bytes = buildNativeDicom({ - numberOfFrames: 2, - rows: 1, - cols: 2, - samplesPerPixel: 3, - photometricInterpretation: 'RGB', - planarConfiguration: 1, - }); - const { header, frames } = parseCineDicom(bytes); - - expect(header.samplesPerPixel).toBe(3); - expect(header.photometricInterpretation).toBe('RGB'); - expect(header.planarConfiguration).toBe(1); - expect(frames[0].byteLength).toBe(1 * 2 * 3); - }); - - it('parses encapsulated PixelData with a populated BOT', () => { - const frameBytes = [fakeJpegFrame(1), fakeJpegFrame(2), fakeJpegFrame(3)]; - const bytes = buildEncapsulatedDicom({ - rows: 2, - cols: 2, - frameJpegBytes: frameBytes, - populateBot: true, - }); - const { header, frames, encapsulated } = parseCineDicom(bytes); - expect(encapsulated).toBe(true); - expect(header.numberOfFrames).toBe(3); - expect(frames.length).toBe(3); - expect(frames[0][0]).toBe(0xff); - expect(frames[0][1]).toBe(0xd8); - expect(frames[2][4]).toBe(3); // payload byte from fakeJpegFrame(3) - }); - - it('parses encapsulated PixelData with an empty BOT (1-fragment-per-frame)', () => { - const frameBytes = [fakeJpegFrame(10), fakeJpegFrame(20)]; - const bytes = buildEncapsulatedDicom({ - rows: 2, - cols: 2, - frameJpegBytes: frameBytes, - populateBot: false, - }); - const { header, frames } = parseCineDicom(bytes); - expect(header.numberOfFrames).toBe(2); - expect(frames.length).toBe(2); - expect(frames[1][4]).toBe(20); - }); -}); diff --git a/src/core/cine/cineInstance.ts b/src/core/cine/cineInstance.ts new file mode 100644 index 000000000..ad85e22d1 --- /dev/null +++ b/src/core/cine/cineInstance.ts @@ -0,0 +1,194 @@ +import { + EXPLICIT_VR_LITTLE_ENDIAN, + getDatasetTag, + IMPLICIT_VR_LITTLE_ENDIAN, + indexFrames, + isUltrasoundMultiframeSopClass, + readBytes, + splitEncapsulatedFrames, + Tags, + trimDicomPadding, + ultrasoundRegionsOf, + type DicomDataset, + type Instance, +} from '@/packages/dicom/core'; + +const JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; + +const NATIVE_TRANSFER_SYNTAXES = new Set([ + IMPLICIT_VR_LITTLE_ENDIAN, + EXPLICIT_VR_LITTLE_ENDIAN, +]); + +const SUPPORTED_TRANSFER_SYNTAXES = new Set([ + ...NATIVE_TRANSFER_SYNTAXES, + JPEG_BASELINE, +]); + +export const isNativeTransferSyntax = (uid: string) => + NATIVE_TRANSFER_SYNTAXES.has(uid); + +export const isSupportedCineTransferSyntax = (uid: string) => + SUPPORTED_TRANSFER_SYNTAXES.has(uid); + +export type CineHeader = { + transferSyntaxUID: string; + rows: number; + cols: number; + numberOfFrames: number; + samplesPerPixel: number; + bitsAllocated: number; + planarConfiguration: number; + photometricInterpretation: string; + pixelSpacing: [number, number] | null; + frameTimeMs: number | null; + patient: { + PatientID: string; + PatientName: string; + PatientBirthDate: string; + PatientSex: string; + }; + study: { + StudyID: string; + StudyInstanceUID: string; + StudyDate: string; + StudyTime: string; + AccessionNumber: string; + StudyDescription: string; + }; + series: { + SeriesInstanceUID: string; + SeriesNumber: string; + SeriesDescription: string; + Modality: string; + }; + regions: ReturnType; +}; + +const text = (dataset: DicomDataset, tag: string) => + trimDicomPadding(getDatasetTag(dataset, tag) ?? ''); + +/** NaN unless the value is a finite number. */ +const numberOf = (value: string | undefined) => { + const trimmed = trimDicomPadding(value ?? ''); + const number = Number(trimmed); + return trimmed && Number.isFinite(number) ? number : NaN; +}; + +const finiteOrNull = (dataset: DicomDataset, tag: string) => { + const value = numberOf(getDatasetTag(dataset, tag)); + return Number.isFinite(value) ? value : null; +}; + +// Absent or zero counts read as their defaults. +const countOr = (dataset: DicomDataset, tag: string, fallback: number) => + numberOf(getDatasetTag(dataset, tag)) || fallback; + +function positivePair(dataset: DicomDataset, tag: string) { + const values = (getDatasetTag(dataset, tag) ?? '').split('\\').map(numberOf); + const [first, second] = values; + return values.length >= 2 && first > 0 && second > 0 + ? ([first, second] as [number, number]) + : null; +} + +const transferSyntaxOf = (instance: Instance) => + trimDicomPadding(instance.transferSyntaxUid ?? ''); + +/** What a cine clip shows and plays, from the header alone. */ +export function readCineHeader(instance: Instance): CineHeader { + const { dataset } = instance; + const tag = (name: string) => text(dataset, name); + return { + transferSyntaxUID: transferSyntaxOf(instance), + rows: countOr(dataset, Tags.Rows, 0), + cols: countOr(dataset, Tags.Columns, 0), + numberOfFrames: countOr(dataset, Tags.NumberOfFrames, 1), + samplesPerPixel: countOr(dataset, Tags.SamplesPerPixel, 1), + bitsAllocated: countOr(dataset, Tags.BitsAllocated, 8), + planarConfiguration: countOr(dataset, Tags.PlanarConfiguration, 0), + photometricInterpretation: tag(Tags.PhotometricInterpretation), + pixelSpacing: positivePair(dataset, Tags.PixelSpacing), + frameTimeMs: finiteOrNull(dataset, Tags.FrameTime), + patient: { + PatientID: tag(Tags.PatientID), + PatientName: tag(Tags.PatientName), + PatientBirthDate: tag(Tags.PatientBirthDate), + PatientSex: tag(Tags.PatientSex), + }, + study: { + StudyID: tag(Tags.StudyID), + StudyInstanceUID: tag(Tags.StudyInstanceUID), + StudyDate: tag(Tags.StudyDate), + StudyTime: tag(Tags.StudyTime), + AccessionNumber: tag(Tags.AccessionNumber), + StudyDescription: tag(Tags.StudyDescription), + }, + series: { + SeriesInstanceUID: tag(Tags.SeriesInstanceUID), + SeriesNumber: tag(Tags.SeriesNumber), + SeriesDescription: tag(Tags.SeriesDescription), + Modality: tag(Tags.Modality), + }, + regions: ultrasoundRegionsOf(dataset), + }; +} + +// Native clips play as 8 bit grayscale or RGB only. +function supportedNativePixels(dataset: DicomDataset) { + if (countOr(dataset, Tags.BitsAllocated, 8) !== 8) return false; + const photometric = text(dataset, Tags.PhotometricInterpretation); + const samples = countOr(dataset, Tags.SamplesPerPixel, 1); + if (samples === 1) return photometric === 'MONOCHROME2'; + return samples === 3 && photometric === 'RGB'; +} + +/** + * Whether an instance plays as a cine clip: a Part 10 ultrasound multi-frame + * image of more than one frame, in a syntax and pixel format the player reads. + */ +export function isCineInstance(instance: Instance) { + const { dataset } = instance; + const transferSyntax = transferSyntaxOf(instance); + return ( + instance.layout?.preamble === true && + instance.pixelData !== null && + isUltrasoundMultiframeSopClass(text(dataset, Tags.SOPClassUID)) && + numberOf(getDatasetTag(dataset, Tags.NumberOfFrames)) > 1 && + isSupportedCineTransferSyntax(transferSyntax) && + (!isNativeTransferSyntax(transferSyntax) || supportedNativePixels(dataset)) + ); +} + +async function readNativeFrames(instance: Instance, signal: AbortSignal) { + const index = indexFrames(instance); + if (index.kind !== 'indexed') + throw new Error(`Cannot locate the cine frames: ${index.detail}`); + const { frames, frameLength } = index; + const first = frames[0].start; + const bytes = await readBytes(instance.source, signal, { + start: first, + end: first + frames.length * frameLength, + }); + if (bytes.length < frames.length * frameLength) + throw new Error('The cine Pixel Data is cut short'); + return frames.map(({ start }) => + bytes.subarray(start - first, start - first + frameLength) + ); +} + +/** Each frame's stored bytes: raw samples when native, a codestream when encapsulated. */ +export async function readCineFrames( + instance: Instance, + header: CineHeader, + signal: AbortSignal +) { + if (isNativeTransferSyntax(header.transferSyntaxUID)) + return readNativeFrames(instance, signal); + if (!instance.pixelData || instance.pixelData.length !== null) + throw new Error('The cine Pixel Data is not encapsulated'); + const value = await readBytes(instance.source, signal, { + start: instance.pixelData.valueOffset, + }); + return splitEncapsulatedFrames(value, header.numberOfFrames); +} diff --git a/src/core/cine/parseCineDicom.ts b/src/core/cine/parseCineDicom.ts deleted file mode 100644 index 411b4753a..000000000 --- a/src/core/cine/parseCineDicom.ts +++ /dev/null @@ -1,304 +0,0 @@ -import dicomParser, { DataSet, Element } from 'dicom-parser'; - -// ================================================================= -// Tag constants (dicom-parser format: 'xGGGGEEEE', lowercase hex) -// ================================================================= - -const TAG_PIXEL_DATA = 'x7fe00010'; -const TAG_PATIENT_NAME = 'x00100010'; -const TAG_PATIENT_ID = 'x00100020'; -const TAG_PATIENT_BIRTH_DATE = 'x00100030'; -const TAG_PATIENT_SEX = 'x00100040'; -const TAG_STUDY_INSTANCE_UID = 'x0020000d'; -const TAG_STUDY_DATE = 'x00080020'; -const TAG_STUDY_TIME = 'x00080030'; -const TAG_STUDY_ID = 'x00200010'; -const TAG_ACCESSION_NUMBER = 'x00080050'; -const TAG_STUDY_DESCRIPTION = 'x00081030'; -const TAG_MODALITY = 'x00080060'; -const TAG_SERIES_INSTANCE_UID = 'x0020000e'; -const TAG_SERIES_NUMBER = 'x00200011'; -const TAG_SERIES_DESCRIPTION = 'x0008103e'; -const TAG_NUMBER_OF_FRAMES = 'x00280008'; -const TAG_ROWS = 'x00280010'; -const TAG_COLUMNS = 'x00280011'; -const TAG_PIXEL_SPACING = 'x00280030'; -const TAG_BITS_ALLOCATED = 'x00280100'; -const TAG_SAMPLES_PER_PIXEL = 'x00280002'; -const TAG_PHOTOMETRIC = 'x00280004'; -const TAG_FRAME_TIME = 'x00181063'; -const TAG_SEQUENCE_OF_ULTRASOUND_REGIONS = 'x00186011'; -const TAG_PLANAR_CONFIGURATION = 'x00280006'; - -const TAG_PHYSICAL_UNITS_X = 'x00186024'; -const TAG_PHYSICAL_UNITS_Y = 'x00186026'; -const TAG_PHYSICAL_DELTA_X = 'x0018602c'; -const TAG_PHYSICAL_DELTA_Y = 'x0018602e'; - -const TAG_TRANSFER_SYNTAX_UID = 'x00020010'; - -// ================================================================= -// Public types -// ================================================================= - -type CineUltrasoundRegion = { - physicalDeltaX: number | null; - physicalDeltaY: number | null; - physicalUnitsX: number | null; - physicalUnitsY: number | null; -}; - -type CinePatientInfo = { - PatientID: string; - PatientName: string; - PatientBirthDate: string; - PatientSex: string; -}; - -type CineStudyInfo = { - StudyID: string; - StudyInstanceUID: string; - StudyDate: string; - StudyTime: string; - AccessionNumber: string; - StudyDescription: string; -}; - -type CineSeriesInfo = { - SeriesInstanceUID: string; - SeriesNumber: string; - SeriesDescription: string; - Modality: string; -}; - -export type CineHeader = { - transferSyntaxUID: string; - rows: number; - cols: number; - numberOfFrames: number; - samplesPerPixel: number; - bitsAllocated: number; - planarConfiguration: number; - photometricInterpretation: string; - pixelSpacing: [number, number] | null; - frameTimeMs: number | null; - patient: CinePatientInfo; - study: CineStudyInfo; - series: CineSeriesInfo; - regions: CineUltrasoundRegion[]; -}; - -export type CineParseResult = { - header: CineHeader; - // Native: zero-copy view into the source buffer. Encapsulated: bytes for - // one frame, possibly assembled from multiple fragments. - frames: Uint8Array[]; - encapsulated: boolean; -}; - -// ================================================================= -// Tag readers -// ================================================================= - -const str = (ds: DataSet, tag: string): string => (ds.string(tag) ?? '').trim(); - -const intStr = (ds: DataSet, tag: string): number => ds.intString(tag) ?? 0; - -const u16 = (ds: DataSet, tag: string): number => ds.uint16(tag) ?? 0; - -// VR=FD (PhysicalDeltaX/Y in ultrasound regions) -const readDouble = (ds: DataSet, tag: string): number | null => { - const v = ds.double(tag); - return v !== undefined && Number.isFinite(v) ? v : null; -}; - -// VR=DS (FrameTime, decimal string) -const readDecimalString = (ds: DataSet, tag: string): number | null => { - const v = ds.floatString(tag); - return v !== undefined && Number.isFinite(v) ? v : null; -}; - -const isPositiveFinite = (v: number | undefined): v is number => - v !== undefined && Number.isFinite(v) && v > 0; - -const readPositiveDecimalPair = ( - ds: DataSet, - tag: string -): [number, number] | null => { - const first = ds.floatString(tag, 0); - const second = ds.floatString(tag, 1); - return isPositiveFinite(first) && isPositiveFinite(second) - ? [first, second] - : null; -}; - -function buildRegion(item: DataSet): CineUltrasoundRegion { - return { - physicalDeltaX: readDouble(item, TAG_PHYSICAL_DELTA_X), - physicalDeltaY: readDouble(item, TAG_PHYSICAL_DELTA_Y), - physicalUnitsX: u16(item, TAG_PHYSICAL_UNITS_X) || null, - physicalUnitsY: u16(item, TAG_PHYSICAL_UNITS_Y) || null, - }; -} - -// ================================================================= -// PixelData extraction -// ================================================================= - -function extractEncapsulatedFrames( - ds: DataSet, - pd: Element, - numberOfFrames: number -): Uint8Array[] { - const bot = pd.basicOffsetTable ?? []; - const fragments = pd.fragments ?? []; - - let offsets: number[]; - if (bot.length === numberOfFrames) { - offsets = bot; - } else if (fragments.length === numberOfFrames) { - offsets = fragments.map((f) => f.offset); - } else { - // Empty BOT and fragments don't map 1:1 — scan for JPEG SOI markers. - offsets = dicomParser.createJPEGBasicOffsetTable(ds, pd); - } - - const frames: Uint8Array[] = []; - for (let i = 0; i < numberOfFrames; i++) { - // ByteArray = Uint8Array | Buffer in the TS shim; in browser it's always Uint8Array. - frames.push( - dicomParser.readEncapsulatedImageFrame( - ds, - pd, - i, - offsets, - fragments - ) as Uint8Array - ); - } - return frames; -} - -function extractNativeFrames( - ds: DataSet, - pd: Element, - numberOfFrames: number, - frameBytes: number -): Uint8Array[] { - const byteArray = ds.byteArray; - const frames: Uint8Array[] = []; - for (let i = 0; i < numberOfFrames; i++) { - frames.push( - new Uint8Array( - byteArray.buffer, - byteArray.byteOffset + pd.dataOffset + i * frameBytes, - frameBytes - ) - ); - } - return frames; -} - -// ================================================================= -// Public entry point -// ================================================================= - -export function parseCineDicom( - input: ArrayBuffer | Uint8Array -): CineParseResult { - const u8 = - input instanceof Uint8Array ? input : new Uint8Array(input as ArrayBuffer); - const ds = dicomParser.parseDicom(u8); - - const pd = ds.elements[TAG_PIXEL_DATA]; - if (!pd) { - throw new Error('PixelData (7FE0,0010) not found in DICOM file'); - } - - const numberOfFrames = intStr(ds, TAG_NUMBER_OF_FRAMES) || 1; - const rows = u16(ds, TAG_ROWS); - const cols = u16(ds, TAG_COLUMNS); - const samplesPerPixel = u16(ds, TAG_SAMPLES_PER_PIXEL) || 1; - const bitsAllocated = u16(ds, TAG_BITS_ALLOCATED) || 8; - const planarConfiguration = u16(ds, TAG_PLANAR_CONFIGURATION); - const transferSyntaxUID = str(ds, TAG_TRANSFER_SYNTAX_UID); - - const regionItems = - ds.elements[TAG_SEQUENCE_OF_ULTRASOUND_REGIONS]?.items ?? []; - const regions = regionItems - .map((item) => item.dataSet) - .filter((d): d is DataSet => !!d) - .map(buildRegion); - - const header: CineHeader = { - transferSyntaxUID, - rows, - cols, - numberOfFrames, - samplesPerPixel, - bitsAllocated, - planarConfiguration, - photometricInterpretation: str(ds, TAG_PHOTOMETRIC), - pixelSpacing: readPositiveDecimalPair(ds, TAG_PIXEL_SPACING), - frameTimeMs: readDecimalString(ds, TAG_FRAME_TIME), - patient: { - PatientID: str(ds, TAG_PATIENT_ID), - PatientName: str(ds, TAG_PATIENT_NAME), - PatientBirthDate: str(ds, TAG_PATIENT_BIRTH_DATE), - PatientSex: str(ds, TAG_PATIENT_SEX), - }, - study: { - StudyID: str(ds, TAG_STUDY_ID), - StudyInstanceUID: str(ds, TAG_STUDY_INSTANCE_UID), - StudyDate: str(ds, TAG_STUDY_DATE), - StudyTime: str(ds, TAG_STUDY_TIME), - AccessionNumber: str(ds, TAG_ACCESSION_NUMBER), - StudyDescription: str(ds, TAG_STUDY_DESCRIPTION), - }, - series: { - SeriesInstanceUID: str(ds, TAG_SERIES_INSTANCE_UID), - SeriesNumber: str(ds, TAG_SERIES_NUMBER), - SeriesDescription: str(ds, TAG_SERIES_DESCRIPTION), - Modality: str(ds, TAG_MODALITY), - }, - regions, - }; - - const encapsulated = !!pd.encapsulatedPixelData; - const frames = encapsulated - ? extractEncapsulatedFrames(ds, pd, numberOfFrames) - : extractNativeFrames( - ds, - pd, - numberOfFrames, - rows * cols * samplesPerPixel * Math.ceil(bitsAllocated / 8) - ); - - return { header, frames, encapsulated }; -} - -// ================================================================= -// Supported transfer syntaxes -// ================================================================= - -const TRANSFER_SYNTAX_IMPLICIT_VR_LE = '1.2.840.10008.1.2'; -const TRANSFER_SYNTAX_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; -const TRANSFER_SYNTAX_JPEG_BASELINE_1 = '1.2.840.10008.1.2.4.50'; - -const NATIVE_TRANSFER_SYNTAXES = new Set([ - TRANSFER_SYNTAX_IMPLICIT_VR_LE, - TRANSFER_SYNTAX_EXPLICIT_VR_LE, -]); - -const SUPPORTED_TRANSFER_SYNTAXES = new Set([ - ...NATIVE_TRANSFER_SYNTAXES, - TRANSFER_SYNTAX_JPEG_BASELINE_1, -]); - -export function isNativeTransferSyntax(uid: string): boolean { - return NATIVE_TRANSFER_SYNTAXES.has(uid); -} - -export function isSupportedCineTransferSyntax(uid: string): boolean { - return SUPPORTED_TRANSFER_SYNTAXES.has(uid); -} diff --git a/src/core/progressiveImage.ts b/src/core/progressiveImage.ts index 16140d2fc..24eaf9062 100644 --- a/src/core/progressiveImage.ts +++ b/src/core/progressiveImage.ts @@ -1,5 +1,5 @@ import { computed, effectScope, ref, Ref, shallowRef } from 'vue'; -import type { SpatialMetadata } from '@/packages/dicom/core/metadata/spatialMetadata'; +import type { SpatialMetadata } from '@/packages/dicom/core'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { ImageMetadata } from '@/src/types/image'; import { onVTKEvent } from '@/src/composables/onVTKEvent'; diff --git a/packages/dicom/core/streaming/__tests__/cachedStreamFetcher.spec.ts b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts similarity index 92% rename from packages/dicom/core/streaming/__tests__/cachedStreamFetcher.spec.ts rename to src/core/streaming/__tests__/cachedStreamFetcher.spec.ts index dbd74db9f..9b2cbcdc3 100644 --- a/packages/dicom/core/streaming/__tests__/cachedStreamFetcher.spec.ts +++ b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts @@ -1,5 +1,8 @@ -import { RequestPool } from '../requestPool'; -import { CachedStreamFetcher, sliceChunks } from '../cachedStreamFetcher'; +import { createDicomRuntime } from '@/packages/dicom/core'; +import { + CachedStreamFetcher, + sliceChunks, +} from '@/src/core/streaming/cachedStreamFetcher'; import { describe, expect, it } from 'vitest'; const readStream = async ( @@ -69,9 +72,12 @@ describe('CachedStreamFetcher', () => { }, }); }; - const pool = new RequestPool(1, fetchRange); + const runtime = createDicomRuntime({ + requestConcurrency: 1, + fetch: fetchRange, + }); const fetcher = new CachedStreamFetcher('https://example.test/data', { - fetch: pool.fetch, + fetch: runtime.fetch, }); await fetcher.connect(); @@ -92,6 +98,7 @@ describe('CachedStreamFetcher', () => { expect(requestedRanges).toHaveLength(2); fetcher.close(); + runtime.dispose(); }); }); diff --git a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts index 74782beab..0481725ce 100644 --- a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts +++ b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts @@ -1,31 +1,23 @@ import { afterEach, describe, expect, it } from 'vitest'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; -import { datasetFromTags } from '@/tests/dicomDataset'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { plannedUpdate } from '@/packages/dicom/core/volume/__tests__/volumeFixture'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { - fromBlob, - type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; import { allocateVolume, - type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; -import { createDicomRuntime, + fromBlob, + readInstance, + Tags, + type ByteSource, + type DecodedPixels, type DicomRuntime, - type PixelDecoder, -} from '@/packages/dicom/core/runtime/createDicomRuntime'; -import type { Extent } from '@/packages/dicom/core/volume/loadVolume'; -import { US_UNIT_CENTIMETERS } from '@/packages/dicom/core/streaming/dicom/ultrasoundRegion'; -import { - sliceToThumbnail, - type ThumbnailSlice, -} from '@/packages/dicom/vtk/thumbnail'; -import { defer } from '@/packages/dicom/core/utils'; -import { readInstance } from '@/packages/dicom/core/instance/readInstance'; + type Extent, + type Instance, + type Volume, + type WholeInstanceDecode, +} from '@/packages/dicom/core'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; +import { sliceThumbnail, type ThumbnailSlice } from '@/packages/dicom/vtk'; +import { defer } from '@/src/utils'; import { nativePixelDicom } from '@/tests/nativePixelDicom'; import DicomVolumeImage, { type DicomVolumeImageInit, @@ -34,6 +26,8 @@ import DicomVolumeImage, { const ROWS = 2; const COLUMNS = 2; const PIXELS_PER_SLICE = ROWS * COLUMNS; +// Physical Units X/Y Direction code for centimeters. +const CENTIMETERS = 3; const PUBLIC_DSC_SLOPE = 112067.85375182; // The slice's z position is also its pixel value, so decoded contents say @@ -55,30 +49,25 @@ function sliceAt(z: number, overrides: Record = {}) { return instanceFor(datasetFromTags(tags), fromBlob(new Blob([String(z)]))); } -function volumeOf(members: Instance[], previous?: Volume) { - const allocation = allocateVolume(plannedUpdate(members), {}, previous); - if (allocation.kind !== 'volume') throw new Error('Expected a volume'); - return allocation.volume; -} +const volumeOf = (members: Instance[], previous?: Volume) => + allocateVolume(plannedUpdate(members), {}, previous); const stack = (count: number) => volumeOf(Array.from({ length: count }, (_, z) => sliceAt(z))); -type Decoded = Awaited>; - /** Decodes a source written by `sliceAt`, recording the values it decodes. */ function decodeTo( dataFor: (value: number) => ArrayLike, components = 1 ) { const decoded: number[] = []; - const decoder: PixelDecoder = async ({ bytes }) => { + const decoder: WholeInstanceDecode = async ({ bytes }) => { const value = Number(new TextDecoder().decode(bytes)); decoded.push(value); return { size: [COLUMNS, ROWS, 1], - data: dataFor(value) as Decoded['data'], - imageType: { components }, + data: dataFor(value) as DecodedPixels['data'], + components, }; }; return { decoded, decoder }; @@ -95,12 +84,12 @@ afterEach(() => { }); function holder( - decoder: PixelDecoder, + decoder: WholeInstanceDecode, init: Omit = {}, requestConcurrency?: number ) { const runtime = createDicomRuntime({ - decoder, + ...decodingWith(decoder), decodeConcurrency: 1, requestConcurrency, }); @@ -159,12 +148,7 @@ const scalarRange = (image: DicomVolumeImage) => const filledWith = (value: number) => Array(PIXELS_PER_SLICE).fill(value); const thumbnailOf = (image: DicomVolumeImage, slice: number) => - sliceToThumbnail({ - data: sliceOf(image, slice), - width: COLUMNS, - height: ROWS, - range: scalarRange(image), - }); + sliceThumbnail(image.getVtkImageData(), slice); describe('DicomVolumeImage loading', () => { it('fills every slice, reporting each decoded extent, then completes', async () => { @@ -270,8 +254,8 @@ describe('DicomVolumeImage loading', () => { region: { physicalDeltaX, physicalDeltaY: 0.03, - physicalUnitsXDirection: US_UNIT_CENTIMETERS, - physicalUnitsYDirection: US_UNIT_CENTIMETERS, + physicalUnitsXDirection: CENTIMETERS, + physicalUnitsYDirection: CENTIMETERS, }, regionCount: 1, }, diff --git a/packages/dicom/core/streaming/cachedStreamFetcher.ts b/src/core/streaming/cachedStreamFetcher.ts similarity index 97% rename from packages/dicom/core/streaming/cachedStreamFetcher.ts rename to src/core/streaming/cachedStreamFetcher.ts index 423e3a646..dee71a767 100644 --- a/packages/dicom/core/streaming/cachedStreamFetcher.ts +++ b/src/core/streaming/cachedStreamFetcher.ts @@ -3,13 +3,13 @@ import { HTTP_STATUS_PARTIAL_CONTENT, HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, HttpNotFound, -} from './httpCodes'; -import { Fetcher, FetcherInit } from './types'; +} from '@/src/core/streaming/httpCodes'; +import { Fetcher, FetcherInit } from '@/src/core/streaming/types'; import { ContentRange, parseContentRangeHeader, -} from '../utils/parseContentRangeHeader'; -import { Maybe } from '../utils'; +} from '@/src/utils/parseContentRangeHeader'; +import { Maybe } from '@/src/types'; type FetchFunction = typeof fetch; diff --git a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts index 8ef99ee48..82700fb95 100644 --- a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts +++ b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts @@ -1,15 +1,15 @@ -import dicomParser, { type DataSet } from 'dicom-parser'; import { deflateRawSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { + fromBlob, + readDicomDataset, + readInstance, + Tags, +} from '@/packages/dicom/core'; import { dicomMetadataForDisplay } from '@/src/core/streaming/dicom/octMetadata'; -import { readInstance } from '@/packages/dicom/core/instance/readInstance'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import { trackedSource } from '@/packages/dicom/core/source/__tests__/sourceFixtures'; -import { readDicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { trackedSource } from '@/tests/byteSourceFixtures'; import { dicomDatasetToTags } from '@/src/io/readDicomTags'; -import { deflatedExplicitVR } from '@/tests/fixtures/oct/volumes'; import { isOCTMetadata, OCT_GEOMETRY_ERROR, @@ -25,27 +25,12 @@ import { element, enhancedFile, sequence, - overwriteDicomString, } from '@/tests/fixtures/oct/dicom'; -const firstItem = (data: DataSet, tag: string) => - data.elements[tag].items![0].dataSet!; - -function fixtureBytes() { - return new Uint8Array(createSyntheticOCT()); -} - -function readDataset(bytes: Uint8Array) { - return dicomParser.parseDicom(bytes, { untilTag: 'x7fe00010' }); -} +const fixtureBytes = (...options: Parameters) => + new Uint8Array(createSyntheticOCT(...options)); -function hide(data: DataSet, tag: string) { - const attribute = data.elements[tag]; - // Explicit-VR DS headers are 8 bytes. Rename to an unused private group. - const start = attribute.dataOffset - 8; - data.byteArray[start] = 0x77; - data.byteArray[start + 1] = 0x77; -} +const SHARED_ORIENTATION = '52009229.00209116.00200037'; const spatialMetadataError = (metadata: Iterable<[string, string]>) => new Map(metadata).get(OCT_GEOMETRY_ERROR); @@ -90,10 +75,9 @@ describe('OCT DICOM activation', () => { ); it('preserves non-OCT metadata without adding projection fields', () => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - overwriteDicomString(data, 'x00080016', '1.2.840.10008.5.1.4.1.1.2'); - overwriteDicomString(data, 'x00080060', 'CT'); + const bytes = fixtureBytes({ + set: { '00080016': '1.2.840.10008.5.1.4.1.1.2', '00080060': 'CT' }, + }); const dataset = readDicomDataset(bytes); expect(dicomMetadataForDisplay(dataset)).toEqual( dicomDatasetToTags(dataset) @@ -130,7 +114,9 @@ describe('OCT enhanced spatial metadata', () => { element('00111010', 'OB', new Uint8Array()), ]).arrayBuffer() ); - const start = readDataset(empty).elements.x00111010.dataOffset; + const emptyElement = element('00111010', 'OB', new Uint8Array()); + const start = + Buffer.from(empty).indexOf(emptyElement) + emptyElement.length; const header = enhancedFile(frames, [ element('00111010', 'OB', new Uint8Array(end - start)), ]); @@ -146,22 +132,18 @@ describe('OCT enhanced spatial metadata', () => { it('uses the complete deflated stream when it exceeds the header probe', async () => { const source = fixtureBytes(); - const bytes = deflatedExplicitVR(source, (dataset) => - deflateRawSync(dataset, { level: 0 }) - ); + const bytes = fixtureBytes({ + deflate: (dataset) => deflateRawSync(dataset, { level: 0 }), + }); expect(bytes.length).toBeGreaterThan(64 * 1024); expect(await augmented(bytes)).toEqual(await augmented(source)); }); it('reads deflated Explicit VR geometry with the required trailing NULL padding', async () => { - const source = new Uint8Array( - await enhancedFile([ - { position: '0\\0\\0' }, - { position: '0\\0\\0.2' }, - ]).arrayBuffer() - ); + const frames = [{ position: '0\\0\\0' }, { position: '0\\0\\0.2' }]; + const source = new Uint8Array(await enhancedFile(frames).arrayBuffer()); let streamLength = 0; - const bytes = deflatedExplicitVR(source, (dataset) => { + const deflate = (dataset: Uint8Array) => { expect(dataset.length).toBeLessThan(65536); // A final stored DEFLATE block adds five bytes to the even DICOM dataset. const header = Buffer.alloc(5); @@ -171,7 +153,10 @@ describe('OCT enhanced spatial metadata', () => { const stream = Buffer.concat([header, dataset]); streamLength = stream.length; return stream; - }); + }; + const bytes = new Uint8Array( + await enhancedFile(frames, [], { deflate }).arrayBuffer() + ); expect(streamLength % 2).toBe(1); expect(bytes.length % 2).toBe(0); expect(bytes.at(-1)).toBe(0); @@ -179,7 +164,7 @@ describe('OCT enhanced spatial metadata', () => { }); it('rejects a truncated deflated dataset before projecting its metadata', async () => { - const bytes = deflatedExplicitVR(fixtureBytes()); + const bytes = fixtureBytes({ deflate: true }); await expect(augmented(bytes.subarray(0, -10))).rejects.toThrow(); }); @@ -189,7 +174,7 @@ describe('OCT enhanced spatial metadata', () => { { preamble: 0, groupLength: false }, ])('reads deflated geometry with %j', async ({ preamble, groupLength }) => { const source = fixtureBytes(); - let bytes = deflatedExplicitVR(source); + let bytes = Buffer.from(fixtureBytes({ deflate: true })); bytes.fill(preamble, 0, 128); if (!groupLength) bytes = Buffer.concat([bytes.subarray(0, 132), bytes.subarray(144)]); @@ -214,9 +199,7 @@ describe('OCT enhanced spatial metadata', () => { }); it('preserves declared scan patterns such as radial scans', async () => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - overwriteDicomString(firstItem(data, 'x00221618'), 'x00080100', '128282'); + const bytes = fixtureBytes({ scanPattern: '128282' }); const tags = await augmented(bytes); expect(isOCTMetadata(tags)).toBe(true); expect(tags.get(OCT_SCAN_PATTERN)).toBe('128282'); @@ -232,15 +215,10 @@ describe('OCT enhanced spatial metadata', () => { sequence('00221640', [ sequence('00221618', [element('00080100', 'SH', pattern)]), ]), - ] - ); - const bytes = new Uint8Array(await file.arrayBuffer()); - overwriteDicomString( - readDataset(bytes), - 'x00080016', - OPHTHALMIC_BSCAN_ANALYSIS_SOP + ], + { set: { '00080016': OPHTHALMIC_BSCAN_ANALYSIS_SOP } } ); - const tags = await augmented(bytes); + const tags = new Map(await projectFile(file)); expect(tags.get(OCT_SCAN_PATTERN)).toBe(pattern); } ); @@ -279,20 +257,16 @@ describe('OCT enhanced spatial metadata', () => { }); it('preserves declarations marking a volume unsuitable for volumetric processing', async () => { - const bytes = fixtureBytes(); - overwriteDicomString(readDataset(bytes), 'x00221622', 'NO'); + const bytes = fixtureBytes({ set: { '00221622': 'NO' } }); expect( (await augmented(bytes)).get(Tags.OphthalmicVolumetricPropertiesFlag) ).toBe('NO'); }); it('preserves missing pixel spacing for the loader fallback', async () => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - const shared = firstItem(data, 'x52009229'); - const measures = firstItem(shared, 'x00289110'); - hide(data, 'x00280030'); - hide(measures, 'x00280030'); + const bytes = fixtureBytes({ + omit: ['00280030', '52009229.00289110.00280030'], + }); const tags = await augmented(bytes); expect(isOCTMetadata(tags)).toBe(true); expect(spatialMetadataError(tags)).toBeUndefined(); @@ -300,8 +274,7 @@ describe('OCT enhanced spatial metadata', () => { }); it('rejects a per-frame geometry count that disagrees with NumberOfFrames', async () => { - const bytes = fixtureBytes(); - overwriteDicomString(readDataset(bytes), 'x00280008', '31'); + const bytes = fixtureBytes({ set: { '00280008': '31' } }); expect(spatialMetadataError(await augmented(bytes))).toMatch( /frame.*count|number.*frames/i ); @@ -315,14 +288,9 @@ describe('OCT enhanced spatial metadata', () => { ])( 'rejects direction cosines that would distort physical thickness %#', async (...orientation) => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - const shared = firstItem(data, 'x52009229'); - overwriteDicomString( - firstItem(shared, 'x00209116'), - 'x00200037', - orientation.join('\\') - ); + const bytes = fixtureBytes({ + set: { [SHARED_ORIENTATION]: orientation.join('\\') }, + }); expect(spatialMetadataError(await augmented(bytes))).toMatch( /orientation|orthonormal|direction/i ); @@ -332,23 +300,20 @@ describe('OCT enhanced spatial metadata', () => { it.each(['position', 'orientation', 'nonunit orientation'])( 'preserves top-level geometry when enhanced %s is invalid', async (kind) => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - if (kind === 'position') { - overwriteDicomString( - firstItem(firstItem(data, 'x52009230'), 'x00209113'), - 'x00200032', - '0\\0' - ); - } else { - overwriteDicomString( - firstItem(firstItem(data, 'x52009229'), 'x00209116'), - 'x00200037', - kind === 'orientation' ? '1\\0\\0\\0\\1' : '2\\0\\0\\0\\.5\\0' - ); - } - overwriteDicomString(data, 'x00200032', '9\\8\\7'); - overwriteDicomString(data, 'x00200037', '1\\0\\0\\0\\1\\0'); + const invalid: Record = + kind === 'position' + ? { '52009230.00209113.00200032': '0\\0' } + : { + [SHARED_ORIENTATION]: + kind === 'orientation' ? '1\\0\\0\\0\\1' : '2\\0\\0\\0\\.5\\0', + }; + const bytes = fixtureBytes({ + set: { + ...invalid, + '00200032': '9\\8\\7', + '00200037': '1\\0\\0\\0\\1\\0', + }, + }); const tags = await augmented(bytes); expect(spatialMetadataError(tags)).toBeTruthy(); expect(tags.get(Tags.ImagePositionPatient)?.trim()).toBe('9\\8\\7'); @@ -360,28 +325,20 @@ describe('OCT enhanced spatial metadata', () => { it.each([false, true])( 'rejects nonuniform B-scan positions with deflate=%s', async (deflated) => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - const finalFrame = data.elements.x52009230.items!.at(-1)!.dataSet!; - const position = firstItem(finalFrame, 'x00209113'); - overwriteDicomString(position, 'x00200032', '0.0\\0.0\\5.8225'); - expect( - spatialMetadataError( - await augmented(deflated ? deflatedExplicitVR(bytes) : bytes) - ) - ).toMatch(/nonuniform/); + const bytes = fixtureBytes({ + set: { '52009230[-1].00209113.00200032': '0.0\\0.0\\5.8225' }, + deflate: deflated, + }); + expect(spatialMetadataError(await augmented(bytes))).toMatch( + /nonuniform/ + ); } ); it('rejects tilted scan positions that leave the Cartesian voxel grid', async () => { - const bytes = fixtureBytes(); - const data = readDataset(bytes); - const secondFrame = data.elements.x52009230.items![1].dataSet!; - overwriteDicomString( - firstItem(secondFrame, 'x00209113'), - 'x00200032', - '1.0\\0.0\\0.1875' - ); + const bytes = fixtureBytes({ + set: { '52009230[1].00209113.00200032': '1.0\\0.0\\0.1875' }, + }); expect(spatialMetadataError(await augmented(bytes))).toMatch( /image grid|nonuniform positions/ ); @@ -411,12 +368,9 @@ describe('OCT enhanced spatial metadata', () => { }); it('accepts rounded orthogonal direction cosines', async () => { - const bytes = fixtureBytes(); - overwriteDicomString( - firstItem(firstItem(readDataset(bytes), 'x52009229'), 'x00209116'), - 'x00200037', - '.8660\\.5\\0\\-.5\\.8660\\0' - ); + const bytes = fixtureBytes({ + set: { [SHARED_ORIENTATION]: '.8660\\.5\\0\\-.5\\.8660\\0' }, + }); expect(spatialMetadataError(await augmented(bytes))).toBeUndefined(); }); @@ -426,7 +380,9 @@ describe('OCT enhanced spatial metadata', () => { const position = normal.map((n) => (n * 0.2).toFixed(4)).join('\\'); const tags = new Map( await projectFile( - enhancedFile([{ position: '0\\0\\0' }, { position }], [], orientation) + enhancedFile([{ position: '0\\0\\0' }, { position }], [], { + orientation, + }) ) ); expect(spatialMetadataError(tags)).toBeUndefined(); @@ -439,26 +395,20 @@ describe('OCT enhanced spatial metadata', () => { 'uses %s orientation when the shared value is blank', async (fallback) => { const orientation = '1\\0\\0\\0\\1\\0'; - const bytes = new Uint8Array( - await enhancedFile( - [ - { - position: '0\\0\\0', - ...(fallback === 'frame' ? { orientation } : {}), - }, - { position: '0\\0\\0.2' }, - ], - fallback === 'top level' - ? [element('00200037', 'DS', orientation)] - : [] - ).arrayBuffer() - ); - overwriteDicomString( - firstItem(firstItem(readDataset(bytes), 'x52009229'), 'x00209116'), - 'x00200037', - ' ' + const file = enhancedFile( + [ + { + position: '0\\0\\0', + ...(fallback === 'frame' ? { orientation } : {}), + }, + { position: '0\\0\\0.2' }, + ], + fallback === 'top level' + ? [element('00200037', 'DS', orientation)] + : [], + { orientation: ' '.repeat(orientation.length + 1) } ); - const tags = await augmented(bytes); + const tags = new Map(await projectFile(file)); expect(spatialMetadataError(tags)).toBeUndefined(); expect(tags.get(Tags.ImageOrientationPatient)).toBe(orientation); expect(tags.get(Tags.ImagePositionPatient)).toBe('0\\0\\0'); @@ -496,29 +446,21 @@ describe('OCT enhanced spatial metadata', () => { ); it('requires orientation before deriving spacing from positioned frames', async () => { - const bytes = new Uint8Array( - await enhancedFile([ - { position: '0\\0\\0' }, - { position: '0.2\\0\\0' }, - ]).arrayBuffer() + const file = enhancedFile( + [{ position: '0\\0\\0' }, { position: '0.2\\0\\0' }], + [], + { omit: [SHARED_ORIENTATION] } ); - const shared = firstItem(readDataset(bytes), 'x52009229'); - hide(firstItem(shared, 'x00209116'), 'x00200037'); - const tags = await augmented(bytes); + const tags = new Map(await projectFile(file)); expect(spatialMetadataError(tags)).toMatch(/orientation.*missing/); expect(tags.has(Tags.SpacingBetweenSlices)).toBe(false); }); it('preserves unpositioned frames without patient orientation', async () => { - const bytes = new Uint8Array( - await enhancedFile( - [{}, {}], - [element('00180088', 'DS', '0.2')] - ).arrayBuffer() - ); - const shared = firstItem(readDataset(bytes), 'x52009229'); - hide(firstItem(shared, 'x00209116'), 'x00200037'); - const tags = await augmented(bytes); + const file = enhancedFile([{}, {}], [element('00180088', 'DS', '0.2')], { + omit: [SHARED_ORIENTATION], + }); + const tags = new Map(await projectFile(file)); expect(spatialMetadataError(tags)).toBeUndefined(); expect(tags.get(Tags.SpacingBetweenSlices)).toBe('0.2'); }); diff --git a/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts b/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts index 39c24a2ac..77d4ef37c 100644 --- a/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts +++ b/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts @@ -1,8 +1,11 @@ import { describe, expect, it, vi } from 'vitest'; -import { readDicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { readInstance } from '@/packages/dicom/core/instance/readInstance'; -import { fromBlob, fromUrl } from '@/packages/dicom/core/source/byteSource'; +import { + fromBlob, + fromUrl, + readDicomDataset, + readInstance, + Tags, +} from '@/packages/dicom/core'; import { dicomMetadataForDisplay } from '../octMetadata'; import { OCT_GEOMETRY_ERROR, OCT_SCAN_PATTERN } from '../octMetadataTags'; import { @@ -11,7 +14,6 @@ import { enhancedFile, sequence, } from '@/tests/fixtures/oct/dicom'; -import { deflatedExplicitVR } from '@/tests/fixtures/oct/volumes'; const positions = (values: number[]) => values.map((z) => ({ position: `0\\0\\${z}` })); @@ -76,8 +78,7 @@ describe('structured OCT application metadata', () => { it.each([false, true])( 'matches file and HTTP OCT metadata after loading, deflated=%s', async (deflated) => { - const original = new Uint8Array(createSyntheticOCT()); - const bytes = deflated ? deflatedExplicitVR(original) : original; + const bytes = new Uint8Array(createSyntheticOCT({ deflate: deflated })); const file = new File([bytes], 'oct.dcm'); const fetch = vi.fn( async () => diff --git a/src/core/streaming/dicom/octDataset.ts b/src/core/streaming/dicom/octDataset.ts index b3ab79d37..d28b88b9d 100644 --- a/src/core/streaming/dicom/octDataset.ts +++ b/src/core/streaming/dicom/octDataset.ts @@ -1,7 +1,9 @@ -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { sequenceItems } from '@/packages/dicom/core/metadata/functionalGroups'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; +import { + getDatasetTag, + sequenceItems, + trimDicomPadding, + type DicomDataset, +} from '@/packages/dicom/core'; /** The OCT policy reads attributes and their explicit sequence paths only. */ export type OCTDataset = { @@ -9,14 +11,11 @@ export type OCTDataset = { items: (tag: string) => OCTDataset[]; }; -const structuredTag = (tag: string) => tag.slice(1).toUpperCase(); - /** Adapts already loaded metadata without reparsing or retaining source bytes. */ export const structuredOCTDataset = (dataset: DicomDataset): OCTDataset => ({ value: (tag) => { - const value = getDatasetTag(dataset, structuredTag(tag)); + const value = getDatasetTag(dataset, tag); return value === undefined ? undefined : trimDicomPadding(value); }, - items: (tag) => - sequenceItems(dataset, structuredTag(tag)).map(structuredOCTDataset), + items: (tag) => sequenceItems(dataset, tag).map(structuredOCTDataset), }); diff --git a/src/core/streaming/dicom/octMetadata.ts b/src/core/streaming/dicom/octMetadata.ts index 133f6a128..d6a34444c 100644 --- a/src/core/streaming/dicom/octMetadata.ts +++ b/src/core/streaming/dicom/octMetadata.ts @@ -1,11 +1,7 @@ -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { Tags, type DicomDataset } from '@/packages/dicom/core'; import { dicomDatasetToTags } from '@/src/io/readDicomTags'; import { type OCTDataset, structuredOCTDataset } from './octDataset'; import { areEquals } from '@kitware/vtk.js/Common/Core/Math'; -import { - Tags, - toDicomParserKey, -} from '@/packages/dicom/core/metadata/dicomTags'; import { frameGridGeometry, imageDirection, @@ -24,17 +20,17 @@ const finiteVector = ( value?.length === length && value.every(Number.isFinite); const positiveNumber = (value: number) => Number.isFinite(value) && value > 0; -const SHARED = 'x52009229'; -const PER_FRAME = 'x52009230'; -const MEASURES = 'x00289110'; -const ORIENTATION = 'x00209116'; -const POSITION = 'x00209113'; -const SCAN_PATTERN = 'x00221618'; -const ACQUISITION_PARAMETERS = 'x00221640'; -const PIXEL_SPACING = toDicomParserKey(Tags.PixelSpacing); -const SLICE_SPACING = toDicomParserKey(Tags.SpacingBetweenSlices); -const IMAGE_ORIENTATION = toDicomParserKey(Tags.ImageOrientationPatient); -const IMAGE_POSITION = toDicomParserKey(Tags.ImagePositionPatient); +const SHARED = '52009229'; +const PER_FRAME = '52009230'; +const MEASURES = '00289110'; +const ORIENTATION = '00209116'; +const POSITION = '00209113'; +const SCAN_PATTERN = '00221618'; +const ACQUISITION_PARAMETERS = '00221640'; +const PIXEL_SPACING = Tags.PixelSpacing; +const SLICE_SPACING = Tags.SpacingBetweenSlices; +const IMAGE_ORIENTATION = Tags.ImageOrientationPatient; +const IMAGE_POSITION = Tags.ImagePositionPatient; const firstItem = (data: OCTDataset | undefined, tag: string) => data?.items(tag)[0]; const sequenceItems = (data: OCTDataset, tag: string) => data.items(tag); @@ -64,7 +60,7 @@ function frameGeometry(data: OCTDataset) { return { frames, declaredFrames: Number.parseInt( - stringValue(data, toDicomParserKey(Tags.NumberOfFrames)) ?? '', + stringValue(data, Tags.NumberOfFrames) ?? '', 10 ), orientation: attribute(ORIENTATION, IMAGE_ORIENTATION), @@ -148,7 +144,7 @@ function scanPattern(data: OCTDataset) { const acquisitions = sequenceItems(data, ACQUISITION_PARAMETERS); const patterns = [data, ...acquisitions].flatMap((dataset) => sequenceItems(dataset, SCAN_PATTERN).flatMap( - (item) => stringValue(item, 'x00080100') ?? [] + (item) => stringValue(item, '00080100') ?? [] ) ); return acquisitions.length > 1 || new Set(patterns).size > 1 @@ -164,7 +160,7 @@ function promoteOCTGeometry(data: OCTDataset, tags: Map) { set(Tags.PixelSpacing, geometry.spacing); set( Tags.OphthalmicVolumetricPropertiesFlag, - stringValue(data, toDicomParserKey(Tags.OphthalmicVolumetricPropertiesFlag)) + stringValue(data, Tags.OphthalmicVolumetricPropertiesFlag) ); set(OCT_SCAN_PATTERN, scanPattern(data)); const reason = geometryError(geometry); diff --git a/src/core/streaming/dicom/octMetadataTags.ts b/src/core/streaming/dicom/octMetadataTags.ts index fe093f624..1977be7a2 100644 --- a/src/core/streaming/dicom/octMetadataTags.ts +++ b/src/core/streaming/dicom/octMetadataTags.ts @@ -1,5 +1,4 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; +import { Tags, trimDicomPadding } from '@/packages/dicom/core'; export const OPHTHALMIC_TOMOGRAPHY_SOP = '1.2.840.10008.5.1.4.1.1.77.1.5.4'; export const OPHTHALMIC_BSCAN_ANALYSIS_SOP = '1.2.840.10008.5.1.4.1.1.77.1.5.8'; diff --git a/src/core/streaming/dicom/seriesGeometry.ts b/src/core/streaming/dicom/seriesGeometry.ts index e061510fc..2af97e30d 100644 --- a/src/core/streaming/dicom/seriesGeometry.ts +++ b/src/core/streaming/dicom/seriesGeometry.ts @@ -1,5 +1,5 @@ import { areEquals } from '@kitware/vtk.js/Common/Core/Math'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { frameGridGeometry, imageDirection, diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 9d7b5b070..17c0a8e0a 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -2,27 +2,24 @@ import { computed } from 'vue'; import mitt from 'mitt'; import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import type { JsonCompatible } from '@itk-wasm/image-io'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; -import { getDatasetModality } from '@/packages/dicom/core/metadata/datasetAccess'; -import type { Volume } from '@/packages/dicom/core/volume/allocateVolume'; import { + getDatasetModality, loadVolume, middleSlot, + readBytes, + type DicomRuntime, type Extent, + type Instance, + type Volume, type VolumeUpdate, -} from '@/packages/dicom/core/volume/loadVolume'; -import type { DicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { abortError } from '@/packages/dicom/core/utils/abort'; +} from '@/packages/dicom/core'; import { applyVolumeUpdate, + encodeThumbnailToUri, sliceThumbnail, toVtkImageData, -} from '@/packages/dicom/vtk/volumeImage'; -import { - encodeThumbnailToUri, type ThumbnailSlice, -} from '@/packages/dicom/vtk/thumbnail'; +} from '@/packages/dicom/vtk'; import { BaseProgressiveImage, type ProgressiveImageEvents, @@ -33,7 +30,7 @@ import { } from '@/src/io/dicom'; import { convertItkToVtkImage } from '@/src/io/convertItkToVtkImage'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; -import { ensureError } from '@/src/utils'; +import { abortError, ensureError } from '@/src/utils'; export type DicomVolumeImageEvents = ProgressiveImageEvents & { /** A decoded region of the current image, as an inclusive extent. */ @@ -48,7 +45,7 @@ type SegmentationResult = { export type DicomVolumeImageInit = { runtime?: Pick< DicomRuntime, - 'decode' | 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' + 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' >; readSegmentation?: (file: File) => Promise; encodeThumbnail?: (slice: ThumbnailSlice) => string; @@ -117,7 +114,8 @@ export default class DicomVolumeImage extends BaseProgressiveImage { private thumbnail: Promise | null = null; - private readonly watchers = new Set<() => void>(); + /** Settles the pending thumbnail once its slice is known; null when none is pending. */ + private settleThumbnail: (() => void) | null = null; private readonly events = mitt(); @@ -163,13 +161,13 @@ export default class DicomVolumeImage extends BaseProgressiveImage { this.replaceContent({ kind: 'volume', volume, failed: new Set() }); this.spatialMetadata.value = volume.spatialMetadata; this.replaceImage(toVtkImageData(volume)); - this.notify(); + this.settleThumbnail?.(); } /** A SEG object, which the segmentation reader turns into a labelmap. */ setSegmentation(instances: readonly Instance[]) { this.replaceContent({ kind: 'segmentation', instances, loaded: false }); - this.notify(); + this.settleThumbnail?.(); } startLoad() { @@ -203,10 +201,10 @@ export default class DicomVolumeImage extends BaseProgressiveImage { getThumbnail(): Promise { if (this.disposed) return Promise.reject(abortError('Image disposed')); this.thumbnail ??= new Promise((resolve, reject) => { - const check = () => { + this.settleThumbnail = () => { const slice = this.disposed ? null : this.thumbnailSlice(); if (slice === undefined) return; - this.watchers.delete(check); + this.settleThumbnail = null; if (this.disposed) reject(abortError('Image disposed')); else if (slice === null) resolve(null); else @@ -216,8 +214,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { ) ); }; - this.watchers.add(check); - check(); + this.settleThumbnail(); }); return this.thumbnail; } @@ -241,7 +238,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { this.disposed = true; this.load?.abort(abortError('Image disposed')); this.load = null; - this.notify(); + this.settleThumbnail?.(); this.events.all.clear(); super.dispose(); this.vtkImageData.value.delete(); @@ -250,7 +247,8 @@ export default class DicomVolumeImage extends BaseProgressiveImage { private replaceContent(content: Content) { this.stopLoad(); this.content = content; - this.thumbnail = null; + // A pending thumbnail settles from the new content instead. + if (!this.settleThumbnail) this.thumbnail = null; this.segBuildInfo = null; this.updateStatus(); } @@ -271,7 +269,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { if (this.loading.value === loading) return; this.loading.value = loading; this.events.emit('loading', loading); - this.notify(); + this.settleThumbnail?.(); } private updateStatus() { @@ -281,10 +279,6 @@ export default class DicomVolumeImage extends BaseProgressiveImage { this.events.emit('status', status); } - private notify() { - [...this.watchers].forEach((check) => check()); - } - /** Undefined while the slice to show may still load; null for none. */ private thumbnailSlice() { const { content } = this; @@ -313,7 +307,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { // Consumers read complete together with not loading, as one transition. if (volumeSettled(content)) this.finishLoad(); this.updateStatus(); - this.notify(); + this.settleThumbnail?.(); } private async loadPixels( @@ -356,6 +350,6 @@ export default class DicomVolumeImage extends BaseProgressiveImage { content.loaded = true; this.finishLoad(); this.updateStatus(); - this.notify(); + this.settleThumbnail?.(); } } diff --git a/src/core/streaming/httpCodes.ts b/src/core/streaming/httpCodes.ts new file mode 100644 index 000000000..4a70c9eae --- /dev/null +++ b/src/core/streaming/httpCodes.ts @@ -0,0 +1,9 @@ +export const HTTP_STATUS_OK = 200; +export const HTTP_STATUS_PARTIAL_CONTENT = 206; +export const HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416; + +export class HttpNotFound extends Error { + constructor(url: string) { + super(`The following resource could not be found: ${url}`); + } +} diff --git a/packages/dicom/core/streaming/types.ts b/src/core/streaming/types.ts similarity index 100% rename from packages/dicom/core/streaming/types.ts rename to src/core/streaming/types.ts diff --git a/src/enface/__tests__/availability.spec.ts b/src/enface/__tests__/availability.spec.ts index 1c1457b16..f716c3152 100644 --- a/src/enface/__tests__/availability.spec.ts +++ b/src/enface/__tests__/availability.spec.ts @@ -9,7 +9,7 @@ import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { setDicomTag } from './dicomMetadataFixture'; describe('OCT view availability', () => { diff --git a/src/enface/__tests__/calibration.spec.ts b/src/enface/__tests__/calibration.spec.ts index 3cce02aff..f6fb63619 100644 --- a/src/enface/__tests__/calibration.spec.ts +++ b/src/enface/__tests__/calibration.spec.ts @@ -1,9 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { toVtkImageData } from '@/packages/dicom/vtk/volumeImage'; +import { Tags } from '@/packages/dicom/core'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +import { toVtkImageData } from '@/packages/dicom/vtk'; import { volumeOf } from '@/tests/unit/octFixture'; -import { datasetFromTags } from '@/tests/dicomDataset'; import { OPHTHALMIC_TOMOGRAPHY_SOP } from '@/src/core/streaming/dicom/octMetadataTags'; import { measureOccupiedDepth } from '@/src/segmentation/measurements/occupiedDepth'; diff --git a/src/enface/__tests__/dicomMetadataFixture.ts b/src/enface/__tests__/dicomMetadataFixture.ts index e4307aee2..74e4a8673 100644 --- a/src/enface/__tests__/dicomMetadataFixture.ts +++ b/src/enface/__tests__/dicomMetadataFixture.ts @@ -1,4 +1,4 @@ -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import type { DicomDataset } from '@/packages/dicom/core'; import { datasetFromTags } from '@/tests/dicomDataset'; const keyOf = (tag: string) => tag.replace('|', '').toUpperCase(); diff --git a/src/enface/__tests__/inputCalibration.spec.ts b/src/enface/__tests__/inputCalibration.spec.ts index 31a00e94a..d008c5f1a 100644 --- a/src/enface/__tests__/inputCalibration.spec.ts +++ b/src/enface/__tests__/inputCalibration.spec.ts @@ -3,7 +3,7 @@ import { mount } from '@vue/test-utils'; import { createPinia, setActivePinia } from 'pinia'; import { computed, defineComponent, h, markRaw, nextTick, ref } from 'vue'; import { createVuetify } from 'vuetify'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { CurrentImageInjectionKey } from '@/src/composables/useCurrentImage'; import { untilLoaded } from '@/src/composables/untilLoaded'; import { useImageCacheStore } from '@/src/store/image-cache'; diff --git a/src/enface/__tests__/occupiedDepthSupport.spec.ts b/src/enface/__tests__/occupiedDepthSupport.spec.ts index a1ce1333d..28317aba8 100644 --- a/src/enface/__tests__/occupiedDepthSupport.spec.ts +++ b/src/enface/__tests__/occupiedDepthSupport.spec.ts @@ -6,7 +6,7 @@ import { getOccupiedDepthSupport } from '@/src/enface/occupiedDepthSupport'; import { createOCTFixture, volumeOf } from '@/tests/unit/octFixture'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { removeDicomTag, setDicomTag } from './dicomMetadataFixture'; describe('occupied-depth support for loaded volumes', () => { @@ -36,24 +36,24 @@ describe('occupied-depth support for loaded volumes', () => { pendingReads.push(fixture.releaseDecode); fixture.image.setVolume(volumeOf([fixture.instance])); const id = useImageCacheStore().addProgressiveImage(fixture.image); - const chunks = vi.spyOn(fixture.image, 'getInstances'); + const getInstances = vi.spyOn(fixture.image, 'getInstances'); expect(getOccupiedDepthSupport(id).calibratedAxes).toBeUndefined(); - expect(chunks).not.toHaveBeenCalled(); + expect(getInstances).not.toHaveBeenCalled(); fixture.releaseDecode(); await untilLoaded(id); - chunks.mockClear(); + getInstances.mockClear(); const initial = getOccupiedDepthSupport(id); const repeated = getOccupiedDepthSupport(id); expect(initial.reason).toBeNull(); expect(repeated).toEqual(initial); - expect(chunks).toHaveBeenCalledTimes(1); + expect(getInstances).toHaveBeenCalledTimes(1); fixture.image.getVtkImageData().setSpacing([1, 1, 1]); expect(getOccupiedDepthSupport(id).calibratedAxes).toEqual([ false, false, false, ]); - expect(chunks).toHaveBeenCalledTimes(2); + expect(getInstances).toHaveBeenCalledTimes(2); }); it.each([ diff --git a/src/enface/__tests__/seriesGeometry.spec.ts b/src/enface/__tests__/seriesGeometry.spec.ts index dfc658b78..9bd5b0ad2 100644 --- a/src/enface/__tests__/seriesGeometry.spec.ts +++ b/src/enface/__tests__/seriesGeometry.spec.ts @@ -1,7 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags, type Instance } from '@/packages/dicom/core'; import { useImageCacheStore } from '@/src/store/image-cache'; import { untilLoaded } from '@/src/composables/untilLoaded'; import { @@ -32,10 +31,10 @@ describe('assembled OCT series through real header and file collaborators', () = async function assemble( positions = [0, 0.2, 0.4], - change?: (chunks: Instance[]) => void, + change?: (instances: Instance[]) => void, modality = 'OPT' ) { - const chunks = await Promise.all( + const instances = await Promise.all( positions.map((z, index) => { const bytes = buildSyntheticDicom({ studyUid: '1.2.3.1', @@ -57,14 +56,14 @@ describe('assembled OCT series through real header and file collaborators', () = return readFixtureInstance(file); }) ); - change?.(chunks); + change?.(instances); // Exercise the source geometry guards on one candidate volume, including // intentionally incompatible instances that collection planning would split. const { image } = await createOCTFixture(); - image.setVolume(volumeOf(chunks)); + image.setVolume(volumeOf(instances)); const id = useImageCacheStore().addProgressiveImage(image); await untilLoaded(id); - return { id, image, chunks }; + return { id, image, instances }; } it('derives slow spacing from complete uniform positions when optional spacing is absent', async () => { @@ -129,9 +128,9 @@ describe('assembled OCT series through real header and file collaborators', () = }); it('uses uniform file positions when optional slice spacing disagrees', async () => { - const { id, image } = await assemble(undefined, (chunks) => { - chunks.forEach((chunk) => - setDicomTag(chunk.dataset, Tags.SpacingBetweenSlices, '0.3') + const { id, image } = await assemble(undefined, (instances) => { + instances.forEach((instance) => + setDicomTag(instance.dataset, Tags.SpacingBetweenSlices, '0.3') ); }); expect(image.getVtkImageData().getSpacing()[2]).toBeCloseTo(0.2, 7); @@ -139,10 +138,10 @@ describe('assembled OCT series through real header and file collaborators', () = }); it('accepts orthogonal direction cosines rounded to four decimals', async () => { - const { id } = await assemble(undefined, (chunks) => { - chunks.forEach((chunk) => + const { id } = await assemble(undefined, (instances) => { + instances.forEach((instance) => setDicomTag( - chunk.dataset, + instance.dataset, Tags.ImageOrientationPatient, '0.9986\\0.0523\\0\\-0.0523\\0.9986\\0' ) @@ -152,9 +151,9 @@ describe('assembled OCT series through real header and file collaborators', () = }); it('does not calibrate in-plane axes when every file omits pixel spacing', async () => { - const { id } = await assemble(undefined, (chunks) => { - chunks.forEach((chunk) => { - removeDicomTag(chunk.dataset, Tags.PixelSpacing); + const { id } = await assemble(undefined, (instances) => { + instances.forEach((instance) => { + removeDicomTag(instance.dataset, Tags.PixelSpacing); }); }); expect(getOccupiedDepthSupport(id).calibratedAxes).toEqual([ @@ -170,16 +169,16 @@ describe('assembled OCT series through real header and file collaborators', () = ])( 'keeps a nonuniform series projection-only: $positions', async ({ positions, displayedSpacing }) => { - const { id, image, chunks } = await assemble(positions); + const { id, image, instances } = await assemble(positions); expect(image.getVtkImageData().getSpacing()[2]).toBeCloseTo( displayedSpacing, 7 ); expect(getEnFaceUnavailableReason(id)).toBeNull(); expect(getOccupiedDepthSupport(id).reason).toMatch(/nonuniform/); - expect(dicomSeriesGeometry(chunks.map(displayMetadata)).reason).toMatch( - /nonuniform/ - ); + expect( + dicomSeriesGeometry(instances.map(displayMetadata)).reason + ).toMatch(/nonuniform/); } ); @@ -191,8 +190,8 @@ describe('assembled OCT series through real header and file collaborators', () = ] as const)( 'rejects an unsupported later structured acquisition: %s', async (kind, reason) => { - const { id } = await assemble(undefined, (chunks) => { - const metadata = chunks[2].dataset; + const { id } = await assemble(undefined, (instances) => { + const metadata = instances[2].dataset; if (kind === 'nonvolumetric') setDicomTag(metadata, Tags.OphthalmicVolumetricPropertiesFlag, 'NO'); else if (kind === 'radial') @@ -221,42 +220,42 @@ describe('assembled OCT series through real header and file collaborators', () = ])( 'keeps inconsistent %s geometry projection-only', async (tag, value, reason) => { - const { id, chunks } = await assemble(undefined, (pending) => + const { id, instances } = await assemble(undefined, (pending) => setDicomTag(pending[2].dataset, tag, value) ); expect(getEnFaceUnavailableReason(id)).toBeNull(); expect(getOccupiedDepthSupport(id).reason).toMatch(reason); - expect(dicomSeriesGeometry(chunks.map(displayMetadata)).reason).toMatch( - reason - ); + expect( + dicomSeriesGeometry(instances.map(displayMetadata)).reason + ).toMatch(reason); } ); it.each([false, true])( 'requires complete positions for occupied-depth measurements: allMissing=%s', async (allMissing) => { - const { id, chunks } = await assemble(undefined, (pending) => { + const { id, instances } = await assemble(undefined, (pending) => { const selected = allMissing ? pending : [pending[1]]; - selected.forEach((chunk) => { - removeDicomTag(chunk.dataset, Tags.ImagePositionPatient); + selected.forEach((instance) => { + removeDicomTag(instance.dataset, Tags.ImagePositionPatient); }); }); expect(getEnFaceUnavailableReason(id)).toBeNull(); expect(getOccupiedDepthSupport(id).reason).toMatch(/incomplete/); - expect(dicomSeriesGeometry(chunks.map(displayMetadata)).reason).toMatch( - /incomplete/ - ); + expect( + dicomSeriesGeometry(instances.map(displayMetadata)).reason + ).toMatch(/incomplete/); } ); it('keeps an altered loaded grid projection-only', async () => { - const { id, image, chunks } = await assemble(); + const { id, image, instances } = await assemble(); const data = image.getVtkImageData(); data.setSpacing([0.02, 0.0104, 1]); expect(getEnFaceUnavailableReason(id)).toBeNull(); expect(getOccupiedDepthSupport(id).reason).toMatch(/loaded.*grid/); expect( - dicomSeriesGeometry(chunks.map(displayMetadata), { + dicomSeriesGeometry(instances.map(displayMetadata), { spacing: data.getSpacing(), direction: data.getDirection(), origin: data.getOrigin(), diff --git a/src/enface/availability.ts b/src/enface/availability.ts index 030963747..9ecbc624f 100644 --- a/src/enface/availability.ts +++ b/src/enface/availability.ts @@ -4,7 +4,7 @@ import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; import type { ProgressiveImage } from '@/src/core/progressiveImage'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { OCT_GEOMETRY_ERROR, OCT_SCAN_PATTERN, diff --git a/src/enface/occupiedDepthSupport.ts b/src/enface/occupiedDepthSupport.ts index d8056285b..b1a246e30 100644 --- a/src/enface/occupiedDepthSupport.ts +++ b/src/enface/occupiedDepthSupport.ts @@ -3,10 +3,8 @@ import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags, unitToMm, type Instance } from '@/packages/dicom/core'; import { dicomSeriesGeometry } from '@/src/core/streaming/dicom/seriesGeometry'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { unitToMm } from '@/packages/dicom/core/streaming/dicom/ultrasoundRegion'; function measurementMetadata(instance: Instance) { const tags = new Map(dicomMetadataForDisplay(instance.dataset)); diff --git a/src/io/__tests__/readDicomTags.differential.spec.ts b/src/io/__tests__/readDicomTags.differential.spec.ts index 27f47e64a..65236cac6 100644 --- a/src/io/__tests__/readDicomTags.differential.spec.ts +++ b/src/io/__tests__/readDicomTags.differential.spec.ts @@ -9,7 +9,8 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { readDicomTagsNode } from '@itk-wasm/dicom'; -import { readDicomTags, tagReaderCorpus } from './readDicomTagsFixtures'; +import { readDicomTags } from './readDicomTagsFixtures'; +import { tagReaderCorpus } from '@/tests/specs/dicomElementFixtures'; let workDir = ''; diff --git a/src/io/__tests__/readDicomTags.spec.ts b/src/io/__tests__/readDicomTags.spec.ts index ddfed9ff6..932d26327 100644 --- a/src/io/__tests__/readDicomTags.spec.ts +++ b/src/io/__tests__/readDicomTags.spec.ts @@ -1,9 +1,7 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { readInstanceFacts } from '@/packages/dicom/core/collections/instanceFacts'; +import { Tags } from '@/packages/dicom/core'; +import { readDicomTags } from './readDicomTagsFixtures'; import { - readDicomTags, buildSlice, CHINESE_NAME_BYTES, CHINESE_NAME_PADDED, @@ -22,7 +20,7 @@ import { LATIN1_NAME_PADDED, UTF8_NAME, UTF8_NAME_BYTES, -} from './readDicomTagsFixtures'; +} from '@/tests/specs/dicomElementFixtures'; import { buildSyntheticCineDicom, rawElement, @@ -374,11 +372,6 @@ describe('readDicomTags specific character set', () => { ); expect(valueOf(tags, Tags.ImagePositionPatient)).toBe('1.5\\-2\\3'); expect(valueOf(tags, Tags.PixelSpacing)).toBe('0.5\\0.75'); - expect(readInstanceFacts(datasetFromTags(tags))).toMatchObject({ - orientation: [1, 0, 0, 0, -1, 0], - position: [1.5, -2, 3], - pixelSpacing: [0.5, 0.75], - }); }); it('decodes each value of a multi valued LO on its own', async () => { diff --git a/src/io/__tests__/readDicomTagsFixtures.ts b/src/io/__tests__/readDicomTagsFixtures.ts index b3129e432..d1a11ce24 100644 --- a/src/io/__tests__/readDicomTagsFixtures.ts +++ b/src/io/__tests__/readDicomTagsFixtures.ts @@ -1,342 +1,5 @@ -import { readDicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { readDicomDataset } from '@/packages/dicom/core'; import { dicomDatasetToTags } from '../readDicomTags'; -import { - attributeTagValue, - buildSyntheticCineDicom, - buildSyntheticDicom, - rawElement, - SyntheticSliceOptions, - undefinedLengthItem, - undefinedLengthSequence, -} from '@/tests/specs/syntheticDicom'; export const readDicomTags = (bytes: Uint8Array) => dicomDatasetToTags(readDicomDataset(bytes)); - -const concat = (...parts: Uint8Array[]) => { - const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); - parts.reduce((offset, part) => { - out.set(part, offset); - return offset + part.length; - }, 0); - return out; -}; - -const bytes = (...values: number[]) => new Uint8Array(values); -const ascii = (text: string) => new TextEncoder().encode(text); - -// ESC $ B designates JIS X 0208, ESC ( B returns to ASCII, as ISO 2022 IR 87 -// requires around every run of ideographic or phonetic characters. -const jisX0208 = (...codes: number[]) => - bytes(0x1b, 0x24, 0x42, ...codes, 0x1b, 0x28, 0x42); - -const JAPANESE_CHARACTER_SET = 'ISO 2022 IR 6\\ISO 2022 IR 87'; - -export const JAPANESE_NAME = 'Yamada^Tarou=山田^太郎=やまだ^たろう'; -export const JAPANESE_NAME_BYTES = concat( - ascii('Yamada^Tarou='), - jisX0208(0x3b, 0x33, 0x45, 0x44), - ascii('^'), - jisX0208(0x42, 0x40, 0x4f, 0x3a), - ascii('='), - jisX0208(0x24, 0x64, 0x24, 0x5e, 0x24, 0x40), - ascii('^'), - jisX0208(0x24, 0x3f, 0x24, 0x6d, 0x24, 0x26) -); - -// ISO 2022 IR 149 carries KS X 1001 in the high half, no escape needed. -export const KOREAN_NAME = 'Hong^Gildong=洪^吉洞=홍^길동'; -export const KOREAN_NAME_BYTES = concat( - ascii('Hong^Gildong='), - bytes(0xfb, 0xf3), - ascii('^'), - bytes(0xd1, 0xce, 0xd4, 0xd7), - ascii('='), - bytes(0xc8, 0xab), - ascii('^'), - bytes(0xb1, 0xe6, 0xb5, 0xbf) -); - -// GB 2312 in the high half. Odd length, so DICOM pads it with a space. -export const CHINESE_NAME_PADDED = '王^小明 '; -export const CHINESE_NAME_BYTES = concat( - bytes(0xcd, 0xf5), - ascii('^'), - bytes(0xd0, 0xa1, 0xc3, 0xf7) -); - -// 0x81 0x39 0xee 0x39 is a four-byte GB18030 code no two-byte charset reaches. -export const GB18030_NAME_PADDED = '王^㐀 '; -export const GB18030_NAME_BYTES = concat( - bytes(0xcd, 0xf5), - ascii('^'), - bytes(0x81, 0x39, 0xee, 0x39) -); - -export const UTF8_NAME = 'Wang^Xiaoming=王^小明'; -export const UTF8_NAME_BYTES = ascii(UTF8_NAME); - -export const LATIN1_NAME_PADDED = 'Bäcker^Jörg '; -export const LATIN1_NAME_BYTES = bytes( - 0x42, - 0xe4, - 0x63, - 0x6b, - 0x65, - 0x72, - 0x5e, - 0x4a, - 0xf6, - 0x72, - 0x67 -); - -const doubles = (...values: number[]) => { - const out = new Uint8Array(values.length * 8); - const view = new DataView(out.buffer); - values.forEach((value, i) => view.setFloat64(i * 8, value, true)); - return out; -}; - -const floats = (...values: number[]) => { - const out = new Uint8Array(values.length * 4); - const view = new DataView(out.buffer); - values.forEach((value, i) => view.setFloat32(i * 4, value, true)); - return out; -}; - -/** - * Elements the named writers cannot emit: a binary buffer VR, an attribute tag, - * binary floats, and the private elements every clinical vendor writes. Tags - * sort after (0028,1053) so the data set stays ascending. - */ -export const KATAKANA_NAME = 'アイウ^エオ'; -export const KATAKANA_NAME_BYTES = bytes(0xb1, 0xb2, 0xb3, 0x5e, 0xb4, 0xb5); - -// Half width katakana and JIS X 0208 runs in one value, which ISO 2022 allows -// and no single decoder covers. GDCM stopped at the first escape here, so this -// fixture stays out of the differential corpus. -export const MIXED_JIS_NAME = 'ヤマダ^タロウ=山田^太郎'; -export const MIXED_JIS_NAME_BYTES = concat( - bytes(0xd4, 0xcf, 0xc0, 0xde), - ascii('^'), - bytes(0xc0, 0xdb, 0xb3), - ascii('='), - jisX0208(0x3b, 0x33, 0x45, 0x44), - ascii('^'), - jisX0208(0x42, 0x40, 0x4f, 0x3a) -); - -export const MIXED_VR_ELEMENTS = [ - // (0028,2000) ICC Profile, OB. - rawElement(0x0028, 0x2000, 'OB', new Uint8Array(8).fill(0x7f)), - // (0028,9445) is FL in the dictionary; written UN, as a vendor would. - rawElement(0x0028, 0x9445, 'UN', bytes(0x01, 0x02, 0x03, 0x04)), - // Odd groups, which every clinical vendor writes and GDCM never reported. - rawElement(0x0029, 0x0010, 'LO', ascii('SIEMENS CSA HEADER ')), - rawElement(0x0029, 0x1010, 'OB', new Uint8Array(6).fill(0x41)), - rawElement(0x0029, 0x1020, 'UN', new Uint8Array(4).fill(0x02)), - rawElement(0x0009, 0x1001, 'SH', ascii('GEPRIV ')), - // (0018,9087) Diffusion b-value FD, (0018,9089) gradient orientation FD x 3. - rawElement(0x0018, 0x9087, 'FD', doubles(1234567)), - rawElement(0x0018, 0x9089, 'FD', doubles(3, 0.000012345678, -0.1 - 0.2)), - // (0028,9459) LUT Frame Range, FL. - rawElement(0x0028, 0x9459, 'FL', floats(-2.5, 1e-30)), - // (0028,0009) Frame Increment Pointer, AT, single and multi valued. - rawElement(0x0028, 0x0009, 'AT', attributeTagValue(0x0018, 0x10ab)), - rawElement( - 0x0028, - 0x000a, - 'AT', - concat(attributeTagValue(0x0018, 0x1063), attributeTagValue(0x0028, 0x00ff)) - ), -]; - -/** Fixed UIDs, so a fixture's tag values are the same on every run. */ -export const sliceOptions = ( - overrides: Partial = {} -): SyntheticSliceOptions => ({ - studyUid: '1.2.826.0.1.3680043.10.999.1', - seriesUid: '1.2.826.0.1.3680043.10.999.2', - sopUid: '1.2.826.0.1.3680043.10.999.3', - instanceNumber: 1, - imageOrientationPatient: [1, 0, 0, 0, 1, 0], - imagePositionPatient: [0, 0, 0], - ...overrides, -}); - -export const buildSlice = (overrides: Partial = {}) => - buildSyntheticDicom(sliceOptions(overrides)); - -/** - * Every shape `tests/specs/syntheticDicom.ts` can emit, one entry per encoding - * or value-formatting concern the tag reader has to get right. `itkDivergence` - * names the tags where the itk-wasm reader is known to depart from the - * standard, with the value this reader returns instead. - */ -export const tagReaderCorpus = (): Array<{ - name: string; - bytes: Uint8Array; - itkDivergence?: Record; -}> => [ - { name: 'explicit VR little endian', bytes: buildSlice() }, - { - name: 'implicit VR little endian', - bytes: buildSlice({ implicitVr: true }), - }, - { - name: '8 bit pixels', - bytes: buildSlice({ - bitsAllocated: 8, - bitsStored: 8, - highBit: 7, - rows: 3, - cols: 5, - pixelValue: 3, - }), - }, - { - name: 'signed pixels', - bytes: buildSlice({ pixelRepresentation: 1, pixelValue: 0xfff0 }), - }, - { - name: 'rescale, slice spacing and a CT modality', - bytes: buildSlice({ - modality: 'CT', - rescaleSlope: 2.5, - rescaleIntercept: -1024, - spacingBetweenSlices: 1.5, - sliceThickness: 2, - }), - }, - { - name: 'fractional and negative geometry', - bytes: buildSlice({ - imageOrientationPatient: [1, 0, 0, 0, -1, 0], - imagePositionPatient: [1.5, -2, 3], - pixelSpacing: [0.5, 0.75], - }), - }, - { - name: 'odd length UIDs and a person name', - bytes: buildSlice({ - studyUid: '1.2.3', - seriesUid: '1.2.4', - sopUid: '1.2.5', - patientName: 'DOE^JOHN', - }), - }, - { - name: 'zero length patient name', - bytes: buildSlice({ patientNameBytes: new Uint8Array(0) }), - }, - { - name: 'ultrasound region sequence', - bytes: buildSlice({ - ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, - }), - }, - { - name: 'implicit VR ultrasound region sequence', - bytes: buildSlice({ - implicitVr: true, - ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, - }), - }, - { - name: 'ISO 2022 IR 87 japanese name', - bytes: buildSlice({ - specificCharacterSet: JAPANESE_CHARACTER_SET, - patientNameBytes: JAPANESE_NAME_BYTES, - }), - }, - { - // A sequence item may declare a character set of its own, which every - // Japanese and Korean study writes as a default plus an extension. - name: 'ISO 2022 IR 87 japanese name with a sequence item character set', - bytes: buildSlice({ - specificCharacterSet: JAPANESE_CHARACTER_SET, - patientNameBytes: JAPANESE_NAME_BYTES, - extraElements: [ - undefinedLengthSequence( - 0x0040, - 0x0275, - undefinedLengthItem( - concat( - rawElement(0x0008, 0x0005, 'CS', ascii(JAPANESE_CHARACTER_SET)), - rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES) - ) - ) - ), - ], - }), - }, - { - name: 'ISO 2022 IR 149 korean name', - bytes: buildSlice({ - specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 149', - patientNameBytes: KOREAN_NAME_BYTES, - }), - }, - { - name: 'ISO 2022 IR 58 chinese name', - bytes: buildSlice({ - specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 58', - patientNameBytes: CHINESE_NAME_BYTES, - }), - }, - { - name: 'GB18030 chinese name', - bytes: buildSlice({ - specificCharacterSet: 'GB18030', - patientNameBytes: GB18030_NAME_BYTES, - }), - }, - { - name: 'ISO_IR 192 utf-8 name', - bytes: buildSlice({ - specificCharacterSet: 'ISO_IR 192', - patientNameBytes: UTF8_NAME_BYTES, - }), - }, - { - name: 'ISO_IR 100 latin-1 name', - bytes: buildSlice({ - specificCharacterSet: 'ISO_IR 100', - patientNameBytes: LATIN1_NAME_BYTES, - }), - }, - { - name: 'binary, attribute tag, float and private elements', - bytes: buildSlice({ extraElements: MIXED_VR_ELEMENTS }), - }, - { - name: 'implicit VR binary, attribute tag, float and private elements', - bytes: buildSlice({ implicitVr: true, extraElements: MIXED_VR_ELEMENTS }), - }, - { - name: 'ISO 2022 IR 13 half width katakana name', - bytes: buildSlice({ - specificCharacterSet: 'ISO 2022 IR 13\\ISO 2022 IR 87', - patientNameBytes: KATAKANA_NAME_BYTES, - }), - // GDCM converted every string VR under the declared character set, so its - // CS and DS values carry the JIS X 0201 yen sign where the file wrote the - // 0x5c value delimiter. PS3.5 6.1.2 limits that conversion to SH, LO, ST, - // PN, LT, UC and UT, and the delimiter is never part of a value. - itkDivergence: { - '0008|0005': 'ISO 2022 IR 13\\ISO 2022 IR 87 ', - '0020|0032': '0\\0\\0 ', - '0020|0037': '1\\0\\0\\0\\1\\0 ', - '0028|0030': '1\\1 ', - }, - }, - { - name: 'multi frame cine', - bytes: buildSyntheticCineDicom({ - studyUid: '1.2.826.0.1.3680043.10.999.4', - seriesUid: '1.2.826.0.1.3680043.10.999.5', - sopUid: '1.2.826.0.1.3680043.10.999.6', - }), - }, -]; diff --git a/src/io/import/__tests__/dataSource.spec.ts b/src/io/import/__tests__/dataSource.spec.ts index 1e5af3345..936c1b8c9 100644 --- a/src/io/import/__tests__/dataSource.spec.ts +++ b/src/io/import/__tests__/dataSource.spec.ts @@ -3,7 +3,7 @@ import { getDataSourceName, isRemoteDataSource, } from '@/src/io/import/dataSource'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import type { Instance } from '@/packages/dicom/core'; describe('isRemoteDatasource', () => { it('should work', () => { diff --git a/src/io/import/__tests__/dicomImportResults.spec.ts b/src/io/import/__tests__/dicomImportResults.spec.ts index 0aefff14c..9efe8af31 100644 --- a/src/io/import/__tests__/dicomImportResults.spec.ts +++ b/src/io/import/__tests__/dicomImportResults.spec.ts @@ -5,7 +5,7 @@ import { importDicomInstanceSources, PartialDicomImportError, } from '@/src/io/import/importDataSources'; -import { PartialImportError, useDICOMStore } from '@/src/store/datasets-dicom'; +import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useDatasetStore } from '@/src/store/datasets'; import type { DicomInstanceSource, @@ -27,91 +27,32 @@ const source = ( stateFileLeaf: { stateID }, }); -const deferred = () => { - let resolve!: () => void; - const promise = new Promise((done) => { - resolve = done; - }); - return { promise, resolve }; -}; - beforeEach(() => setActivePinia(createPinia())); -it('returns a stable order regardless of series commit order', async () => { +it('returns a stable order regardless of series commit order', () => { const sources = [source('a'), source('b')]; - const loadables = await importDicomInstanceSources( - sources, - async (_, { onCommitted }) => { - const result = { volumes: {}, dissolved: [] }; - onCommitted({ ...result, volumes: { b: [sources[1].instance] } }); - onCommitted({ ...result, volumes: { a: [sources[0].instance] } }); - return result; - } - ); + const loadables = importDicomInstanceSources(sources, () => ({ + volumes: { b: [sources[1].instance], a: [sources[0].instance] }, + dissolved: [], + })); expect(loadables.map(({ dataID }) => dataID)).toEqual(['a', 'b']); }); -it.each([false, true])( - 'omits a dissolved volume when an overlapping import overtakes it (failure=%s)', - async (fail) => { - const first = source('first'); - const committed = deferred(); - const finish = deferred(); - const delayed = importDicomInstanceSources( - [first], - async (_, { onCommitted }) => { - const result = { volumes: { old: [first.instance] }, dissolved: [] }; - onCommitted(result); - committed.resolve(); - await finish.promise; - if (fail) - throw new PartialImportError([ - { error: new Error('failed'), instances: [] }, - ]); - return result; - } - ).catch((error: PartialDicomImportError) => error.loadables); - await committed.promise; - await importDicomInstanceSources( - [source('second')], - async (instances, hooks) => { - const result = { volumes: { current: instances }, dissolved: ['old'] }; - hooks.removeDissolved('old'); - hooks.onCommitted(result); - return result; - } - ); - finish.resolve(); - expect(await delayed).toEqual([]); - } -); - -it('maps only leaves supplied by this restore while saving full membership', async () => { +it('maps only leaves supplied by this restore while saving full membership', () => { const previous = source('previous', '1'); - await importDicomInstanceSources( - [previous], - async (instances, { onCommitted }) => { - const result = { volumes: { existing: instances }, dissolved: [] }; - onCommitted(result); - return result; - } - ); + importDicomInstanceSources([previous], (instances) => ({ + volumes: { existing: instances }, + dissolved: [], + })); const current = source('current', '2'); const other = source('other', '1'); - const loadables = await importDicomInstanceSources( - [current, other], - async (_, { onCommitted }) => { - const result = { - volumes: { - existing: [previous.instance, current.instance], - other: [other.instance], - }, - dissolved: [], - }; - onCommitted(result); - return result; - } - ); + const loadables = importDicomInstanceSources([current, other], () => ({ + volumes: { + existing: [previous.instance, current.instance], + other: [other.instance], + }, + dissolved: [], + })); expect(buildStateIDToStoreID(loadables)).toEqual({ 1: 'other', 2: 'existing', @@ -123,16 +64,20 @@ it('maps only leaves supplied by this restore while saving full membership', asy ]); }); -it('preserves the failure of every rejected series and blames its own sources', async () => { +it('preserves the failure of every rejected series and blames its own sources', () => { const first = source('first'); const second = source('second', 'second', '2'); const { createImage } = imageFactory(); - const failure = await importDicomInstanceSources( - [first, second], - (instances, hooks) => - useDICOMStore().importInstances(instances, { ...hooks, createImage }) - ).catch((error: PartialDicomImportError) => error); - expect(failure).toBeInstanceOf(PartialDicomImportError); + const failure = (() => { + try { + importDicomInstanceSources([first, second], (instances, hooks) => + useDICOMStore().importInstances(instances, { ...hooks, createImage }) + ); + return null; + } catch (error) { + return error; + } + })(); if (!(failure instanceof PartialDicomImportError)) throw new Error('Expected failed import'); expect( diff --git a/src/io/import/__tests__/dicomInstanceProvenance.spec.ts b/src/io/import/__tests__/dicomInstanceProvenance.spec.ts index a973e4613..b8769765f 100644 --- a/src/io/import/__tests__/dicomInstanceProvenance.spec.ts +++ b/src/io/import/__tests__/dicomInstanceProvenance.spec.ts @@ -1,10 +1,8 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +import { getDatasetTag, Tags } from '@/packages/dicom/core'; import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import type { DicomInstanceSource, @@ -45,32 +43,27 @@ describe('importDicomInstanceSources', () => { setActivePinia(createPinia()); }); - it('inherits a moved member and drops the dissolved dataset', async () => { + it('inherits a moved member and drops the dissolved dataset', () => { const datasetStore = useDatasetStore(); const [a, b, c] = ['sop-a', 'sop-b', 'sop-c'].map(instanceSourceFor); - // Stands in for the store: a dissolved id is removed, then the commit - // is reported, as the store's commit does. + // Stands in for the store: a dissolved id is removed during the commit. const load = ( sources: DicomInstanceSource[], result: ImportInstancesResult ) => - importDicomInstanceSources( - sources, - async (_instances, { onCommitted, removeDissolved }) => { - result.dissolved.forEach(removeDissolved); - onCommitted(result); - return result; - } - ); + importDicomInstanceSources(sources, (_instances, { removeDissolved }) => { + result.dissolved.forEach(removeDissolved); + return result; + }); - await load([a, b], { + load([a, b], { volumes: { 'vol-1': [a.instance], 'vol-2': [b.instance] }, dissolved: [], }); expect(datasetStore.getDataSource('vol-2')).toBeDefined(); - await load([c], { + load([c], { volumes: { 'vol-1': [a.instance, b.instance, c.instance] }, dissolved: ['vol-2'], }); diff --git a/src/io/import/dataSource.ts b/src/io/import/dataSource.ts index 0ae9a9d57..7cc781a57 100644 --- a/src/io/import/dataSource.ts +++ b/src/io/import/dataSource.ts @@ -1,5 +1,5 @@ -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { Fetcher } from '@/packages/dicom/core/streaming/types'; +import type { Instance } from '@/packages/dicom/core'; +import type { Fetcher } from '@/src/core/streaming/types'; import { Maybe } from '@/src/types'; /** diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 9255d156d..9d93deb93 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -42,7 +42,7 @@ import downloadStream from '@/src/io/import/processors/downloadStream'; import { asyncSelect } from '@/src/utils/asyncSelect'; import { evaluateChain, Skip } from '@/src/utils/evaluateChain'; import { ensureError } from '@/src/utils'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import type { Instance } from '@/packages/dicom/core'; import { useDatasetStore } from '@/src/store/datasets'; import { PartialImportError, @@ -168,30 +168,15 @@ export class PartialDicomImportError extends Error { } } -/** - * A committed series becomes datasets here, synchronously with its commit, so - * another import cannot record a membership in between. - */ -const publishImportedInstances = ({ volumes }: ImportInstancesResult) => { - // Every member reports back, so a collection that gained a member from a - // dissolved one carries its provenance too. - const loadables = Object.entries(volumes).map(([id, instances]) => - asLoadableResult( - id, - { type: 'collection', sources: sourcesOf(instances) }, - 'image' - ) - ); - useDatasetStore().addDataSources(loadables); - return loadables; -}; - -/** What the import needs of its caller: where to publish and how to remove. */ +/** What the import needs of its caller: how to remove a dissolved dataset. */ export type ImportInstancesHooks = Required< - Pick + Pick >; -export async function importDicomInstanceSources( +const loadableOf = (id: string, sources: DicomInstanceSource[]) => + asLoadableResult(id, { type: 'collection', sources }, 'image'); + +export function importDicomInstanceSources( sources: DicomInstanceSource[], importInstances = (instances: Instance[], hooks: ImportInstancesHooks) => useDICOMStore().importInstances(instances, hooks) @@ -200,53 +185,47 @@ export async function importDicomInstanceSources( sources.forEach((src) => instanceToDataSource.set(src.instance, src)); - const loadables: LoadableResult[] = []; const supplied = new Set(sources); - const publish = (committed: ImportInstancesResult) => { - const published = publishImportedInstances(committed); - loadables.push( - ...published.map((result) => ({ - ...result, - dataSource: { - type: 'collection' as const, - sources: - result.dataSource.type === 'collection' - ? result.dataSource.sources.filter((source) => - supplied.has(source) - ) - : [], - }, - })) + const datasetStore = useDatasetStore(); + // Every member reports back, so a collection that gained a member from a + // dissolved one saves its provenance too; the result names only this + // import's own sources. + const publish = ({ volumes }: ImportInstancesResult) => { + const entries = Object.entries(volumes); + datasetStore.addDataSources( + entries.map(([id, instances]) => loadableOf(id, sourcesOf(instances))) ); + return entries + .sort(([a], [b]) => (a < b ? -1 : Number(a > b))) + .map(([id, instances]) => + loadableOf( + id, + sourcesOf(instances).filter((source) => supplied.has(source)) + ) + ); }; - // A replan folded the dissolved collection into others, so the dataset an - // earlier import created for it no longer describes anything loaded. The - // dataset store's removal clears every store that names it, in the order - // eviction needs. - const datasetStore = useDatasetStore(); - const removeDissolved = (id: string) => datasetStore.remove(id); - const currentLoadables = () => - loadables - .filter(({ dataID }) => datasetStore.getDataSource(dataID) !== undefined) - .sort((a, b) => (a.dataID < b.dataID ? -1 : Number(a.dataID > b.dataID))); - - await importInstances( - sources.map((src) => src.instance), - { onCommitted: publish, removeDissolved } - ).catch((err) => { + // The dataset store's removal clears every store that names a dissolved + // dataset, in the order eviction needs. + const hooks = { removeDissolved: (id: string) => datasetStore.remove(id) }; + + try { + return publish( + importInstances( + sources.map((src) => src.instance), + hooks + ) + ); + } catch (err) { if (!(err instanceof PartialImportError)) throw err; - // The series that committed published themselves, so they are reported - // beside the failure rather than lost with it. + // The series that committed are reported beside the failure. throw new PartialDicomImportError( - currentLoadables(), + publish(err.committed), err.failures.map(({ error, instances }) => ({ error, sources: sourcesOf(instances), })) ); - }); - - return currentLoadables(); + } } /** @@ -254,11 +233,11 @@ export async function importDicomInstanceSources( * loaded, so their datasets are reported beside a failure rather than lost * with it, and only the sources of the series that failed are blamed for it. */ -async function importDicomResults( +function importDicomResults( sources: DicomInstanceSource[] -): Promise { +): ImportDataSourcesResult[] { try { - return await importDicomInstanceSources(sources); + return importDicomInstanceSources(sources); } catch (err) { const partial = err instanceof PartialDicomImportError ? err : null; const failures = partial?.failures ?? [ @@ -421,7 +400,7 @@ async function importDataSourcesWithPolicy( .map(({ source }) => source) .filter((src): src is DicomInstanceSource => src.type === 'dicom'); - const dicomResults = await importDicomResults(dicomInstanceSources); + const dicomResults = importDicomResults(dicomInstanceSources); results.push(...dicomResults); const loadableResults = results.filter( diff --git a/src/io/import/processors/__tests__/handleDicom.spec.ts b/src/io/import/processors/__tests__/handleDicom.spec.ts index 8a36d7127..08c181076 100644 --- a/src/io/import/processors/__tests__/handleDicom.spec.ts +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -1,13 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; import { + getDatasetTag, + readBytes, readDicomDataset, - withoutPrivateElements, -} from '@/packages/dicom/core/metadata/dicomDataset'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; + Tags, +} from '@/packages/dicom/core'; import type { DataSource } from '@/src/io/import/dataSource'; import { fileToDataSource } from '@/src/io/import/dataSource'; import handleDicom from '@/src/io/import/processors/handleDicom'; @@ -15,12 +14,58 @@ import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { Skip } from '@/src/utils/evaluateChain'; import { useMessageStore } from '@/src/store/messages'; import { stripFileMeta, stripPreamble } from '@/tests/specs/syntheticDicom'; -import { - bytesFetcher, - dicomFile, - syntheticSlice, - withoutPixelData, -} from '@/tests/dicomSourceFixtures'; +import { syntheticSlice, withoutPixelData } from '@/tests/dicomSourceFixtures'; +import { StopSignal } from '@/src/core/streaming/cachedStreamFetcher'; +import type { Fetcher } from '@/src/core/streaming/types'; + +export const dicomFile = (bytes: Uint8Array, name = 'slice.dcm') => + new File([bytes as BlobPart], name, { type: FILE_EXT_TO_MIME.dcm }); + +/** + * A byte source that hands out its bytes a chunk at a time as the reader pulls + * them, so what a loader left undelivered says where it stopped. + */ +export const bytesFetcher = (bytes: Uint8Array, chunkSize = bytes.length) => { + let delivered = 0; + let abortController: AbortController | null = null; + + const fetcher: Fetcher = { + connect: async () => { + abortController ??= new AbortController(); + }, + getStream: () => { + let offset = 0; + return new ReadableStream({ + pull: (controller) => { + if (offset >= bytes.length) { + controller.close(); + return; + } + const chunk = bytes.slice(offset, offset + chunkSize); + offset += chunk.length; + delivered += chunk.length; + controller.enqueue(chunk); + }, + }); + }, + blob: async () => + new Blob([bytes as BlobPart], { type: FILE_EXT_TO_MIME.dcm }), + close: () => { + abortController?.abort(StopSignal); + }, + get connected() { + return !!abortController; + }, + get size() { + return delivered; + }, + contentType: FILE_EXT_TO_MIME.dcm, + get abortSignal() { + return abortController?.signal; + }, + }; + return fetcher; +}; const REGION = { physicalDeltaX: 0.0625, physicalDeltaY: 0.125 }; @@ -49,8 +94,8 @@ const instanceOf = (result: unknown) => { return source; }; -const headerOf = (bytes: Uint8Array) => - withoutPrivateElements(readDicomDataset(bytes)); +// Synthetic slices carry no private elements, so the instance keeps them all. +const headerOf = readDicomDataset; describe('handleDicom', () => { beforeEach(() => { diff --git a/src/io/import/processors/handleDicom.ts b/src/io/import/processors/handleDicom.ts index 34a88948e..c5e86a023 100644 --- a/src/io/import/processors/handleDicom.ts +++ b/src/io/import/processors/handleDicom.ts @@ -1,4 +1,12 @@ -import { getDatasetModality } from '@/packages/dicom/core/metadata/datasetAccess'; +import { + fromBlob, + fromUrl, + getDatasetModality, + IMPLICIT_VR_LITTLE_ENDIAN, + type DicomLayout, + type DicomRuntime, + type Instance, +} from '@/packages/dicom/core'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; import { Skip } from '@/src/utils/evaluateChain'; import { @@ -10,14 +18,7 @@ import { DataSource, getDataSourceName } from '@/src/io/import/dataSource'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { getErrorDetail } from '@/src/utils'; import { surfaceWarning, useMessageStore } from '@/src/store/messages'; -import { - IMPLICIT_VR_LITTLE_ENDIAN, - type DicomLayout, -} from '@/packages/dicom/core/metadata/dicomLayout'; import { Maybe } from '@/src/types'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import type { DicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { fromBlob, fromUrl } from '@/packages/dicom/core/source/byteSource'; // A folder of files that all depart from Part 10 the same way would raise one // notice per file, so each departure is reported once per session. diff --git a/src/io/import/processors/openUriStream.ts b/src/io/import/processors/openUriStream.ts index f6b6902d2..7732f402f 100644 --- a/src/io/import/processors/openUriStream.ts +++ b/src/io/import/processors/openUriStream.ts @@ -1,5 +1,5 @@ import { Skip } from '@/src/utils/evaluateChain'; -import { CachedStreamFetcher } from '@/packages/dicom/core/streaming/cachedStreamFetcher'; +import { CachedStreamFetcher } from '@/src/core/streaming/cachedStreamFetcher'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; import { ImportHandler, diff --git a/src/io/import/processors/updateUriType.ts b/src/io/import/processors/updateUriType.ts index c45159608..70445ebbd 100644 --- a/src/io/import/processors/updateUriType.ts +++ b/src/io/import/processors/updateUriType.ts @@ -1,5 +1,5 @@ import { Skip } from '@/src/utils/evaluateChain'; -import StreamingByteReader from '@/packages/dicom/core/streaming/streamingByteReader'; +import { StreamingByteReader } from '@/packages/dicom/core'; import { ImportHandler, asIntermediateResult } from '@/src/io/import/common'; import { getFileMimeFromMagicStream } from '@/src/io/magic'; import { getMimeTypeFromFilename } from '@/src/io/io'; diff --git a/src/io/magic.ts b/src/io/magic.ts index 6781ace24..226215474 100644 --- a/src/io/magic.ts +++ b/src/io/magic.ts @@ -1,4 +1,4 @@ -import StreamingByteReader from '@/packages/dicom/core/streaming/streamingByteReader'; +import { StreamingByteReader } from '@/packages/dicom/core'; import { Maybe } from '../types'; interface MagicDatabase { diff --git a/src/io/readDicomTags.ts b/src/io/readDicomTags.ts index 7b02a3dbd..142702e71 100644 --- a/src/io/readDicomTags.ts +++ b/src/io/readDicomTags.ts @@ -1,20 +1,23 @@ -import { binaryString, hex4 } from '@/packages/dicom/core/metadata/dcmjsParser'; -import { VALUE_DELIMITER } from '@/packages/dicom/core/metadata/dicomCharacterSet'; import { - DicomElement, - DicomDataset, isPrivateElement, -} from '@/packages/dicom/core/metadata/dicomDataset'; + type DicomDataset, + type DicomElement, +} from '@/packages/dicom/core'; const SPECIFIC_CHARACTER_SET = '00080005'; +const VALUE_DELIMITER = '\\'; + /** VRs whose values are binary floats rather than text. */ const FLOAT_VRS = new Set(['FD', 'FL', 'OD', 'OF']); /** Significant digits of a C++ `ostream`, which is what GDCM printed with. */ const FLOAT_PRECISION = 6; -const hexTag = (value: number) => hex4(value).toLowerCase(); +const binaryString = (bytes: Uint8Array) => + Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''); + +const hexTag = (value: number) => value.toString(16).padStart(4, '0'); /** An AT value is a packed tag, which GDCM printed as `(gggg,eeee)`. */ const attributeTagText = ({ diff --git a/src/segmentation/__tests__/artifactParentRestore.spec.ts b/src/segmentation/__tests__/artifactParentRestore.spec.ts index e5738dca7..ed4d528d8 100644 --- a/src/segmentation/__tests__/artifactParentRestore.spec.ts +++ b/src/segmentation/__tests__/artifactParentRestore.spec.ts @@ -1,4 +1,4 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; import { nextTick } from 'vue'; @@ -6,17 +6,15 @@ import { flushPromises } from '@vue/test-utils'; import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; import { - emptyRegistry, - registerInstances, -} from '@/packages/dicom/core/collections/instanceRegistry'; -import { allocateVolume } from '@/packages/dicom/core/volume/allocateVolume'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; + allocateVolume, + createDicomRuntime, + fromBlob, + Tags, +} from '@/packages/dicom/core'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import { LoadedVtkImage } from '@/src/core/progressiveImage'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; import { useImageCacheStore } from '@/src/store/image-cache'; import { type LabelmapIO } from '@/src/segmentation/store'; import { useToolStore } from '@/src/store/tools'; @@ -112,8 +110,8 @@ const pendingImage = async (id = 'parent') => { datasetFromTags(meta), fromBlob(new Blob(['pixels'])) ); - const runtime = createDicomRuntime({ - decoder: async () => { + const runtime = createDicomRuntime( + decodingWith(async () => { started.resolve(); await decoded.promise; return { @@ -121,16 +119,12 @@ const pendingImage = async (id = 'parent') => { data: Uint16Array.from({ length: 16 }, (_, index) => index === 5 ? 1 : 0 ), - imageType: { components: 1 }, + components: 1, }; - }, - }); - const allocation = allocateVolume( - registerInstances(emptyRegistry, [instance]).updates[0] + }) ); - if (allocation.kind !== 'volume') throw new Error('Expected a volume'); const image = new DicomVolumeImage({ runtime }); - image.setVolume(allocation.volume); + image.setVolume(allocateVolume(plannedUpdate([instance]))); cache().addProgressiveImage(image, { id }); await started.promise; expect(image.loading.value).toBe(true); diff --git a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts index 1060d371c..b1445ae29 100644 --- a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts +++ b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts @@ -1,8 +1,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags, type Instance } from '@/packages/dicom/core'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { uriToDataSource, type DataSource } from '@/src/io/import/dataSource'; import type { DicomInstanceSource } from '@/src/io/import/dataSource'; @@ -23,11 +22,12 @@ import { // Slices of one acquisition, interleaved with a second acquisition's slices // along the same stretch of the slice axis. -const acquisition = (number: string, zs: number[]) => +const acquisition = (number: string, zs: number[], orientation?: string) => zs.map((z, i) => sliceFor({ sop: `acq${number}-${i}`, z, + orientation, tags: { [Tags.AcquisitionNumber]: number }, }) ); @@ -69,11 +69,11 @@ describe('DICOM store acquisition split across imports', () => { setActivePinia(createPinia()); }); - it('loads one series holding two overlapping passes as two labelled volumes', async () => { + it('loads one series holding two overlapping passes as two labelled volumes', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); - const result = await store.importInstances( + const result = store.importInstances( [...acquisitionOne(), ...acquisitionTwo()], { createImage } ); @@ -88,16 +88,16 @@ describe('DICOM store acquisition split across imports', () => { expect(useMessageStore().messages).toEqual([]); }); - it('splits a series imported one acquisition at a time, keeping the first id', async () => { + it('splits a series imported one acquisition at a time, keeping the first id', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); const first = acquisitionOne(); - const initial = await store.importInstances(first, { createImage }); + const initial = store.importInstances(first, { createImage }); const [firstId] = volumeIds(initial); expect(store.volumeInfo[firstId].splitLabel).toBeUndefined(); - const second = await store.importInstances(acquisitionTwo(), { + const second = store.importInstances(acquisitionTwo(), { createImage, }); @@ -116,14 +116,14 @@ describe('DICOM store acquisition split across imports', () => { expect(created[0].getInstances()).toEqual(first); }); - it('does not duplicate a subset re-imported after the full series', async () => { + it('does not duplicate a subset re-imported after the full series', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); - await store.importInstances([...acquisitionOne(), ...acquisitionTwo()], { + store.importInstances([...acquisitionOne(), ...acquisitionTwo()], { createImage, }); - const again = await store.importInstances(acquisitionOne(), { + const again = store.importInstances(acquisitionOne(), { createImage, }); @@ -134,15 +134,15 @@ describe('DICOM store acquisition split across imports', () => { }); }); - it('keeps an established split when a later slice lacks the discriminator', async () => { + it('keeps an established split when a later slice lacks the discriminator', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); - await store.importInstances([...acquisitionOne(), ...acquisitionTwo()], { + store.importInstances([...acquisitionOne(), ...acquisitionTwo()], { createImage, }); const untagged = sliceFor({ sop: 'untagged', z: 1.5 }); - const result = await store.importInstances([untagged], { createImage }); + const result = store.importInstances([untagged], { createImage }); // The slice no axis can place forms its own volume; the two passes stay. expect(result.dissolved).toEqual([]); @@ -153,7 +153,42 @@ describe('DICOM store acquisition split across imports', () => { ]); }); - it('warns once per volume whose repeated positions no tag separates', async () => { + it('reorients a volume when a sibling pass outvotes its axes', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + // Within the orientation tolerance, so the passes share one set of axes. + const tilted = '1\\0\\0\\0\\0.99995\\0.0099998'; + store.importInstances( + [...acquisition('1', [0, 2]), ...acquisition('2', [1, 3], tilted)], + { createImage } + ); + const [id] = Object.entries(store.volumeInfo).find( + ([, info]) => info.splitLabel === 'acquisition 1' + )!; + const directionOf = () => + Array.from( + useImageCacheStore().imageById[id]!.getVtkImageData().getDirection() + ); + const before = directionOf(); + + store.importInstances( + [ + sliceFor({ + sop: 'acq2-late', + z: 5, + orientation: tilted, + tags: { [Tags.AcquisitionNumber]: '2' }, + }), + ], + { createImage } + ); + + expect(before).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); + expect(directionOf()[4]).toBeCloseTo(0.99995, 6); + expect(directionOf()[5]).toBeCloseTo(0.0099998, 6); + }); + + it('warns once per volume whose repeated positions no tag separates', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); const doubled = () => @@ -165,9 +200,9 @@ describe('DICOM store acquisition split across imports', () => { }) ); - await store.importInstances(doubled(), { createImage }); + store.importInstances(doubled(), { createImage }); // Dropping the same folder again changes nothing worth repeating. - await store.importInstances(doubled(), { createImage }); + store.importInstances(doubled(), { createImage }); const { messages } = useMessageStore(); expect(messages).toHaveLength(1); @@ -177,7 +212,7 @@ describe('DICOM store acquisition split across imports', () => { ); }); - it('tells the user when a later import regroups a dataset away', async () => { + it('tells the user when a later import regroups a dataset away', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); const tagged = (sop: string, z: number, number: string) => @@ -187,8 +222,8 @@ describe('DICOM store acquisition split across imports', () => { const first = [tagged('a', 0, '1'), tagged('b', 2, '2')]; const second = [tagged('c', 2, '1'), tagged('d', 0, '2')]; - const [id] = volumeIds(await store.importInstances(first, { createImage })); - const result = await store.importInstances(second, { createImage }); + const [id] = volumeIds(store.importInstances(first, { createImage })); + const result = store.importInstances(second, { createImage }); expect(result.dissolved).toEqual([id]); const regrouped = useMessageStore().messages.filter((message) => @@ -200,14 +235,14 @@ describe('DICOM store acquisition split across imports', () => { ); }); - it('repartitions saved provenance when a later import splits the series', async () => { + it('repartitions saved provenance when a later import splits the series', () => { const { createImage } = imageFactory(); const datasetStore = useDatasetStore(); const store = useDICOMStore(); const first = acquisitionOne().map(instanceSource); const second = acquisitionTwo().map(instanceSource); - const load = async (sources: DicomInstanceSource[]) => { - const loadables = await importDicomInstanceSources( + const load = (sources: DicomInstanceSource[]) => { + const loadables = importDicomInstanceSources( sources, (instances, hooks) => store.importInstances(instances, { createImage, ...hooks }) @@ -215,8 +250,8 @@ describe('DICOM store acquisition split across imports', () => { return loadables.map(({ dataID }) => dataID); }; - const [firstId] = await load(first); - const ids = await load(second); + const [firstId] = load(first); + const ids = load(second); const secondId = ids.find((id) => id !== firstId)!; // Each dataset saves exactly its own pass, so a restore replans them the diff --git a/src/store/__tests__/datasets-dicom-cine.spec.ts b/src/store/__tests__/datasets-dicom-cine.spec.ts index 294d4b393..c072abb5e 100644 --- a/src/store/__tests__/datasets-dicom-cine.spec.ts +++ b/src/store/__tests__/datasets-dicom-cine.spec.ts @@ -1,54 +1,27 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; +import { Tags, type Instance } from '@/packages/dicom/core'; import { - SOP_CLASS_ULTRASOUND_MULTIFRAME, - SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, - Tags, -} from '@/packages/dicom/core/metadata/dicomTags'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import type { CineParseResult } from '@/src/core/cine/parseCineDicom'; -import { - cineHeader, - cineParseResult, + cineInstance, + TS_JPEG_BASELINE, } from '@/src/core/cine/__tests__/cineFixtures'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; import { useImageCacheStore } from '@/src/store/image-cache'; -import { instanceTags } from '@/src/store/__tests__/dicomTagFixtures'; import { imageFactory } from '@/src/store/__tests__/dicomImportFixtures'; -import { isCineInstance, useDICOMStore } from '@/src/store/datasets-dicom'; - -// Pixel tags let a clip that is not played as cine load as a volume instead. -const PIXEL_TAGS: Array<[string, string]> = [ - [Tags.Rows, '2'], - [Tags.Columns, '2'], - [Tags.SamplesPerPixel, '1'], - [Tags.BitsStored, '8'], - [Tags.PixelRepresentation, '0'], -]; - -function metadata(overrides: Record = {}) { - return [ - ...instanceTags({ - sopClassUid: SOP_CLASS_ULTRASOUND_MULTIFRAME, - numberOfFrames: '2', - sopInstanceUid: 'sop-uid', - modality: 'US', - seriesDescription: 'Unsupported native cine', - }), - ...PIXEL_TAGS, - ].map(([tag, value]) => [tag, overrides[tag] ?? value]) as [string, string][]; -} +import { useDICOMStore } from '@/src/store/datasets-dicom'; -// MONOCHROME1 native pixels are a clip the cine player does not support. -const unsupportedHeader = () => - cineHeader({ photometricInterpretation: 'MONOCHROME1' }); +const SERIES = { + [Tags.SeriesNumber]: '7', + [Tags.SeriesDescription]: 'Unsupported native cine', +}; -const clip = (meta = metadata()): Instance => - instanceFor(datasetFromTags(meta), fromBlob(new Blob([new Uint8Array([2])]))); +// MONOCHROME1 native pixels are a clip the cine player does not support. +const unsupported = () => + cineInstance({ + ...SERIES, + [Tags.PhotometricInterpretation]: 'MONOCHROME1', + }); const onlyId = (volumes: Record) => { const ids = Object.keys(volumes); @@ -56,70 +29,23 @@ const onlyId = (volumes: Record) => { return ids[0]; }; -describe('isCineInstance', () => { - it('accepts a single current ultrasound multi-frame image with more than one frame', () => { - expect(isCineInstance(clip().dataset)).toBe(true); - }); - - it('accepts the retired ultrasound multi-frame SOP class UID', () => { - expect( - isCineInstance( - clip( - metadata({ - [Tags.SOPClassUID]: SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, - }) - ).dataset - ) - ).toBe(true); - }); - - it('rejects non-ultrasound SOP classes', () => { - expect( - isCineInstance( - clip( - metadata({ - [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2', - }) - ).dataset - ) - ).toBe(false); - }); - - it('rejects single-frame images', () => { - expect( - isCineInstance( - clip( - metadata({ - [Tags.NumberOfFrames]: '1', - }) - ).dataset - ) - ).toBe(false); - }); -}); - describe('DICOM store cine routing', () => { beforeEach(() => { setActivePinia(createPinia()); }); - it('falls back to volume import for unsupported parsed cine headers', async () => { + it('imports a clip the cine player does not support as a volume', () => { const { created, createImage } = imageFactory(); - const parseCineDicom = vi.fn(() => cineParseResult(unsupportedHeader())); - const unsupported = clip(); + const clip = unsupported(); const store = useDICOMStore(); - const result = await store.importInstances([unsupported], { - createImage, - parseCineDicom, - }); + const result = store.importInstances([clip], { createImage }); - expect(parseCineDicom).toHaveBeenCalledOnce(); expect(created).toHaveLength(1); - expect(created[0].getInstances()).toEqual([unsupported]); + expect(created[0].getInstances()).toEqual([clip]); const id = onlyId(result.volumes); - expect(result.volumes[id]).toEqual([unsupported]); + expect(result.volumes[id]).toEqual([clip]); expect(useImageCacheStore().imageById[id]).toBe(created[0]); expect(store.volumeInfo[id]).toMatchObject({ NumberOfSlices: 2, @@ -132,58 +58,42 @@ describe('DICOM store cine routing', () => { }); }); - it('falls back to volume import when cine parsing throws', async () => { + it('plays a clip as cine from its header alone, whatever its pixels hold', () => { const { created, createImage } = imageFactory(); - const parseCineDicom = vi.fn((): CineParseResult => { - throw new Error('unsupported encapsulated frame layout'); - }); - const malformed = clip(); + const malformed = cineInstance( + {}, + { transferSyntaxUid: TS_JPEG_BASELINE, pixels: new Uint8Array(8) } + ); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); const store = useDICOMStore(); - const result = await store - .importInstances([malformed], { createImage, parseCineDicom }) - .finally(() => warn.mockRestore()); - - expect(parseCineDicom).toHaveBeenCalledOnce(); - expect(created).toHaveLength(1); - expect(created[0].getInstances()).toEqual([malformed]); + const id = onlyId( + store.importInstances([malformed], { createImage }).volumes + ); - const id = onlyId(result.volumes); - expect(useImageCacheStore().imageById[id]).toBe(created[0]); - expect(store.volumeInfo[id].kind).toBe('volume'); + expect(created).toHaveLength(0); + expect(store.volumeInfo[id].kind).toBe('cine'); + expect(useImageCacheStore().imageById[id]).toBeInstanceOf(DicomCineImage); }); - it('reuses an unsupported cine clip that already loaded as a volume', async () => { + it('reuses an unsupported cine clip that already loaded as a volume', () => { const { created, createImage } = imageFactory(); - const parseCineDicom = () => cineParseResult(unsupportedHeader()); const store = useDICOMStore(); - const first = await store.importInstances([clip()], { - createImage, - parseCineDicom, - }); - const repeated = await store.importInstances([clip()], { - createImage, - parseCineDicom, - }); + const first = store.importInstances([unsupported()], { createImage }); + const repeated = store.importInstances([unsupported()], { createImage }); expect(Object.keys(repeated.volumes)).toEqual(Object.keys(first.volumes)); expect(created).toHaveLength(1); }); - it('refuses to reuse a cached image that is not a DICOM volume', async () => { - const parseCineDicom = vi.fn(() => cineParseResult(unsupportedHeader())); + it('refuses to reuse a cached image that is not a DICOM volume', () => { const normalClip = () => - clip( - metadata({ - [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2', - [Tags.NumberOfFrames]: '1', - }) - ); + cineInstance({ + [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2', + [Tags.NumberOfFrames]: '1', + }); const learner = imageFactory(); - const learned = await useDICOMStore().importInstances([normalClip()], { + const learned = useDICOMStore().importInstances([normalClip()], { createImage: learner.createImage, - parseCineDicom, }); const id = onlyId(learned.volumes); @@ -194,27 +104,21 @@ describe('DICOM store cine routing', () => { {} as (typeof imageCacheStore.imageById)[string]; const { created, createImage } = imageFactory(); - await expect( - useDICOMStore().importInstances([normalClip()], { - createImage, - parseCineDicom, - }) - ).rejects.toThrow(/non-DICOM/); + expect(() => + useDICOMStore().importInstances([normalClip()], { createImage }) + ).toThrow(/non-DICOM/); expect(created).toHaveLength(0); }); }); -it('imports two same-shaped ultrasound clips as separate playable cine volumes', async () => { +it('imports two same-shaped ultrasound clips as separate playable cine volumes', () => { setActivePinia(createPinia()); const clips = ['clip-1', 'clip-2'].map((sop) => - clip(metadata({ [Tags.SOPInstanceUID]: sop })) + cineInstance({ [Tags.SOPInstanceUID]: sop }) ); const { created, createImage } = imageFactory(); const store = useDICOMStore(); - const result = await store.importInstances(clips, { - createImage, - parseCineDicom: () => cineParseResult(cineHeader()), - }); + const result = store.importInstances(clips, { createImage }); expect( Object.values(result.volumes).map((members) => members.length) ).toEqual([1, 1]); diff --git a/src/store/__tests__/datasets-dicom-geometry.spec.ts b/src/store/__tests__/datasets-dicom-geometry.spec.ts index 4963060ce..ebdf64bb4 100644 --- a/src/store/__tests__/datasets-dicom-geometry.spec.ts +++ b/src/store/__tests__/datasets-dicom-geometry.spec.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useMessageStore } from '@/src/store/messages'; import { @@ -36,9 +36,9 @@ const slices = (count: number, options?: Parameters[1]) => describe('planned DICOM geometry in the image cache', () => { beforeEach(() => setActivePinia(createPinia())); - it('builds on the axes most slices declare when the first spatial slice leans off them', async () => { + it('builds on the axes most slices declare when the first spatial slice leans off them', () => { const { created, createImage } = imageFactory(); - const result = await useDICOMStore().importInstances(slices(121), { + const result = useDICOMStore().importInstances(slices(121), { createImage, }); const [image] = created; @@ -51,11 +51,11 @@ describe('planned DICOM geometry in the image cache', () => { image.dispose(); }); - it('warns when a slice leans further off the volume axes than a sample can hide', async () => { + it('warns when a slice leans further off the volume axes than a sample can hide', () => { // Four samples 90mm apart: a 0.001 rad lean moves the far corner 0.36mm. const wide = { stray: leaning(0.001), pixelSpacing: '90\\90' }; const { created, createImage } = imageFactory(); - await useDICOMStore().importInstances(slices(5, wide), { createImage }); + useDICOMStore().importInstances(slices(5, wide), { createImage }); const [image] = created; expect(image.getVtkImageData().getDirection()).toEqual([...AXIAL, 0, 0, 1]); @@ -65,26 +65,26 @@ describe('planned DICOM geometry in the image cache', () => { image.dispose(); }); - it('takes new axes on an incremental import and keeps the old ones when it fails', async () => { + it('takes new axes on an incremental import and keeps the old ones when it fails', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); const first = slice(0); - await store.importInstances([first], { createImage }); + store.importInstances([first], { createImage }); const [image] = created; const direction = () => image.getVtkImageData().getDirection().slice(0, 6); expect(direction()).toEqual(TILTED); const rest = slices(121).slice(1); // A sibling collection of the series cannot be allocated. - await expect( + expect(() => store.importInstances([...rest, unallocatableFor({ sop: 'scout' })], { createImage, }) - ).rejects.toThrow(ALLOCATION_FAILURE); + ).toThrow(ALLOCATION_FAILURE); expect(image.getInstances()).toEqual([first]); expect(direction()).toEqual(TILTED); - await store.importInstances(rest, { createImage }); + store.importInstances(rest, { createImage }); expect(direction()).toEqual(AXIAL); expect(image.getVtkImageData().getSpacing()).toEqual([1, 1, 5]); image.dispose(); diff --git a/src/store/__tests__/datasets-dicom-lifetime.spec.ts b/src/store/__tests__/datasets-dicom-lifetime.spec.ts index 2276589a1..98f82903a 100644 --- a/src/store/__tests__/datasets-dicom-lifetime.spec.ts +++ b/src/store/__tests__/datasets-dicom-lifetime.spec.ts @@ -1,6 +1,6 @@ import { beforeEach, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { hangingSource } from '@/packages/dicom/core/source/__tests__/sourceFixtures'; +import { hangingSource } from '@/tests/byteSourceFixtures'; import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useDatasetStore } from '@/src/store/datasets'; import { useImageCacheStore } from '@/src/store/image-cache'; @@ -14,7 +14,7 @@ beforeEach(() => setActivePinia(createPinia())); it('cancels a pending pixel read when its dataset is removed', async () => { const hanging = hangingSource(); const store = useDICOMStore(); - const { volumes } = await store.importInstances( + const { volumes } = store.importInstances( [sliceFor({ sop: '1.2.3.5', source: hanging.source })], { createImage: imageFactory().createImage } ); diff --git a/src/store/__tests__/datasets-dicom-reimport.spec.ts b/src/store/__tests__/datasets-dicom-reimport.spec.ts index 7fbd12a54..60e3fa785 100644 --- a/src/store/__tests__/datasets-dicom-reimport.spec.ts +++ b/src/store/__tests__/datasets-dicom-reimport.spec.ts @@ -8,7 +8,7 @@ import { type ImportInstancesResult, } from '@/src/store/datasets-dicom'; import { untilLoaded } from '@/src/composables/untilLoaded'; -import { mergingChunks } from '@/tests/dicomOrientationFixtures'; +import { mergingInstances } from '@/tests/dicomOrientationFixtures'; import { ALLOCATION_FAILURE, imageFactory, @@ -47,10 +47,10 @@ describe('DICOM store incremental import', () => { const second = sliceFor({ sop: 'b', z: 1 }); const store = useDICOMStore(); - const firstResult = await store.importInstances([first], { createImage }); + const firstResult = store.importInstances([first], { createImage }); const id = onlyId(firstResult); await untilLoaded(id); - const secondResult = await store.importInstances([second], { + const secondResult = store.importInstances([second], { createImage, }); await untilLoaded(id); @@ -68,11 +68,11 @@ describe('DICOM store incremental import', () => { it('builds the volume in planned order, not arrival order', async () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); - await store.importInstances([sliceFor({ sop: 'b', z: 1 })], { + store.importInstances([sliceFor({ sop: 'b', z: 1 })], { createImage, }); const id = onlyId( - await store.importInstances([sliceFor({ sop: 'a', z: 0 })], { + store.importInstances([sliceFor({ sop: 'a', z: 0 })], { createImage, }) ); @@ -82,44 +82,42 @@ describe('DICOM store incremental import', () => { expect(sliceValues(created[0])).toEqual([1, 2]); }); - it('gives one series the same volume id however it is imported', async () => { - const load = async (batches: string[][]) => { + it('gives one series the same volume id however it is imported', () => { + const load = (batches: string[][]) => { setActivePinia(createPinia()); const { createImage } = imageFactory(); const store = useDICOMStore(); return batches.reduce( - (chain, batch) => - chain.then(() => - store - .importInstances( - batch.map((sop) => sliceFor({ sop, z: sop.charCodeAt(0) })), - { createImage } - ) - .then(onlyId) + (_, batch) => + onlyId( + store.importInstances( + batch.map((sop) => sliceFor({ sop, z: sop.charCodeAt(0) })), + { createImage } + ) ), - Promise.resolve('') + '' ); }; - const oneBatch = await load([['a', 'b', 'c']]); - expect(await load([['a'], ['b', 'c']])).toBe(oneBatch); - expect(await load([['b', 'c'], ['a']])).toBe(oneBatch); + const oneBatch = load([['a', 'b', 'c']]); + expect(load([['a'], ['b', 'c']])).toBe(oneBatch); + expect(load([['b', 'c'], ['a']])).toBe(oneBatch); expect( - await load([ + load([ ['a', 'b', 'c'], ['a', 'b', 'c'], ]) ).toBe(oneBatch); }); - it('keeps one member when the same instance arrives twice', async () => { + it('keeps one member when the same instance arrives twice', () => { const { created, createImage } = imageFactory(); const original = sliceFor({ sop: 'a', z: 0 }); const resupplied = sliceFor({ sop: 'a', z: 0 }); const store = useDICOMStore(); - const first = await store.importInstances([original], { createImage }); - const second = await store.importInstances([resupplied], { createImage }); + const first = store.importInstances([original], { createImage }); + const second = store.importInstances([resupplied], { createImage }); expect(created).toHaveLength(1); expect(created[0].getInstances()).toEqual([original]); @@ -127,27 +125,27 @@ describe('DICOM store incremental import', () => { expect(store.volumeInfo[onlyId(first)].NumberOfSlices).toBe(1); }); - it('counts every member of the volume after a re-import', async () => { + it('counts every member of the volume after a re-import', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); - const first = await store.importInstances([sliceFor({ sop: 'a', z: 0 })], { + const first = store.importInstances([sliceFor({ sop: 'a', z: 0 })], { createImage, }); - await store.importInstances([sliceFor({ sop: 'b', z: 1 })], { + store.importInstances([sliceFor({ sop: 'b', z: 1 })], { createImage, }); expect(store.volumeInfo[onlyId(first)].NumberOfSlices).toBe(2); }); - it('splits incompatible instances of one series into two volumes', async () => { + it('splits incompatible instances of one series into two volumes', () => { const { created, createImage } = imageFactory(); const scout = sliceFor({ sop: 'scout', rows: '8', z: 0 }); const slices = [sliceFor({ sop: 'a', z: 0 }), sliceFor({ sop: 'b', z: 1 })]; const store = useDICOMStore(); - const result = await store.importInstances([scout, ...slices], { + const result = store.importInstances([scout, ...slices], { createImage, }); @@ -165,18 +163,18 @@ describe('DICOM store incremental import', () => { expect(store.studyVolumes[STUDY_UID].sort()).toEqual([...ids].sort()); }); - it('rebuilds a removed series from the instances the re-import brings', async () => { + it('rebuilds a removed series from the instances the re-import brings', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); const original = sliceFor({ sop: 'a', z: 0 }); - const id = onlyId(await store.importInstances([original], { createImage })); + const id = onlyId(store.importInstances([original], { createImage })); useImageCacheStore().removeImage(id); store.deleteVolume(id); const resupplied = sliceFor({ sop: 'a', z: 0 }); const reimported = onlyId( - await store.importInstances([resupplied], { createImage }) + store.importInstances([resupplied], { createImage }) ); expect(reimported).toBe(id); @@ -186,21 +184,21 @@ describe('DICOM store incremental import', () => { expect(created[1].getInstances()[0]).toBe(resupplied); }); - const merging = () => mergingChunks(sliceFor); + const merging = () => mergingInstances(sliceFor); - it('drops the volume a replan dissolved', async () => { + it('drops the volume a replan dissolved', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); const imageCacheStore = useImageCacheStore(); const { between, straight, tilted } = merging(); - const first = await store.importInstances([straight, tilted], { + const first = store.importInstances([straight, tilted], { createImage, }); const ids = Object.keys(first.volumes); expect(ids).toHaveLength(2); - const merged = await store.importInstances([between], { createImage }); + const merged = store.importInstances([between], { createImage }); const survivor = onlyId(merged); const dissolved = ids.find((id) => id !== survivor)!; @@ -214,36 +212,15 @@ describe('DICOM store incremental import', () => { expect(merged.volumes[survivor]).toEqual([straight, tilted, between]); }); - it('does not resurrect a volume a concurrent import dissolved', async () => { - const { createImage } = imageFactory(); - const store = useDICOMStore(); - const imageCacheStore = useImageCacheStore(); - const { between, straight, tilted } = merging(); - - const [first, second] = await Promise.all([ - store.importInstances([straight, tilted], { createImage }), - store.importInstances([between], { createImage }), - ]); - const survivor = onlyId(second); - - Object.keys(first.volumes) - .filter((id) => id !== survivor) - .forEach((id) => { - expect(imageCacheStore.imageById[id]).toBeUndefined(); - expect(store.volumeInfo[id]).toBeUndefined(); - }); - expect(store.volumeInfo[survivor].NumberOfSlices).toBe(3); - }); - - it('lets a corrected re-import replace the instance a failed import brought', async () => { + it('lets a corrected re-import replace the instance a failed import brought', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); - await expect( + expect(() => store.importInstances([unallocatableFor({ sop: 'a' })], { createImage }) - ).rejects.toThrow(ALLOCATION_FAILURE); + ).toThrow(ALLOCATION_FAILURE); const corrected = sliceFor({ sop: 'a', rows: '8' }); - await store.importInstances([corrected], { createImage }); + store.importInstances([corrected], { createImage }); // Identity, not shape: the failed import must not pin its instance. expect(created).toHaveLength(1); @@ -251,13 +228,13 @@ describe('DICOM store incremental import', () => { expect(created[0].getInstances()[0]).toBe(corrected); }); - it('keeps two series in one batch apart', async () => { + it('keeps two series in one batch apart', () => { const { createImage } = imageFactory(); const first = sliceFor({ sop: 'a', series: SERIES_UID }); const second = sliceFor({ sop: 'b', series: OTHER_SERIES_UID }); const store = useDICOMStore(); - const result = await store.importInstances([first, second], { + const result = store.importInstances([first, second], { createImage, }); diff --git a/src/store/__tests__/datasets-dicom-transaction.spec.ts b/src/store/__tests__/datasets-dicom-transaction.spec.ts index 85fffda80..02def5b4c 100644 --- a/src/store/__tests__/datasets-dicom-transaction.spec.ts +++ b/src/store/__tests__/datasets-dicom-transaction.spec.ts @@ -1,13 +1,8 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags, type Instance } from '@/packages/dicom/core'; import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; import { nextTick } from 'vue'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { - fromBlob, - type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; import type { DicomInstanceSource, DataSource, @@ -26,10 +21,6 @@ import { type ImportInstancesResult, } from '@/src/store/datasets-dicom'; import { tilt } from '@/tests/dicomOrientationFixtures'; -import { - cineHeader, - cineParseResult, -} from '@/src/core/cine/__tests__/cineFixtures'; import { ALLOCATION_FAILURE, cineFor, @@ -49,7 +40,15 @@ const onlyId = ({ volumes }: ImportInstancesResult) => { return ids[0]; }; -const parseCineDicom = () => cineParseResult(cineHeader()); +/** The error a call throws, or null when it returns. */ +const failureOf = (run: () => unknown) => { + try { + run(); + return null; + } catch (error) { + return error; + } +}; /** * Orientation agreement is a tolerance, so a bucket depends on which instance @@ -69,12 +68,12 @@ const splitting = () => ({ const cachedIds = () => Object.keys(useImageCacheStore().imageById); /** Loads the pair a later batch splits into two fresh collections. */ -const loadSplittablePair = async () => { +const loadSplittablePair = () => { const instances = splitting(); const loaded = imageFactory(); const store = useDICOMStore(); const id = onlyId( - await store.importInstances([instances.one, instances.three], { + store.importInstances([instances.one, instances.three], { createImage: loaded.createImage, }) ); @@ -86,16 +85,16 @@ const growAndFail = async () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); const first = sliceFor({ sop: 'a', z: 0 }); - const id = onlyId(await store.importInstances([first], { createImage })); + const id = onlyId(store.importInstances([first], { createImage })); await untilLoaded(id); const shown = created[0].getVtkImageData(); - await expect( + expect(() => store.importInstances( [sliceFor({ sop: 'b', z: 1 }), unallocatableFor({ sop: 'scout' })], { createImage } ) - ).rejects.toThrow(ALLOCATION_FAILURE); + ).toThrow(ALLOCATION_FAILURE); return { store, id, first, created, shown }; }; @@ -105,11 +104,11 @@ describe('DICOM store atomic series commit', () => { setActivePinia(createPinia()); }); - it('commits nothing for a series when one of its collections fails to allocate', async () => { + it('commits nothing for a series when one of its collections fails to allocate', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); - await expect( + expect(() => store.importInstances( [ unallocatableFor({ sop: 'scout' }), @@ -118,7 +117,7 @@ describe('DICOM store atomic series commit', () => { ], { createImage } ) - ).rejects.toThrow(ALLOCATION_FAILURE); + ).toThrow(ALLOCATION_FAILURE); expect(created).toEqual([]); expect(cachedIds()).toEqual([]); @@ -151,7 +150,7 @@ describe('DICOM store atomic series commit', () => { const retry = imageFactory(); const corrected = sliceFor({ sop: 'b', z: 1 }); const scout = sliceFor({ sop: 'scout', rows: '8' }); - const result = await store.importInstances([corrected, scout], { + const result = store.importInstances([corrected, scout], { createImage: retry.createImage, }); @@ -171,15 +170,15 @@ describe('DICOM store atomic series commit', () => { expect(store.volumeInfo[scoutId].NumberOfSlices).toBe(1); }); - it('keeps a dissolved volume when the split that dissolves it fails', async () => { - const { store, id, zero, two, loaded } = await loadSplittablePair(); + it('keeps a dissolved volume when the split that dissolves it fails', () => { + const { store, id, zero, two, loaded } = loadSplittablePair(); const failing = imageFactory(); - await expect( + expect(() => store.importInstances([zero, two, unallocatableFor({ sop: 'scout' })], { createImage: failing.createImage, }) - ).rejects.toThrow(ALLOCATION_FAILURE); + ).toThrow(ALLOCATION_FAILURE); expect(cachedIds()).toEqual([id]); expect(store.volumeInfo[id].NumberOfSlices).toBe(2); @@ -188,26 +187,26 @@ describe('DICOM store atomic series commit', () => { expect(failing.created).toEqual([]); }); - it('hands a dissolved volume to the given removal before reporting the commit', async () => { - const { store, id, zero, two } = await loadSplittablePair(); - const calls: string[] = []; + it('hands a dissolved volume to the given removal', () => { + const { store, id, zero, two } = loadSplittablePair(); + const removed: string[] = []; - await store.importInstances([zero, two], { + const result = store.importInstances([zero, two], { createImage: imageFactory().createImage, - removeDissolved: (removed) => calls.push(`remove:${removed}`), - onCommitted: ({ dissolved }) => calls.push(`commit:${dissolved.join()}`), + removeDissolved: (dissolved) => removed.push(dissolved), }); - expect(calls).toEqual([`remove:${id}`, `commit:${id}`]); + expect(removed).toEqual([id]); + expect(result.dissolved).toEqual([id]); // The removal is the caller's whole, so the store evicted nothing itself. expect(cachedIds()).toContain(id); expect(store.volumeInfo[id]).toBeDefined(); }); - it('removes the dissolved volume once the split commits', async () => { - const { store, id, zero, one, two, three } = await loadSplittablePair(); + it('removes the dissolved volume once the split commits', () => { + const { store, id, zero, one, two, three } = loadSplittablePair(); - const result = await store.importInstances([zero, two], { + const result = store.importInstances([zero, two], { createImage: imageFactory().createImage, }); @@ -226,7 +225,7 @@ describe('DICOM store atomic series commit', () => { expect(Object.values(result.volumes)).toContainEqual([two, three]); }); - it('converges on the one-shot plan when one series is imported concurrently', async () => { + it('converges on the one-shot plan when one series arrives in two imports', () => { const state = (created: ReturnType['created']) => { const store = useDICOMStore(); return { @@ -240,40 +239,38 @@ describe('DICOM store atomic series commit', () => { }; }; - const oneShot = async () => { + const oneShot = () => { setActivePinia(createPinia()); const { created, createImage } = imageFactory(); - await useDICOMStore().importInstances( + useDICOMStore().importInstances( [sliceFor({ sop: 'a', z: 0 }), sliceFor({ sop: 'b', z: 1 })], { createImage } ); return state(created); }; - const concurrent = async () => { + const twice = () => { setActivePinia(createPinia()); const { created, createImage } = imageFactory(); const store = useDICOMStore(); - await Promise.all([ - store.importInstances([sliceFor({ sop: 'a', z: 0 })], { createImage }), - store.importInstances([sliceFor({ sop: 'b', z: 1 })], { createImage }), - ]); + store.importInstances([sliceFor({ sop: 'a', z: 0 })], { createImage }); + store.importInstances([sliceFor({ sop: 'b', z: 1 })], { createImage }); return state(created); }; - expect(await concurrent()).toEqual(await oneShot()); + expect(twice()).toEqual(oneShot()); }); - it('registers no cine image when a sibling collection fails', async () => { + it('registers no cine image when a sibling collection fails', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); - await expect( + expect(() => store.importInstances( [cineFor('cine'), unallocatableFor({ sop: 'scout' })], - { createImage, parseCineDicom } + { createImage } ) - ).rejects.toThrow(ALLOCATION_FAILURE); + ).toThrow(ALLOCATION_FAILURE); // A cine clip is planned like any other collection: it reaches no store alone. expect(cachedIds()).toEqual([]); @@ -291,7 +288,7 @@ describe('DICOM store atomic series commit', () => { const scout = sliceFor({ sop: 'scout', rows: '8' }); scoutRef = new WeakRef(scout); const { createImage } = imageFactory(); - const { volumes } = await store.importInstances( + const { volumes } = store.importInstances( [scout, sliceFor({ sop: 'a', z: 0 }), sliceFor({ sop: 'b', z: 1 })], { createImage } ); @@ -334,59 +331,35 @@ const sopsOfDataset = (dataSource: DataSource | undefined) => { }); }; -/** The pipeline's own shape: a series reaches the dataset store as it commits. */ +/** The pipeline's own shape: committed series reach the dataset store. */ const load = ( instances: Instance[], createImage = imageFactory().createImage ) => importDicomInstanceSources(instances.map(sourceFor), (batch, hooks) => - useDICOMStore().importInstances(batch, { - createImage, - parseCineDicom, - ...hooks, - }) + useDICOMStore().importInstances(batch, { createImage, ...hooks }) ); -/** A cine clip whose bytes arrive once the returned release is called. */ -const slowCine = () => { - let release!: () => void; - const gate = new Promise((resolve) => { - release = resolve; - }); - const bytes = fromBlob(new Blob(['cine'])); - const source: ByteSource = { - read: (signal) => { - const { readable, writable } = new TransformStream(); - gate.then(() => bytes.read(signal).pipeTo(writable)); - return readable; - }, - }; - return { - cine: cineFor('slow', { series: OTHER_SERIES_UID, source }), - release: () => release(), - }; -}; - describe('importDicomInstanceSources atomic series commit', () => { beforeEach(() => { setActivePinia(createPinia()); }); - it('leaves the dataset list and its provenance unchanged when a commit fails', async () => { + it('leaves the dataset list and its provenance unchanged when a commit fails', () => { const { zero, one, two, three } = splitting(); const store = useDICOMStore(); const datasetStore = useDatasetStore(); - const [loadable] = await load([one, three]); + const [loadable] = load([one, three]); const id = loadable.dataID; expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ 'sop-1', 'sop-3', ]); - await expect( - load([zero, two, unallocatableFor({ sop: 'scout' })]) - ).rejects.toThrow(ALLOCATION_FAILURE); + expect(() => load([zero, two, unallocatableFor({ sop: 'scout' })])).toThrow( + ALLOCATION_FAILURE + ); expect(datasetStore.idsAsSelections).toEqual([id]); expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ @@ -397,54 +370,11 @@ describe('importDicomInstanceSources atomic series commit', () => { expect(store.volumeInfo[id].NumberOfSlices).toBe(2); }); - it('records the membership a later import added while a cine read delays a batch', async () => { - const { cine, release } = slowCine(); - const store = useDICOMStore(); - const datasetStore = useDatasetStore(); - - const delayed = load([sliceFor({ sop: 'a', z: 0 }), cine]); - const [grown] = await load([sliceFor({ sop: 'b', z: 1 })]); - release(); - await delayed; - - // The delayed batch plans against the series as it now stands, so the - // saved sources name the whole volume. - expect(sopsOfDataset(datasetStore.getDataSource(grown.dataID))).toEqual([ - 'a', - 'b', - ]); - expect(store.volumeInfo[grown.dataID].NumberOfSlices).toBe(2); - }); - - it('keeps the growth an import landed while an earlier failing batch waited', async () => { - const { cine, release } = slowCine(); - const store = useDICOMStore(); - const datasetStore = useDatasetStore(); - - const [loadable] = await load([sliceFor({ sop: 'a', z: 0 })]); - const id = loadable.dataID; - const failing = load([ - sliceFor({ sop: 'b', z: 1 }), - unallocatableFor({ sop: 'scout' }), - cine, - ]).then( - () => null, - (err) => err - ); - await load([sliceFor({ sop: 'c', z: 2 })]); - release(); - - expect(await failing).toBeInstanceOf(PartialDicomImportError); - expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual(['a', 'c']); - expect(store.volumeInfo[id].NumberOfSlices).toBe(2); - }); - - it('grows a volume whose sibling the user removed while the batch waited', async () => { - const { cine, release } = slowCine(); + it('grows a volume after the user removed its sibling', () => { const store = useDICOMStore(); const datasetStore = useDatasetStore(); - const loaded = await load([ + const loaded = load([ sliceFor({ sop: 'scout', rows: '8' }), sliceFor({ sop: 'a', z: 0 }), sliceFor({ sop: 'b', z: 1 }), @@ -458,10 +388,8 @@ describe('importDicomInstanceSources atomic series commit', () => { const scoutId = idOf(['scout']); const id = idOf(['a', 'b']); - const delayed = load([sliceFor({ sop: 'c', z: 2 }), cine]); datasetStore.remove(scoutId); - release(); - await delayed; + load([sliceFor({ sop: 'c', z: 2 })]); expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ 'a', @@ -473,21 +401,20 @@ describe('importDicomInstanceSources atomic series commit', () => { expect(store.volumeInfo[scoutId]).toBeUndefined(); }); - it('reports what a committed series landed and blames only what failed', async () => { + it('reports what a committed series landed and blames only what failed', () => { const { zero, one, two, three } = splitting(); const store = useDICOMStore(); const datasetStore = useDatasetStore(); - const [loadable] = await load([one, three]); + const [loadable] = load([one, three]); const dissolvedId = loadable.dataID; - const failure = await load([ - zero, - two, - unallocatableFor({ sop: 'other', series: OTHER_SERIES_UID }), - ]).then( - () => null, - (err) => err + const failure = failureOf(() => + load([ + zero, + two, + unallocatableFor({ sop: 'other', series: OTHER_SERIES_UID }), + ]) ); expect(failure).toBeInstanceOf(PartialDicomImportError); @@ -515,20 +442,14 @@ describe('importDicomInstanceSources atomic series commit', () => { describe('DICOM record naming', () => { beforeEach(() => setActivePinia(createPinia())); - it('commits a nameless series with a usable fallback name', async () => { + it('commits a nameless series with a usable fallback name', () => { const nameless = sliceFor({ sop: 'nameless', tags: { [Tags.SeriesNumber]: '', [Tags.SeriesDescription]: '' }, }); const store = useDICOMStore(); const { created, createImage } = imageFactory(); - const committed: ImportInstancesResult[] = []; - const result = await store.importInstances([nameless], { - createImage, - onCommitted: (r) => committed.push(r), - }); - const id = onlyId(result); - expect(committed).toHaveLength(1); + const id = onlyId(store.importInstances([nameless], { createImage })); expect(created[0].getName()).toBe(SERIES_UID); expect(getDisplayName(store.volumeInfo[id])).toBe(SERIES_UID); }); diff --git a/src/store/__tests__/dicomImportFixtures.ts b/src/store/__tests__/dicomImportFixtures.ts index cc1952bef..2c8695edc 100644 --- a/src/store/__tests__/dicomImportFixtures.ts +++ b/src/store/__tests__/dicomImportFixtures.ts @@ -1,20 +1,16 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { - SOP_CLASS_ULTRASOUND_MULTIFRAME, - Tags, -} from '@/packages/dicom/core/metadata/dicomTags'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; import { createDicomRuntime, - type PixelDecoder, -} from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { fromBlob, + getDatasetTag, + Tags, type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; + type Instance, + type WholeInstanceDecode, +} from '@/packages/dicom/core'; +import { decodingWith } from '@/tests/dicomVolumeFixtures'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; +import { cineInstance } from '@/src/core/cine/__tests__/cineFixtures'; export const SERIES_UID = '1.2.826.0.1.3680043.9.7'; export const OTHER_SERIES_UID = '1.2.826.0.1.3680043.9.8'; @@ -87,18 +83,18 @@ const numberTag = (instance: Instance, tag: string) => Number(getDatasetTag(instance.dataset, tag)); /** Fills each slice with its InstanceNumber, without a decoder worker. */ -export const instanceNumberDecoder: PixelDecoder = async ({ instance }) => { +const instanceNumberDecoder: WholeInstanceDecode = async ({ instance }) => { const size = [ numberTag(instance, Tags.Columns), numberTag(instance, Tags.Rows), 1, - ]; + ] as const; return { size, data: new Uint16Array(size[0] * size[1]).fill( numberTag(instance, Tags.InstanceNumber) ), - imageType: { components: 1 }, + components: 1, }; }; @@ -106,8 +102,13 @@ export const instanceNumberDecoder: PixelDecoder = async ({ instance }) => { const noThumbnail = () => ''; /** Records every DICOM image the store creates, decoding without workers. */ -export function imageFactory(decoder: PixelDecoder = instanceNumberDecoder) { - const runtime = createDicomRuntime({ decoder, decodeConcurrency: 1 }); +export function imageFactory( + decoder: WholeInstanceDecode = instanceNumberDecoder +) { + const runtime = createDicomRuntime({ + ...decodingWith(decoder), + decodeConcurrency: 1, + }); const created: DicomVolumeImage[] = []; const createImage = () => { const image = new DicomVolumeImage({ @@ -125,26 +126,11 @@ export const membersOf = (image: DicomVolumeImage) => image.getInstances().map(sopOf); /** A single ultrasound multi-frame instance, which the store routes to cine. */ -export function cineFor( - sop: string, - { series = SERIES_UID, source = fromBlob(new Blob([sop])) } = {} -) { - const metadata = [ - [Tags.SOPClassUID, SOP_CLASS_ULTRASOUND_MULTIFRAME], - [Tags.NumberOfFrames, '2'], - [Tags.SOPInstanceUID, sop], - [Tags.PatientID, 'patient-1'], - [Tags.PatientName, 'Test Patient'], - [Tags.StudyInstanceUID, STUDY_UID], - [Tags.Modality, 'US'], - [Tags.SeriesInstanceUID, series], - [Tags.SeriesNumber, '7'], - [Tags.SeriesDescription, 'Imported cine'], - [Tags.Rows, '2'], - [Tags.Columns, '2'], - [Tags.SamplesPerPixel, '1'], - [Tags.BitsStored, '8'], - [Tags.PixelRepresentation, '0'], - ] as Array<[string, string]>; - return instanceFor(datasetFromTags(metadata), source); -} +export const cineFor = (sop: string, { series = SERIES_UID } = {}) => + cineInstance({ + [Tags.SOPInstanceUID]: sop, + [Tags.StudyInstanceUID]: STUDY_UID, + [Tags.SeriesInstanceUID]: series, + [Tags.SeriesNumber]: '7', + [Tags.SeriesDescription]: 'Imported cine', + }); diff --git a/src/store/__tests__/dicomTagFixtures.ts b/src/store/__tests__/dicomTagFixtures.ts index 47c31130f..d6262c19c 100644 --- a/src/store/__tests__/dicomTagFixtures.ts +++ b/src/store/__tests__/dicomTagFixtures.ts @@ -1,4 +1,4 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; /** * The tags one synthetic instance carries, in the order the DICOM store reads diff --git a/src/store/__tests__/duplicateDatasetSave.spec.ts b/src/store/__tests__/duplicateDatasetSave.spec.ts index 961b5f086..1aed29305 100644 --- a/src/store/__tests__/duplicateDatasetSave.spec.ts +++ b/src/store/__tests__/duplicateDatasetSave.spec.ts @@ -1,4 +1,4 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; import { beforeEach, describe, expect, it } from 'vitest'; import { setActivePinia, createPinia } from 'pinia'; import JSZip from 'jszip'; @@ -13,8 +13,7 @@ import { isRemoteDataSource, type DataSource, } from '@/src/io/import/dataSource'; -import { instanceFor } from '@/packages/dicom/core/instance/__tests__/instanceFixture'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; // --------------------------------------------------------------------------- diff --git a/src/store/datasets-dicom.ts b/src/store/datasets-dicom.ts index ebf5d6d66..7498cf43b 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -1,39 +1,30 @@ import { dicomDatasetToTags } from '@/src/io/readDicomTags'; import { defineStore } from 'pinia'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import { - getDatasetModality, - getDatasetTag, -} from '@/packages/dicom/core/metadata/datasetAccess'; import { + allocateVolume, emptyRegistry, forgetCollection, + getDatasetModality, registerInstances, + seriesKeyOf, + Tags, + type Instance, type InstanceCollectionUpdate, type RegistryState, -} from '@/packages/dicom/core/collections/instanceRegistry'; -import { seriesKeyOf } from '@/packages/dicom/core/collections/instanceFacts'; -import { groupBy } from '@/packages/dicom/core/collections/groupBy'; -import { - allocateVolume, type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; -import { - isUltrasoundMultiframeSopClass, - Tags, -} from '@/packages/dicom/core/metadata/dicomTags'; +} from '@/packages/dicom/core'; import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; +import type { ProgressiveImage } from '@/src/core/progressiveImage'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; import { - parseCineDicom, - type CineParseResult, -} from '@/src/core/cine/parseCineDicom'; + isCineInstance, + readCineHeader, + type CineHeader, +} from '@/src/core/cine/cineInstance'; import { surfaceWarning, useMessageStore } from '@/src/store/messages'; import { viewedSlice } from '@/src/store/dicom-viewed-slice'; -import { ensureError, removeFromArray } from '../utils'; +import { ensureError, groupBy, removeFromArray } from '../utils'; export const ANONYMOUS_PATIENT = 'Anonymous'; export const ANONYMOUS_PATIENT_ID = 'ANONYMOUS'; @@ -115,16 +106,6 @@ export const getDisplayName = (info: VolumeInfo) => { return info.splitLabel ? `${name} (${info.splitLabel})` : name; }; -/** A single ultrasound multi-frame instance, which plays as a cine clip. */ -export function isCineInstance(dataset: DicomDataset) { - const sopClass = getDatasetTag(dataset, Tags.SOPClassUID)?.trim() ?? ''; - const frames = parseInt( - (getDatasetTag(dataset, Tags.NumberOfFrames) ?? '0').trim(), - 10 - ); - return isUltrasoundMultiframeSopClass(sopClass) && frames > 1; -} - export const getWindowLevels = (info: VolumeInfo) => { const { WindowWidth, WindowLevel } = info; if ( @@ -154,12 +135,6 @@ export const getWindowLevels = (info: VolumeInfo) => { export type ImportInstancesDeps = { createImage?: (id: string) => DicomVolumeImage; - parseCineDicom?: typeof parseCineDicom; - /** - * What one series committed, reported synchronously with the commit, so no - * other import can land between the two. - */ - onCommitted?: (result: ImportInstancesResult) => void; /** * Removes a volume a replan dissolved from everything that names it, before * its replacements are reported. This store and the image cache alone by @@ -178,18 +153,23 @@ export type ImportInstancesResult = { }; /** - * A batch whose series did not all commit. Each series commits on its own and - * reports itself through `onCommitted`, so what landed is already published - * when this is thrown. + * A batch whose series did not all commit. Each series commits on its own, so + * `committed` holds what the series that did commit landed. */ export class PartialImportError extends Error { readonly failures: { error: Error; instances: Instance[] }[]; - constructor(failures: { error: Error; instances: Instance[] }[]) { + readonly committed: ImportInstancesResult; + + constructor( + failures: { error: Error; instances: Instance[] }[], + committed: ImportInstancesResult + ) { super(failures[0].error.message); this.name = 'PartialImportError'; this.cause = failures[0].error; this.failures = failures; + this.committed = committed; } } @@ -204,23 +184,14 @@ type DatabaseRecord = { /** * One collection's next value, computed before any store is touched. `keep` - * is a collection already shown as it is planned. + * is a collection already shown as it is planned; `fill` gives a DICOM image + * its new volume or SEG object. */ -type Candidate = - | { kind: 'keep'; id: string; record: DatabaseRecord | null } - | { - kind: 'cine'; - id: string; - image: DicomCineImage; - record: DatabaseRecord; - } - | { kind: 'volume'; id: string; volume: Volume; record: DatabaseRecord } - | { - kind: 'segmentation'; - id: string; - instances: readonly Instance[]; - record: DatabaseRecord; - }; +type Candidate = { id: string; record: DatabaseRecord } & ( + | { kind: 'keep' } + | { kind: 'cine'; image: DicomCineImage } + | { kind: 'dicom'; fill: (image: DicomVolumeImage) => void } +); const withDisplayName = ( record: Omit @@ -269,10 +240,7 @@ const volumeRecord = ({ }); }; -const cineRecord = ( - id: string, - header: CineParseResult['header'] -): DatabaseRecord => +const cineRecord = (id: string, header: CineHeader): DatabaseRecord => withDisplayName({ patient: header.patient, study: header.study, @@ -290,87 +258,55 @@ const cineRecord = ( warnings: [], }); -const tryParseCine = (parse: typeof parseCineDicom, bytes: Uint8Array) => { - try { - const parsed = parse(bytes); - return DicomCineImage.isSupported(parsed.header) ? parsed : null; - } catch (err) { - console.warn( - 'Failed to parse cine DICOM; falling back to volume import', - err - ); - return null; - } -}; +const cineMember = ({ kind, members }: InstanceCollectionUpdate) => + kind === 'image' && members.length === 1 && isCineInstance(members[0]) + ? members[0] + : null; -/** Cine clips need their bytes to decide, so they are read before planning. */ -async function readCines(instances: Instance[], parse: typeof parseCineDicom) { - const never = new AbortController().signal; - const clips = instances.filter(({ dataset }) => isCineInstance(dataset)); - const parsed = await Promise.all( - clips.map(async (instance) => { - // An unreadable clip falls back to the volume path, which reports it. - const bytes = await readBytes(instance.source, never).catch(() => null); - return [instance, bytes && tryParseCine(parse, bytes)] as const; - }) - ); - return new Map( - parsed.flatMap(([instance, clip]) => (clip ? [[instance, clip]] : [])) - ); +function cineCandidate( + id: string, + clip: Instance, + cached: ProgressiveImage | undefined +): Candidate { + const header = readCineHeader(clip); + const record = cineRecord(id, header); + return cached + ? { kind: 'keep', id, record } + : { kind: 'cine', id, record, image: new DicomCineImage(clip, header) }; } -const samePlan = (volume: Volume, update: InstanceCollectionUpdate) => - volume.members.length === update.members.length && - volume.members.every((member, index) => member === update.members[index]) && - volume.collection.orientation?.join() === - update.collection.orientation?.join() && - JSON.stringify(volume.reconstruction) === - JSON.stringify(update.collection.reconstruction ?? volume.reconstruction); - -type PlanContext = { - loaded: Record; - cines: Map; -}; - -function cineCandidate( - update: InstanceCollectionUpdate, - { loaded, cines }: PlanContext -): Candidate | null { - const { id, members } = update; - const parsed = members.length === 1 ? cines.get(members[0]) : undefined; - // A state-file reload already built this clip. - if (loaded[id]?.kind === 'cine') return { kind: 'keep', id, record: null }; - const cached = useImageCacheStore().imageById[id]; - if (!parsed || (cached && !(cached instanceof DicomCineImage))) return null; - return { - kind: 'cine', - id, - image: new DicomCineImage(parsed), - record: cineRecord(id, parsed.header), +function fillFor(update: InstanceCollectionUpdate, previous?: Volume) { + if (update.kind === 'segmentation') + return (image: DicomVolumeImage) => image.setSegmentation(update.members); + const volume = allocateVolume(update, {}, previous); + return (image: DicomVolumeImage) => { + image.setVolume(volume); + volume.warnings.forEach(([title, details]) => + surfaceWarning(title, details) + ); }; } -/** The next value of one planned collection. Pure apart from reading stores. */ -function planCandidate( - update: InstanceCollectionUpdate, - context: PlanContext -): Candidate { - const cine = cineCandidate(update, context); - if (cine) return cine; +/** The next value of one planned collection. Pure apart from reading the cache. */ +function planCandidate(update: InstanceCollectionUpdate): Candidate { const { id } = update; const cached = useImageCacheStore().imageById[id]; + const clip = cineMember(update); + if (clip) return cineCandidate(id, clip, cached); + const record = volumeRecord(update); + // A re-import retries whatever failed to load. + if (cached && update.change === 'unchanged') + return { kind: 'keep', id, record }; if (cached && !(cached instanceof DicomVolumeImage)) throw new Error( `Volume ${id} is already loaded as a non-DICOM progressive image; cannot re-import it as a DICOM volume.` ); - const record = volumeRecord(update); - const previous = cached?.getVolume() ?? undefined; - if (previous && samePlan(previous, update)) - return { kind: 'keep', id, record }; - const allocation = allocateVolume(update, {}, previous); - if (allocation.kind === 'segmentation') - return { kind: 'segmentation', id, instances: update.members, record }; - return { kind: 'volume', id, volume: allocation.volume, record }; + return { + kind: 'dicom', + id, + record, + fill: fillFor(update, cached?.getVolume() ?? undefined), + }; } type CommitTarget = { @@ -403,12 +339,7 @@ function showCandidate( } const cached = cache.imageById[id] as DicomVolumeImage | undefined; const image = cached ?? createImage(id); - if (candidate.kind === 'volume') { - image.setVolume(candidate.volume); - candidate.volume.warnings.forEach(([title, details]) => - surfaceWarning(title, details) - ); - } else image.setSegmentation(candidate.instances); + candidate.fill(image); if (cached) image.startLoad(); else cache.addProgressiveImage(image, { id }); return image; @@ -419,12 +350,9 @@ function commitCandidate( candidate: Candidate, createImage: (id: string) => DicomVolumeImage ) { - const { record } = candidate; - if (!record) return; - const { patient, study, volume, warnings, name } = record; + const { patient, study, volume, warnings, name } = candidate.record; store._updateDatabase(patient, study, volume); if (candidate.kind === 'keep') { - // A re-import retries whatever failed to load. const image = useImageCacheStore().imageById[candidate.id]; image?.setName(name); image?.startLoad(); @@ -483,10 +411,10 @@ export const useDICOMStore = defineStore('dicom', { * synchronous step. A series that fails to plan or allocate changes * nothing, because nothing computed for it is assigned. */ - async importInstances( + importInstances( instances: Instance[], deps: ImportInstancesDeps = {} - ): Promise { + ): ImportInstancesResult { const createImage = deps.createImage ?? ((id: string) => @@ -497,50 +425,37 @@ export const useDICOMStore = defineStore('dicom', { this.deleteVolume(id); useImageCacheStore().removeImage(id); }); - const cines = await readCines( - instances, - deps.parseCineDicom ?? parseCineDicom - ); - const failures: PartialImportError['failures'] = []; const results = [ ...groupBy(instances, (instance) => seriesKeyOf(instance.dataset)), ].flatMap(([, batch]) => { try { - const committed = this._commitSeries(batch, { - cines, - createImage, - removeDissolved, - }); - deps.onCommitted?.(committed); - return [committed]; + return [this._commitSeries(batch, { createImage, removeDissolved })]; } catch (error) { failures.push({ error: ensureError(error), instances: batch }); return []; } }); - if (failures.length) throw new PartialImportError(failures); - - return { + const committed = { volumes: Object.fromEntries( results.flatMap(({ volumes }) => Object.entries(volumes)) ), dissolved: results.flatMap(({ dissolved }) => dissolved), }; + if (failures.length) throw new PartialImportError(failures, committed); + return committed; }, _commitSeries( batch: Instance[], context: { - cines: Map; createImage: (id: string) => DicomVolumeImage; removeDissolved: (id: string) => void; } ): ImportInstancesResult { const { state, updates, removed, conflictingInstanceUids } = registerInstances(registryOf(this), batch); - const plan = { loaded: this.volumeInfo, cines: context.cines }; - const candidates = updates.map((update) => planCandidate(update, plan)); + const candidates = updates.map(planCandidate); registries.set(this, state); candidates.forEach((candidate) => diff --git a/src/store/datasets.ts b/src/store/datasets.ts index cf4ec75ea..ca565a978 100644 --- a/src/store/datasets.ts +++ b/src/store/datasets.ts @@ -9,10 +9,12 @@ import { useLayersStore } from '@/src/store/datasets-layers'; import { useModelStore } from '@/src/store/datasets-models'; import { useViewConfigStore } from '@/src/store/view-configs'; import { useImageStatsStore } from '@/src/store/image-stats'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; +import { + getDatasetTag, + Tags, + trimDicomPadding, + type Instance, +} from '@/packages/dicom/core'; export const DataType = { Image: 'Image', diff --git a/src/store/dicom-runtime.ts b/src/store/dicom-runtime.ts index 26127b76e..6e9758fb8 100644 --- a/src/store/dicom-runtime.ts +++ b/src/store/dicom-runtime.ts @@ -1,6 +1,6 @@ import { defineStore } from 'pinia'; import { markRaw, onScopeDispose } from 'vue'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; +import { createDicomRuntime } from '@/packages/dicom/core'; import { $fetch } from '@/src/utils/fetch'; import itkConfig from '@/src/io/itk/itkConfig'; diff --git a/src/store/dicom-web/dicom-web-store.ts b/src/store/dicom-web/dicom-web-store.ts index a9b2571bc..1d6a74ced 100644 --- a/src/store/dicom-web/dicom-web-store.ts +++ b/src/store/dicom-web/dicom-web-store.ts @@ -23,7 +23,7 @@ import { } from '@/src/core/dicom-web-api'; import { useViewStore } from '@/src/store/views'; import { isVolumeResult } from '@/src/io/import/common'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; +import { trimDicomPadding } from '@/packages/dicom/core'; const DICOM_WEB_URL_PARAM = 'dicomweb'; diff --git a/src/types/image.ts b/src/types/image.ts index 86d92c12f..9dd1b4263 100644 --- a/src/types/image.ts +++ b/src/types/image.ts @@ -1,7 +1,7 @@ import { mat3, mat4, vec3 } from 'gl-matrix'; import type { Bounds } from '@kitware/vtk.js/types'; import { LPSDirections } from './lps'; -import type { SpatialMetadata } from '@/packages/dicom/core/metadata/spatialMetadata'; +import type { SpatialMetadata } from '@/packages/dicom/core'; export type ImageMetadata = { name: string; diff --git a/src/utils/__tests__/dicomWindowRange.spec.ts b/src/utils/__tests__/dicomWindowRange.spec.ts index e6a8f0f3b..d2490a2dc 100644 --- a/src/utils/__tests__/dicomWindowRange.spec.ts +++ b/src/utils/__tests__/dicomWindowRange.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; import { getConsistentDicomWindowRange } from '@/src/utils/dicomWindowRange'; function windowTags(center: string, width: string, voiFunction?: string) { diff --git a/src/utils/dicom/windowMetadata.ts b/src/utils/dicom/windowMetadata.ts index cfb37e51b..c374c55fd 100644 --- a/src/utils/dicom/windowMetadata.ts +++ b/src/utils/dicom/windowMetadata.ts @@ -1,6 +1,4 @@ -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { getDatasetTag, Tags, type DicomDataset } from '@/packages/dicom/core'; /** The VOI attributes used when choosing a shared display window. */ export const getWindowMetadata = (dataset: DicomDataset) => diff --git a/src/utils/dicomWindowRange.ts b/src/utils/dicomWindowRange.ts index d90af3073..b16469404 100644 --- a/src/utils/dicomWindowRange.ts +++ b/src/utils/dicomWindowRange.ts @@ -1,4 +1,4 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/packages/dicom/core'; type DicomMetadata = Iterable | null | undefined; diff --git a/src/utils/index.ts b/src/utils/index.ts index 3496873f7..3c7166a20 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -95,6 +95,16 @@ export function partition( return partitioned; } +/** Groups keep input order, both of the keys and of their members. */ +export const groupBy = (items: readonly T[], keyOf: (item: T) => string) => + items.reduce((groups, item) => { + const key = keyOf(item); + const group = groups.get(key); + if (group) group.push(item); + else groups.set(key, [item]); + return groups; + }, new Map()); + /** A cursor over `items`: each call hands out the next one, wrapping around. */ export function cycle(items: readonly T[]) { let index = 0; @@ -245,6 +255,9 @@ export function ensureError(e: unknown) { return e instanceof Error ? e : new Error(JSON.stringify(e)); } +export const abortError = (message: string) => + new DOMException(message, 'AbortError'); + export function getErrorDetail(error: unknown, fallback: string): string { return error instanceof Error && error.message ? error.message : fallback; } diff --git a/src/utils/parseContentRangeHeader.ts b/src/utils/parseContentRangeHeader.ts new file mode 100644 index 000000000..4e798f127 --- /dev/null +++ b/src/utils/parseContentRangeHeader.ts @@ -0,0 +1,40 @@ +const CONTENT_RANGE_REGEXP = + /^bytes (?(?\d+)-(?\d+)|\*)\/(?\d+|\*)$/; + +export type ContentRange = + | { type: 'empty-range' } + | { type: 'invalid-range' } + | { type: 'unsatisfied-range'; length: number } + | { type: 'range'; start: number; end: number; length: number | null }; + +/** + * Parses a Content-Range header. + * + * Only supports bytes ranges. + * @param headerValue + * @returns + */ +export function parseContentRangeHeader( + headerValue: string | null +): ContentRange { + if (headerValue == null) return { type: 'empty-range' }; + + const match = CONTENT_RANGE_REGEXP.exec(headerValue); + const groups = match?.groups; + if (!groups) return { type: 'invalid-range' }; + + const length = groups.length === '*' ? null : parseInt(groups.length, 10); + + if (groups.range === '*') { + if (length === null) return { type: 'invalid-range' }; + return { type: 'unsatisfied-range', length }; + } + + const start = parseInt(groups.start, 10); + const end = parseInt(groups.end, 10); + + if (end < start || (length !== null && length <= end)) + return { type: 'invalid-range' }; + + return { type: 'range', start, end, length }; +} diff --git a/packages/dicom/core/source/__tests__/sourceFixtures.ts b/tests/byteSourceFixtures.ts similarity index 74% rename from packages/dicom/core/source/__tests__/sourceFixtures.ts rename to tests/byteSourceFixtures.ts index b0f3a94b3..7dd2a472c 100644 --- a/packages/dicom/core/source/__tests__/sourceFixtures.ts +++ b/tests/byteSourceFixtures.ts @@ -1,5 +1,4 @@ -import { concatBytes, defer } from '../../utils'; -import type { ByteSource } from '../byteSource'; +import type { ByteSource } from '@/packages/dicom/core'; /** Hands out bytes a chunk at a time and counts what readers pulled and cancelled. */ export const trackedSource = (bytes: Uint8Array, chunkSize = bytes.length) => { @@ -31,8 +30,8 @@ export const trackedSource = (bytes: Uint8Array, chunkSize = bytes.length) => { /** A source whose bytes never arrive; it reports when it is pulled and cancelled. */ export const hangingSource = () => { - const pulled = defer(); - const cancelled = defer(); + const pulled = Promise.withResolvers(); + const cancelled = Promise.withResolvers(); const source: ByteSource = { read: () => new ReadableStream({ @@ -45,13 +44,3 @@ export const hangingSource = () => { }; return { source, pulled: pulled.promise, cancelled: cancelled.promise }; }; - -export const readBytes = async (stream: ReadableStream) => { - const parts: Uint8Array[] = []; - const reader = stream.getReader(); - for (;;) { - const { done, value } = await reader.read(); - if (done) return concatBytes(parts); - parts.push(value); - } -}; diff --git a/tests/dicomDataset.ts b/tests/dicomDataset.ts index 39e283ab2..f468d04a5 100644 --- a/tests/dicomDataset.ts +++ b/tests/dicomDataset.ts @@ -1,4 +1,9 @@ -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { + fromBlob, + type ByteSource, + type DicomDataset, + type Instance, +} from '@/packages/dicom/core'; /** Structured headers for fixtures whose values are written as tag strings. */ export const datasetFromTags = ( @@ -16,3 +21,19 @@ export const datasetFromTags = ( }; }), }); + +const noBytes = fromBlob(new Blob([])); + +/** An instance as `readInstance` returns it, from a header built in memory. */ +export const instanceFor = ( + dataset: DicomDataset, + source: ByteSource = noBytes +): Instance => + Object.freeze({ + source, + dataset, + layout: null, + ultrasoundRegions: null, + transferSyntaxUid: null, + pixelData: null, + }); diff --git a/tests/dicomOrientationFixtures.ts b/tests/dicomOrientationFixtures.ts index 497e691af..0b1ffe843 100644 --- a/tests/dicomOrientationFixtures.ts +++ b/tests/dicomOrientationFixtures.ts @@ -12,8 +12,10 @@ export const tilt = (radians: number) => { * reference, and both others agree with it. Planned apart, the pair merges * into one collection once the between instance arrives. */ -export const mergingChunks = (chunkFor: (slice: MergingSlice) => T) => ({ - between: chunkFor({ sop: 'sop-1', z: 2, orientation: tilt(0.01) }), - straight: chunkFor({ sop: 'sop-2', z: 0, orientation: tilt(0) }), - tilted: chunkFor({ sop: 'sop-3', z: 1, orientation: tilt(0.02) }), +export const mergingInstances = ( + instanceFor: (slice: MergingSlice) => T +) => ({ + between: instanceFor({ sop: 'sop-1', z: 2, orientation: tilt(0.01) }), + straight: instanceFor({ sop: 'sop-2', z: 0, orientation: tilt(0) }), + tilted: instanceFor({ sop: 'sop-3', z: 1, orientation: tilt(0.02) }), }); diff --git a/tests/dicomConsumer.ts b/tests/dicomPages.ts similarity index 74% rename from tests/dicomConsumer.ts rename to tests/dicomPages.ts index f198dc62b..646f71297 100644 --- a/tests/dicomConsumer.ts +++ b/tests/dicomPages.ts @@ -1,9 +1,9 @@ -export async function openDicomConsumer(url: string, expectedError?: string) { +export async function openDicomPage(url: string, expectedError?: string) { await browser.url(url); - await waitForDicomConsumer(expectedError); + await waitForDicomPage(expectedError); } -export async function waitForDicomConsumer( +export async function waitForDicomPage( expectedError?: string, status = 'complete' ) { diff --git a/tests/dicomSourceFixtures.ts b/tests/dicomSourceFixtures.ts index 94ef419e6..b52de6e24 100644 --- a/tests/dicomSourceFixtures.ts +++ b/tests/dicomSourceFixtures.ts @@ -1,11 +1,5 @@ -import { StopSignal } from '@/packages/dicom/core/streaming/cachedStreamFetcher'; -import type { Fetcher } from '@/packages/dicom/core/streaming/types'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; -import { - readInstance, - type ReadInstanceOptions, -} from '@/packages/dicom/core/instance/readInstance'; -import { trackedSource } from '@/packages/dicom/core/source/__tests__/sourceFixtures'; +import { readInstance, type ReadInstanceOptions } from '@/packages/dicom/core'; +import { trackedSource } from '@/tests/byteSourceFixtures'; import { buildSyntheticDicom, type SyntheticSliceOptions, @@ -38,55 +32,6 @@ export const pixelDataStart = (bytes: Uint8Array) => { export const withoutPixelData = (bytes: Uint8Array) => bytes.slice(0, pixelDataStart(bytes)); -export const dicomFile = (bytes: Uint8Array, name = 'slice.dcm') => - new File([bytes as BlobPart], name, { type: FILE_EXT_TO_MIME.dcm }); - -/** - * A byte source that hands out its bytes a chunk at a time as the reader pulls - * them, so what a loader left undelivered says where it stopped. - */ -export const bytesFetcher = (bytes: Uint8Array, chunkSize = bytes.length) => { - let delivered = 0; - let abortController: AbortController | null = null; - - const fetcher: Fetcher = { - connect: async () => { - abortController ??= new AbortController(); - }, - getStream: () => { - let offset = 0; - return new ReadableStream({ - pull: (controller) => { - if (offset >= bytes.length) { - controller.close(); - return; - } - const chunk = bytes.slice(offset, offset + chunkSize); - offset += chunk.length; - delivered += chunk.length; - controller.enqueue(chunk); - }, - }); - }, - blob: async () => - new Blob([bytes as BlobPart], { type: FILE_EXT_TO_MIME.dcm }), - close: () => { - abortController?.abort(StopSignal); - }, - get connected() { - return !!abortController; - }, - get size() { - return delivered; - }, - contentType: FILE_EXT_TO_MIME.dcm, - get abortSignal() { - return abortController?.signal; - }, - }; - return fetcher; -}; - /** Reads a header from bytes delivered `chunkSize` at a time. */ export const readHeader = ( bytes: Uint8Array, diff --git a/tests/dicomVolumeFixtures.ts b/tests/dicomVolumeFixtures.ts new file mode 100644 index 000000000..a227f7b41 --- /dev/null +++ b/tests/dicomVolumeFixtures.ts @@ -0,0 +1,21 @@ +import { + emptyRegistry, + registerInstances, + singleDecoderTable, + wholeInstanceDecoder, + type Instance, + type WholeInstanceDecode, +} from '@/packages/dicom/core'; + +/** The first collection planned from these members, which must be an image. */ +export const plannedUpdate = (members: Instance[]) => { + const [update] = registerInstances(emptyRegistry, members).updates; + if (update.kind !== 'image') throw new Error(`Planned a ${update.kind}`); + return update; +}; + +/** Runtime options that send every instance whole to `decode`. */ +export const decodingWith = (decode: WholeInstanceDecode) => ({ + decoders: () => + singleDecoderTable(wholeInstanceDecoder('Test decoder', decode)), +}); diff --git a/tests/fixtures/dicom-consumer/composition.html b/tests/fixtures/dicom-pages/composition.html similarity index 100% rename from tests/fixtures/dicom-consumer/composition.html rename to tests/fixtures/dicom-pages/composition.html diff --git a/tests/fixtures/dicom-consumer/composition.ts b/tests/fixtures/dicom-pages/composition.ts similarity index 94% rename from tests/fixtures/dicom-consumer/composition.ts rename to tests/fixtures/dicom-pages/composition.ts index 4eddc15e9..3141c7b5b 100644 --- a/tests/fixtures/dicom-consumer/composition.ts +++ b/tests/fixtures/dicom-pages/composition.ts @@ -1,9 +1,9 @@ import { emptyRegistry, + getDatasetTag, registerInstances, -} from '@volview/dicom/core/collections/instanceRegistry'; -import { getDatasetTag } from '@volview/dicom/core/metadata/datasetAccess'; -import type { Instance } from '@volview/dicom/core/instance/readInstance'; + type Instance, +} from '@/packages/dicom/core'; import corpus from '../../dicomCompositionCorpus.json'; import { failed, never, report, runtime, sourceOf } from './shared'; import { loadCollection } from './loadVolume'; diff --git a/tests/fixtures/dicom-consumer/compositionReference.py b/tests/fixtures/dicom-pages/compositionReference.py similarity index 100% rename from tests/fixtures/dicom-consumer/compositionReference.py rename to tests/fixtures/dicom-pages/compositionReference.py diff --git a/tests/fixtures/dicom-consumer/core.html b/tests/fixtures/dicom-pages/core.html similarity index 84% rename from tests/fixtures/dicom-consumer/core.html rename to tests/fixtures/dicom-pages/core.html index ecd91b4df..562277756 100644 --- a/tests/fixtures/dicom-consumer/core.html +++ b/tests/fixtures/dicom-pages/core.html @@ -2,7 +2,7 @@ - DICOM core consumer + DICOM core page -

DICOM core consumer

+

DICOM core page

diff --git a/tests/fixtures/dicom-consumer/core.ts b/tests/fixtures/dicom-pages/core.ts similarity index 84% rename from tests/fixtures/dicom-consumer/core.ts rename to tests/fixtures/dicom-pages/core.ts index fbf2cfc99..7cf7f283e 100644 --- a/tests/fixtures/dicom-consumer/core.ts +++ b/tests/fixtures/dicom-pages/core.ts @@ -1,13 +1,14 @@ -import { fromBlob, readBytes } from '@volview/dicom/core/source/byteSource'; +import { fromBlob, readBytes } from '@/packages/dicom/core'; import { assetUrls, createRuntime, + firstUnit, describeMetadata, failed, + gdcmOnly, loadInstance, never, report, - runtime, } from './shared'; import { fixtureBytes } from './fixtureData'; @@ -15,6 +16,7 @@ async function recoverWorker() { const recovering = createRuntime({ assets: assetUrls('./recovering-worker.js'), decodeConcurrency: 1, + ...gdcmOnly, }); const file = new File( [fixtureBytes() as Uint8Array], @@ -25,8 +27,8 @@ async function recoverWorker() { // are read before either decode starts, so the first call takes the lane // whose worker fails. const readCopy = () => readBytes(instance.source, never); - const decode = (bytes: Uint8Array) => - recovering.decode({ instance, bytes }, never); + const decode = async (bytes: Uint8Array) => + firstUnit(recovering, instance).decode(bytes, never); const [firstBytes, queuedBytes] = await Promise.all([readCopy(), readCopy()]); const first = decode(firstBytes).then( () => report('first-error', 'unexpected success'), @@ -44,7 +46,10 @@ async function run() { const instance = await loadInstance(); describeMetadata(instance); const bytes = await readBytes(instance.source, never); - const image = await runtime.decode({ instance, bytes }, never); + const image = await firstUnit(createRuntime(gdcmOnly), instance).decode( + bytes, + never + ); report('pixels', Array.from(image.data).join(', ')); report('dimensions', image.size.join(', ')); report('status', 'complete'); diff --git a/tests/fixtures/dicom-consumer/corpus.html b/tests/fixtures/dicom-pages/corpus.html similarity index 66% rename from tests/fixtures/dicom-consumer/corpus.html rename to tests/fixtures/dicom-pages/corpus.html index 261355caa..9d26eabf0 100644 --- a/tests/fixtures/dicom-consumer/corpus.html +++ b/tests/fixtures/dicom-pages/corpus.html @@ -2,10 +2,10 @@ - DICOM volume corpus consumer + DICOM volume corpus page -

DICOM volume corpus consumer

+

DICOM volume corpus page

diff --git a/tests/fixtures/dicom-consumer/corpus.ts b/tests/fixtures/dicom-pages/corpus.ts similarity index 78% rename from tests/fixtures/dicom-consumer/corpus.ts rename to tests/fixtures/dicom-pages/corpus.ts index d17f30546..896f419cb 100644 --- a/tests/fixtures/dicom-consumer/corpus.ts +++ b/tests/fixtures/dicom-pages/corpus.ts @@ -1,12 +1,16 @@ +import { + singleDecoderTable, + wholeInstanceDecoder, +} from '@/packages/dicom/core'; import { createRuntime, failed, never, report, sourceOf } from './shared'; import { loadInstanceVolume } from './loadVolume'; import { describeVolume } from './describeVolume'; -const customDecoder = async () => ({ +const customDecoder = wholeInstanceDecoder('Custom', () => ({ size: [4, 4, 2], - imageType: { components: 1 }, + components: 1, data: new Uint16Array([...Array(16).fill(2), ...Array(16).fill(4)]), -}); +})); async function run() { const params = new URL(location.href).searchParams; @@ -19,7 +23,9 @@ async function run() { ? new File([await (await fetch(url)).blob()], 'volume.dcm') : url; const runtime = createRuntime( - params.get('decoder') === 'custom' ? { decoder: customDecoder } : {} + params.get('decoder') === 'custom' + ? { decoders: () => singleDecoderTable(customDecoder) } + : {} ); const instance = await runtime.readInstance(sourceOf(input), never); const { volume, image } = await loadInstanceVolume(instance, { diff --git a/tests/fixtures/dicom-consumer/describeVolume.ts b/tests/fixtures/dicom-pages/describeVolume.ts similarity index 92% rename from tests/fixtures/dicom-consumer/describeVolume.ts rename to tests/fixtures/dicom-pages/describeVolume.ts index cf4c9ddd4..899d7b705 100644 --- a/tests/fixtures/dicom-consumer/describeVolume.ts +++ b/tests/fixtures/dicom-pages/describeVolume.ts @@ -1,6 +1,6 @@ import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; -/** Public consumer output used to check geometry and every calibrated voxel. */ +/** Public page output used to check geometry and every calibrated voxel. */ export async function describeVolume( image: vtkImageData, report: (name: string, value: string) => void diff --git a/tests/fixtures/dicom-consumer/enhancedFixtures.ts b/tests/fixtures/dicom-pages/enhancedFixtures.ts similarity index 100% rename from tests/fixtures/dicom-consumer/enhancedFixtures.ts rename to tests/fixtures/dicom-pages/enhancedFixtures.ts diff --git a/tests/fixtures/dicom-consumer/fixtureData.ts b/tests/fixtures/dicom-pages/fixtureData.ts similarity index 100% rename from tests/fixtures/dicom-consumer/fixtureData.ts rename to tests/fixtures/dicom-pages/fixtureData.ts diff --git a/tests/fixtures/dicom-consumer/loadVolume.ts b/tests/fixtures/dicom-pages/loadVolume.ts similarity index 56% rename from tests/fixtures/dicom-consumer/loadVolume.ts rename to tests/fixtures/dicom-pages/loadVolume.ts index 3c0a3a243..c083e7025 100644 --- a/tests/fixtures/dicom-consumer/loadVolume.ts +++ b/tests/fixtures/dicom-pages/loadVolume.ts @@ -1,20 +1,15 @@ import { + allocateVolume, emptyRegistry, + loadVolume, registerInstances, - type InstanceCollectionUpdate, -} from '@volview/dicom/core/collections/instanceRegistry'; -import type { Instance } from '@volview/dicom/core/instance/readInstance'; -import { - allocateVolume, type AllocateVolumeOptions, + type DicomRuntime, + type Instance, + type InstanceCollectionUpdate, type Volume, -} from '@volview/dicom/core/volume/allocateVolume'; -import { loadVolume } from '@volview/dicom/core/volume/loadVolume'; -import type { DicomRuntime } from '@volview/dicom/core/runtime/createDicomRuntime'; -import { - applyVolumeUpdate, - toVtkImageData, -} from '@volview/dicom/vtk/volumeImage'; +} from '@/packages/dicom/core'; +import { applyVolumeUpdate, toVtkImageData } from '@/packages/dicom/vtk'; import { never, runtime as defaultRuntime } from './shared'; type LoadOptions = AllocateVolumeOptions & { @@ -24,13 +19,12 @@ type LoadOptions = AllocateVolumeOptions & { /** Allocates a planned collection and decodes it the way a viewer would. */ export async function loadCollection( - update: Pick, + update: InstanceCollectionUpdate, { previous, runtime = defaultRuntime, ...options }: LoadOptions = {} ) { - const allocation = allocateVolume(update, options, previous); - if (allocation.kind !== 'volume') - throw new Error(`Expected a volume, got ${allocation.kind}`); - const { volume } = allocation; + if (update.kind !== 'image') + throw new Error(`Expected a volume, got ${update.kind}`); + const volume = allocateVolume(update, options, previous); const image = toVtkImageData(volume); for await (const loaded of loadVolume(volume, { runtime, signal: never })) { if ('error' in loaded) throw loaded.error; diff --git a/tests/fixtures/dicom-consumer/parity.html b/tests/fixtures/dicom-pages/parity.html similarity index 100% rename from tests/fixtures/dicom-consumer/parity.html rename to tests/fixtures/dicom-pages/parity.html diff --git a/tests/fixtures/dicom-consumer/parity.ts b/tests/fixtures/dicom-pages/parity.ts similarity index 67% rename from tests/fixtures/dicom-consumer/parity.ts rename to tests/fixtures/dicom-pages/parity.ts index c423f9794..633a8e6a9 100644 --- a/tests/fixtures/dicom-consumer/parity.ts +++ b/tests/fixtures/dicom-pages/parity.ts @@ -1,16 +1,22 @@ -import { readBytes } from '@volview/dicom/core/source/byteSource'; -import type { Instance } from '@volview/dicom/core/instance/readInstance'; -import { - defaultDecoderTable, - planDecode, - type DecodePlan, -} from '@volview/dicom/core/pixels/decoderTable'; import { getVolumeBufferType, instancePixelFormats, + nativeFrameDecoder, + planDecode, + readBytes, + type DecodeUnit, + type Instance, type VolumeBufferConstructor, -} from '@volview/dicom/core/volume/pixelFormat'; -import { createRuntime, failed, never, report, sourceOf } from './shared'; +} from '@/packages/dicom/core'; +import { + createRuntime, + failed, + firstUnit, + gdcmOnly, + never, + report, + sourceOf, +} from './shared'; // Decodes each listed instance through GDCM and, where the decoder table // plans native frames, frame by frame from ranged reads, then reports the @@ -18,6 +24,7 @@ import { createRuntime, failed, never, report, sourceOf } from './shared'; // GDCM output must also equal the native samples before any conversion. const runtime = createRuntime(); +const gdcm = createRuntime(gdcmOnly); const firstMismatch = ( expected: ArrayLike, @@ -36,17 +43,18 @@ const isFloat = (data: ArrayLike) => async function decodeFrames( instance: Instance, - plan: Extract, + units: DecodeUnit[], Target: VolumeBufferConstructor ) { const frames = await Promise.all( - plan.index.frames.map( - async (range) => - plan.decode( - await readBytes(instance.source, never, range), - plan.format, - Target - ).samples + units.map( + async (unit) => + ( + await unit.decode( + await readBytes(instance.source, never, unit.range ?? undefined), + never + ) + ).data ) ); const samples = new Target(frames.reduce((n, frame) => n + frame.length, 0)); @@ -65,28 +73,29 @@ async function compare(name: string, source: string) { const input = source === 'file' ? new File([await (await fetch(url)).blob()], name) : url; const instance = await runtime.readInstance(sourceOf(input), never); - const plan = planDecode(defaultDecoderTable, instance); - if (plan.kind !== 'frames') - return { - name, - plan: plan.kind, - reason: plan.kind === 'unsupported' ? plan.error.message : plan.reason, - }; - const gdcm = await runtime.decode( - { instance, bytes: await readBytes(instance.source, never) }, + const planned = planDecode(runtime.decoders, instance, Float64Array); + if ('error' in planned) + return { name, plan: 'unsupported', reason: planned.error.message }; + if (planned.decoder !== nativeFrameDecoder) + return { name, plan: planned.decoder.name }; + const Target = getVolumeBufferType(instancePixelFormats(instance.dataset)); + const units = nativeFrameDecoder.plan(instance, Target) as DecodeUnit[]; + const decoded = await firstUnit(gdcm, instance).decode( + await readBytes(instance.source, never), never ); - const Target = getVolumeBufferType(instancePixelFormats(instance.dataset)); - const native = await decodeFrames(instance, plan, Target); + const native = await decodeFrames(instance, units, Target); return { name, - plan: plan.kind, + plan: 'frames', volume: Target.name, - gdcm: gdcm.data.constructor.name, + gdcm: decoded.data.constructor.name, native: native.constructor.name, samples: native.length, - mismatch: firstMismatch(new Target(gdcm.data), native), - rawMismatch: isFloat(gdcm.data) ? null : firstMismatch(gdcm.data, native), + mismatch: firstMismatch(new Target(decoded.data), native), + rawMismatch: isFloat(decoded.data) + ? null + : firstMismatch(decoded.data, native), }; } diff --git a/tests/fixtures/dicom-consumer/server.mjs b/tests/fixtures/dicom-pages/server.mjs similarity index 59% rename from tests/fixtures/dicom-consumer/server.mjs rename to tests/fixtures/dicom-pages/server.mjs index 43df13ab3..73c0f63ca 100644 --- a/tests/fixtures/dicom-consumer/server.mjs +++ b/tests/fixtures/dicom-pages/server.mjs @@ -1,11 +1,70 @@ -import { execFileSync } from 'node:child_process'; -import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises'; -import { resolve } from 'node:path'; +import { cp, mkdir, mkdtemp, readFile, readdir, rm } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { preview } from 'vite'; -import { buildConsumer } from '../../../packages/dicom/scripts/check-consumers.mjs'; +import { build, preview } from 'vite'; const root = fileURLToPath(new URL('../../../', import.meta.url)); +const fixture = fileURLToPath(new URL('.', import.meta.url)); +const require = createRequire(import.meta.url); + +// Pages exercise the DICOM module alone, so nothing from the app or its UI +// frameworks may enter their bundles. +const forbiddenModule = (id, kind) => { + const path = id.replaceAll('\\', '/'); + return ( + path.startsWith(`${root.replaceAll('\\', '/')}src/`) || + /\/node_modules\/(vue|pinia|@vue\/|@vueuse\/)/.test(path) || + (kind === 'core' && path.includes('/node_modules/@kitware/vtk.js/')) + ); +}; + +const moduleRoot = (name) => resolve(dirname(require.resolve(name)), '..'); + +async function copyItkAssets(assets) { + await mkdir(resolve(assets, 'image-io'), { recursive: true }); + await cp( + resolve( + moduleRoot('itk-wasm'), + 'dist/pipeline/web-workers/bundles/itk-wasm-pipeline.min.worker.js' + ), + resolve(assets, 'itk-wasm-pipeline.min.worker.js') + ); + const pipelines = resolve(moduleRoot('@itk-wasm/image-io'), 'dist/pipelines'); + for (const name of await readdir(pipelines)) { + if (/^gdcm-read-image\.(js|wasm|wasm\.zst)$/.test(name)) + await cp(resolve(pipelines, name), resolve(assets, 'image-io', name)); + } +} + +async function buildPage(kind, outDir) { + await build({ + configFile: false, + root: fixture, + publicDir: false, + base: './', + logLevel: 'warn', + resolve: { alias: [{ find: '@', replacement: root.replace(/\/$/, '') }] }, + plugins: [ + { + name: 'dicom-module-only', + generateBundle() { + for (const id of this.getModuleIds()) { + if (forbiddenModule(id, kind)) + this.error(`Unexpected ${kind} page dependency: ${id}`); + } + }, + }, + ], + build: { + outDir, + emptyOutDir: true, + rollupOptions: { input: resolve(fixture, `${kind}.html`) }, + }, + worker: { format: 'es' }, + }); + await copyItkAssets(resolve(outDir, 'assets')); +} function serveDicom(bytes, request, response) { const match = /^bytes=(\d+)-(\d*)/.exec(request.headers.range ?? ''); @@ -26,28 +85,19 @@ function serveDicom(bytes, request, response) { response.end(bytes.subarray(start, end)); } -export async function startDicomConsumerFixtures( +export async function startDicomPages( bytes, { kinds = ['core', 'vtk'], fixtures = {} } = {} ) { await mkdir(resolve(root, '.tmp'), { recursive: true }); const directory = await mkdtemp(resolve(root, '.tmp/dicom-browser-')); - const packageDist = resolve(directory, 'package'); const servers = []; /** @type {Record} */ const urls = {}; try { - execFileSync( - process.execPath, - ['packages/dicom/scripts/build.mjs', packageDist], - { - cwd: root, - stdio: 'inherit', - } - ); for (const kind of kinds) { const outDir = resolve(directory, kind); - await buildConsumer(kind, outDir, packageDist); + await buildPage(kind, outDir); const pipelineWorker = await readFile( resolve(outDir, 'assets/itk-wasm-pipeline.min.worker.js') ); diff --git a/tests/fixtures/dicom-consumer/shared.ts b/tests/fixtures/dicom-pages/shared.ts similarity index 69% rename from tests/fixtures/dicom-consumer/shared.ts rename to tests/fixtures/dicom-pages/shared.ts index 054e63604..7e60f09a6 100644 --- a/tests/fixtures/dicom-consumer/shared.ts +++ b/tests/fixtures/dicom-pages/shared.ts @@ -1,11 +1,13 @@ import { createDicomRuntime, + fromBlob, + fromUrl, + getDatasetTag, + planDecode, + singleDecoderTable, type DicomRuntimeOptions, -} from '@volview/dicom/core/runtime/createDicomRuntime'; -import { fromBlob, fromUrl } from '@volview/dicom/core/source/byteSource'; -import type { Instance } from '@volview/dicom/core/instance/readInstance'; -import { getDatasetTag } from '@volview/dicom/core/metadata/datasetAccess'; -import { readInstanceFacts } from '@volview/dicom/core/collections/instanceFacts'; + type Instance, +} from '@/packages/dicom/core'; import { fixtureBytes } from './fixtureData'; export const assetUrls = ( @@ -28,6 +30,19 @@ export const runtime = createRuntime(); /** Pages never cancel; disposing the runtime stops everything on pagehide. */ export const never = new AbortController().signal; +/** Runtime options that send every instance whole to GDCM. */ +export const gdcmOnly = { decoders: singleDecoderTable }; + +/** The first unit `decoding`'s table plans for an instance. */ +export function firstUnit( + decoding: Pick, 'decoders'>, + instance: Instance +) { + const planned = planDecode(decoding.decoders, instance, Float64Array); + if ('error' in planned) throw planned.error; + return planned.units[0]; +} + export const sourceOf = (input: URL | File) => input instanceof File ? fromBlob(input) @@ -49,10 +64,11 @@ export async function loadInstance() { } export function describeMetadata({ dataset }: Instance) { - const facts = readInstanceFacts(dataset); + const numbers = (tag: string) => + getDatasetTag(dataset, tag)!.split('\\').map(Number).join(', '); report('patient', getDatasetTag(dataset, '00100010')!.trim()); - report('position', facts.position!.join(', ')); - report('pixel-spacing', facts.pixelSpacing!.join(', ')); + report('position', numbers('00200032')); + report('pixel-spacing', numbers('00280030')); } export function failed(error: unknown) { diff --git a/tests/fixtures/dicom-consumer/vtk.html b/tests/fixtures/dicom-pages/vtk.html similarity index 85% rename from tests/fixtures/dicom-consumer/vtk.html rename to tests/fixtures/dicom-pages/vtk.html index 8784b9e43..237d613e2 100644 --- a/tests/fixtures/dicom-consumer/vtk.html +++ b/tests/fixtures/dicom-pages/vtk.html @@ -2,7 +2,7 @@ - DICOM vtk consumer + DICOM vtk page -

DICOM vtk consumer

+

DICOM vtk page

diff --git a/tests/fixtures/dicom-consumer/vtk.ts b/tests/fixtures/dicom-pages/vtk.ts similarity index 100% rename from tests/fixtures/dicom-consumer/vtk.ts rename to tests/fixtures/dicom-pages/vtk.ts diff --git a/tests/fixtures/oct/dicom.ts b/tests/fixtures/oct/dicom.ts index 6558f3ac4..e9854c7f7 100644 --- a/tests/fixtures/oct/dicom.ts +++ b/tests/fixtures/oct/dicom.ts @@ -1,4 +1,4 @@ -import type { DataSet } from 'dicom-parser'; +import { deflateRawSync } from 'node:zlib'; import reference from './reference.json'; import { elemShort, elemLong, LONG_FORM_VRS } from '../../specs/syntheticDicom'; @@ -17,21 +17,6 @@ export function element(tag: string, vr: string, value: string | Uint8Array) { ); } -/** Overwrites a fixed-length string value in place, padding the remainder. */ -export function overwriteDicomString( - data: DataSet, - tag: string, - value: string, - pad = 0x20 -) { - const { dataOffset, length } = data.elements[tag]; - const bytes = new TextEncoder().encode(value); - if (bytes.length > length) - throw new Error('Replacement exceeds the DICOM value length'); - data.byteArray.fill(pad, dataOffset, dataOffset + length); - data.byteArray.set(bytes, dataOffset); -} - export function sequence(tag: string, datasets: Uint8Array[]) { return element( tag, @@ -48,6 +33,123 @@ export function sequence(tag: string, datasets: Uint8Array[]) { ); } +/** An element to encode, an SQ holding its items; bytes pass through as encoded. */ +type Node = + | Readonly<{ tag: string; vr: string; value: string | Uint8Array }> + | Readonly<{ tag: string; vr: 'SQ'; items: Node[][] }> + | Uint8Array; + +const leaf = (tag: string, vr: string, value: string | Uint8Array): Node => ({ + tag, + vr, + value, +}); +const sq = (tag: string, items: Node[][]): Node => ({ tag, vr: 'SQ', items }); + +const encode = (nodes: Node[]): Buffer => + concat( + nodes.map((node) => { + if (node instanceof Uint8Array) return node; + if ('items' in node) return sequence(node.tag, node.items.map(encode)); + return element(node.tag, node.vr, node.value); + }) + ); + +/** + * Paths name a tag and descend through `tag[item]` steps, item 0 by default + * and negative from the end: `52009230[-1].00209113.00200032`. + */ +export type DatasetEdits = { + set?: Record; + omit?: string[]; +}; + +export type Part10Options = DatasetEdits & { + /** Deflated Explicit VR Little Endian, through `deflateRawSync` or the given function. */ + deflate?: boolean | ((dataset: Uint8Array) => Uint8Array); +}; + +const DEFLATED_EXPLICIT_VR = '1.2.840.10008.1.2.1.99'; + +function edit( + nodes: Node[], + [step, ...rest]: string[], + change: (node: Node) => Node | null +): Node[] { + const [, tag, item = '0'] = step.match(/^([0-9a-f]{8})(?:\[(-?\d+)\])?$/i)!; + const index = nodes.findIndex( + (node) => !(node instanceof Uint8Array) && node.tag === tag + ); + if (index < 0) throw new Error(`No element ${tag} to edit`); + const node = nodes[index]; + const next = + rest.length === 0 + ? change(node) + : sq( + tag, + (node as { items: Node[][] }).items.map((items, at, all) => + at === (Number(item) + all.length) % all.length + ? edit(items, rest, change) + : items + ) + ); + return nodes.flatMap((each, at) => + at !== index ? [each] : next ? [next] : [] + ); +} + +const applyEdits = (nodes: Node[], { set = {}, omit = [] }: DatasetEdits) => + [ + ...Object.entries(set).map( + ([path, value]) => + (all: Node[]) => + edit(all, path.split('.'), (node) => + leaf( + (node as { tag: string }).tag, + (node as { vr: string }).vr, + value + ) + ) + ), + ...omit.map( + (path) => (all: Node[]) => edit(all, path.split('.'), () => null) + ), + ].reduce((all, apply) => apply(all), nodes); + +const isFileMeta = (node: Node) => + !(node instanceof Uint8Array) && node.tag.startsWith('0002'); + +/** A Part 10 file; File Meta Group Length is written when `groupLength` or deflating. */ +function part10( + nodes: Node[], + { deflate, ...edits }: Part10Options, + groupLength: boolean +) { + const edited = applyEdits(nodes, edits); + const meta = edited + .filter(isFileMeta) + .map((node) => + deflate && !(node instanceof Uint8Array) && node.tag === '00020010' + ? leaf(node.tag, 'UI', DEFLATED_EXPLICIT_VR) + : node + ); + const metaBytes = encode(meta); + const length = Buffer.alloc(4); + length.writeUInt32LE(metaBytes.length); + const dataset = encode(edited.filter((node) => !isFileMeta(node))); + const deflateWith = deflate === true ? deflateRawSync : deflate; + const body = deflateWith ? deflateWith(dataset) : dataset; + return concat([ + Buffer.alloc(128), + Buffer.from('DICM'), + ...(groupLength || deflate ? [element('00020000', 'UL', length)] : []), + metaBytes, + body, + // DICOM requires an even-length deflated stream with a trailing NULL if needed. + Buffer.alloc(deflateWith ? body.length % 2 : 0), + ]); +} + type Frame = { position?: string; spacing?: string; @@ -55,51 +157,47 @@ type Frame = { slowSpacing?: string; }; const positionSequence = (position: string) => - sequence('00209113', [element('00200032', 'DS', position)]); + sq('00209113', [[leaf('00200032', 'DS', position)]]); const measureSequence = (spacing: string) => - sequence('00289110', [element('00280030', 'DS', spacing)]); + sq('00289110', [[leaf('00280030', 'DS', spacing)]]); const orientationSequence = (orientation: string) => - sequence('00209116', [element('00200037', 'DS', orientation)]); + sq('00209116', [[leaf('00200037', 'DS', orientation)]]); export function enhancedFile( frames: Frame[], extraHeader: Uint8Array[] = [], - orientation = '1\\0\\0\\0\\1\\0' + { + orientation = '1\\0\\0\\0\\1\\0', + ...options + }: Part10Options & { orientation?: string } = {} ) { return new Blob([ - concat([ - Buffer.alloc(128), - Buffer.from('DICM'), - element('00020010', 'UI', '1.2.840.10008.1.2.1'), - element('00080016', 'UI', '1.2.840.10008.5.1.4.1.1.77.1.5.4'), - element('00280008', 'IS', String(frames.length)), - ...extraHeader, - sequence('52009229', [ - concat([ - measureSequence('0.01\\0.02'), - orientationSequence(orientation), + part10( + [ + leaf('00020010', 'UI', '1.2.840.10008.1.2.1'), + leaf('00080016', 'UI', '1.2.840.10008.5.1.4.1.1.77.1.5.4'), + leaf('00280008', 'IS', String(frames.length)), + ...extraHeader, + sq('52009229', [ + [measureSequence('0.01\\0.02'), orientationSequence(orientation)], ]), - ]), - sequence( - '52009230', - frames.map((frame) => - concat([ + sq( + '52009230', + frames.map((frame) => [ ...(frame.position ? [positionSequence(frame.position)] : []), ...(frame.spacing ? [measureSequence(frame.spacing)] : []), ...(frame.slowSpacing - ? [ - sequence('00289110', [ - element('00180088', 'DS', frame.slowSpacing), - ]), - ] + ? [sq('00289110', [[leaf('00180088', 'DS', frame.slowSpacing)]])] : []), ...(frame.orientation ? [orientationSequence(frame.orientation)] : []), ]) - ) - ), - ]), + ), + ], + options, + false + ), ]); } @@ -113,82 +211,89 @@ export function syntheticScalars() { }); } +type SyntheticOCTOptions = Part10Options & { + scanPattern?: string; + scalars?: Uint16Array; + /** Declares (0028,0120) Pixel Padding Value. */ + pixelPaddingValue?: number; +}; + /** A regular raster with the intensity x + 2y + 3z and no clinical pixels. */ -export function createSyntheticOCT() { +export function createSyntheticOCT({ + scanPattern = '128280', + scalars = syntheticScalars(), + pixelPaddingValue, + ...options +}: SyntheticOCTOptions = {}) { const [width, depth, frames] = reference.size; const [sx, sy, sz] = reference.spacing; const uid = '1.2.826.0.1.3680043.10.999.1'; const us = (tag: string, value: number) => { const bytes = Buffer.alloc(2); bytes.writeUInt16LE(value); - return element(tag, 'US', bytes); + return leaf(tag, 'US', bytes); }; const sop = '1.2.840.10008.5.1.4.1.1.77.1.5.4'; - const fileMeta = concat([ - element('00020001', 'OB', Uint8Array.of(0, 1)), - element('00020002', 'UI', sop), - element('00020003', 'UI', `${uid}.3`), - element('00020010', 'UI', '1.2.840.10008.1.2.1'), - element('00020012', 'UI', `${uid}.99`), - ]); - const groupLength = Buffer.alloc(4); - groupLength.writeUInt32LE(fileMeta.length); const orientation = '1.0\\0.0\\0.0\\0.0\\1.0\\0.0'; - const measures = sequence('00289110', [ - concat([ - element('00180050', 'DS', String(sz)), - element('00180088', 'DS', String(sz)), - element('00280030', 'DS', `${sy}\\${sx}`), - ]), + const measures = sq('00289110', [ + [ + leaf('00180050', 'DS', String(sz)), + leaf('00180088', 'DS', String(sz)), + leaf('00280030', 'DS', `${sy}\\${sx}`), + ], ]); - const pixels = Buffer.alloc(width * depth * frames * 2); - syntheticScalars().forEach((value, index) => - pixels.writeUInt16LE(value, index * 2) + const pixels = Buffer.alloc(scalars.length * 2); + scalars.forEach((value, index) => pixels.writeUInt16LE(value, index * 2)); + return part10( + [ + leaf('00020001', 'OB', Uint8Array.of(0, 1)), + leaf('00020002', 'UI', sop), + leaf('00020003', 'UI', `${uid}.3`), + leaf('00020010', 'UI', '1.2.840.10008.1.2.1'), + leaf('00020012', 'UI', `${uid}.99`), + leaf('00080008', 'CS', 'DERIVED\\PRIMARY'), + leaf('00080016', 'UI', sop), + leaf('00080018', 'UI', `${uid}.3`), + leaf('00080020', 'DA', '20260101'), + leaf('00080030', 'TM', '000000'), + leaf('00080060', 'CS', 'OPT'), + leaf('0008103e', 'LO', 'Synthetic OCT raster'), + leaf('00100010', 'PN', 'SYNTHETIC'), + leaf('00100020', 'LO', 'SYNTHETIC'), + leaf('00180050', 'DS', String(sz)), + leaf('00180088', 'DS', String(sz)), + leaf('0020000d', 'UI', `${uid}.1`), + leaf('0020000e', 'UI', `${uid}.2`), + leaf('00200011', 'IS', '1'), + leaf('00200013', 'IS', '1'), + leaf('00200032', 'DS', '0\\0\\0'), + leaf('00200037', 'DS', orientation), + leaf('00200052', 'UI', `${uid}.4`), + sq('00221618', [[leaf('00080100', 'SH', scanPattern)]]), + leaf('00221622', 'CS', 'YES'), + us('00280002', 1), + leaf('00280004', 'CS', 'MONOCHROME2'), + leaf('00280008', 'IS', String(frames)), + us('00280010', depth), + us('00280011', width), + leaf('00280030', 'DS', `${sy}\\${sx}`), + us('00280100', 16), + us('00280101', 16), + us('00280102', 15), + us('00280103', 0), + ...(pixelPaddingValue === undefined + ? [] + : [us('00280120', pixelPaddingValue)]), + sq('52009229', [[measures, orientationSequence(orientation)]]), + sq( + '52009230', + Array.from({ length: frames }, (_, z) => [ + positionSequence(`0.0\\0.0\\${(z * sz).toFixed(4)}`), + ]) + ), + leaf('7fe00010', 'OW', pixels), + ], + options, + true ); - return concat([ - Buffer.alloc(128), - Buffer.from('DICM'), - element('00020000', 'UL', groupLength), - fileMeta, - element('00080008', 'CS', 'DERIVED\\PRIMARY'), - element('00080016', 'UI', sop), - element('00080018', 'UI', `${uid}.3`), - element('00080020', 'DA', '20260101'), - element('00080030', 'TM', '000000'), - element('00080060', 'CS', 'OPT'), - element('0008103e', 'LO', 'Synthetic OCT raster'), - element('00100010', 'PN', 'SYNTHETIC'), - element('00100020', 'LO', 'SYNTHETIC'), - element('00180050', 'DS', String(sz)), - element('00180088', 'DS', String(sz)), - element('0020000d', 'UI', `${uid}.1`), - element('0020000e', 'UI', `${uid}.2`), - element('00200011', 'IS', '1'), - element('00200013', 'IS', '1'), - element('00200032', 'DS', '0\\0\\0'), - element('00200037', 'DS', orientation), - element('00200052', 'UI', `${uid}.4`), - sequence('00221618', [element('00080100', 'SH', '128280')]), - element('00221622', 'CS', 'YES'), - us('00280002', 1), - element('00280004', 'CS', 'MONOCHROME2'), - element('00280008', 'IS', String(frames)), - us('00280010', depth), - us('00280011', width), - element('00280030', 'DS', `${sy}\\${sx}`), - us('00280100', 16), - us('00280101', 16), - us('00280102', 15), - us('00280103', 0), - sequence('52009229', [ - concat([measures, orientationSequence(orientation)]), - ]), - sequence( - '52009230', - Array.from({ length: frames }, (_, z) => - positionSequence(`0.0\\0.0\\${(z * sz).toFixed(4)}`) - ) - ), - element('7fe00010', 'OW', pixels), - ]); } diff --git a/tests/fixtures/oct/padding.ts b/tests/fixtures/oct/padding.ts index 338fc8d15..59c202019 100644 --- a/tests/fixtures/oct/padding.ts +++ b/tests/fixtures/oct/padding.ts @@ -1,37 +1,28 @@ -import dicomParser from 'dicom-parser'; -import { elemShort, LONG_FORM_VRS } from '../../specs/syntheticDicom'; +import reference from './reference.json'; +import { + createSyntheticOCT, + syntheticScalars, + type Part10Options, +} from './dicom'; -function paddingElement() { - return elemShort(0x0028, 0x0120, 'US', Uint8Array.of(255, 255)); -} +const PADDING = 65535; -/** Declared missing data added to a synthetic raster; original intensity retained elsewhere. */ -export function paddedSyntheticOCT(original: Uint8Array) { - const source = dicomParser.parseDicom(original); - const next = Object.keys(source.elements) - .sort() - .find((tag) => tag > 'x00280120')!; - const element = source.elements[next]; - const longVR = LONG_FORM_VRS.has(element.vr!); - const position = element.dataOffset - (longVR ? 12 : 8); - const bytes = Buffer.concat([ - original.subarray(0, position), - paddingElement(), - original.subarray(position), - ]); - const dataset = dicomParser.parseDicom(bytes); - const width = dataset.uint16('x00280011')!; - const depth = dataset.uint16('x00280010')!; - const offset = dataset.elements.x7fe00010.dataOffset; - const pixelOffset = (x: number, y: number, z: number) => - offset + 2 * ((z * depth + y) * width + x); +/** Declared missing data over two B-scan columns and one voxel; original intensity elsewhere. */ +export function paddedSyntheticOCT(options: Part10Options = {}) { + const [width, depth] = reference.size; + const scalars = syntheticScalars(); + const voxel = (x: number, y: number, z: number) => + (z * depth + y) * width + x; for (const [x, z] of [ [0, 0], [5, 12], ]) { - for (let y = 0; y < depth; y++) - bytes.writeUInt16LE(65535, pixelOffset(x, y, z)); + for (let y = 0; y < depth; y++) scalars[voxel(x, y, z)] = PADDING; } - bytes.writeUInt16LE(65535, pixelOffset(10, 0, 10)); - return { bytes }; + scalars[voxel(10, 0, 10)] = PADDING; + return createSyntheticOCT({ + ...options, + scalars, + pixelPaddingValue: PADDING, + }); } diff --git a/tests/fixtures/oct/volumes.ts b/tests/fixtures/oct/volumes.ts index e43b66ed6..6b7647da6 100644 --- a/tests/fixtures/oct/volumes.ts +++ b/tests/fixtures/oct/volumes.ts @@ -1,55 +1,16 @@ -import dicomParser from 'dicom-parser'; -import { deflateRawSync, gzipSync } from 'node:zlib'; +import { gzipSync } from 'node:zlib'; import reference from './reference.json'; -import { overwriteDicomString, syntheticScalars } from './dicom'; -import { elemShort } from '../../specs/syntheticDicom'; +import { createSyntheticOCT, syntheticScalars } from './dicom'; -/** Preserve a Part 10 dataset while changing only its transfer syntax. */ -export function deflatedExplicitVR( - source: Uint8Array, - deflate: (dataset: Uint8Array) => Uint8Array = deflateRawSync -) { - const data = dicomParser.parseDicom(source, { untilTag: 'x7fe00010' }); - const position = Math.max( - ...Object.values(data.elements) - .filter((element) => element.tag.startsWith('x0002')) - .map((element) => element.dataOffset + element.length) - ); - const syntax = data.elements.x00020010; - const uid = Buffer.from('1.2.840.10008.1.2.1.99', 'ascii'); - const syntaxElement = elemShort(2, 16, 'UI', uid); - let prefix = Buffer.concat([ - source.subarray(0, syntax.dataOffset - 8), - syntaxElement, - source.subarray(syntax.dataOffset + syntax.length, position), - ]); - const groupLength = data.elements.x00020000; - if (!groupLength) { - const lengthElement = elemShort(2, 0, 'UL', new Uint8Array(4)); - prefix = Buffer.concat([ - prefix.subarray(0, 132), - lengthElement, - prefix.subarray(132), - ]); - } - const lengthOffset = groupLength?.dataOffset ?? 140; - prefix.writeUInt32LE(prefix.length - (lengthOffset + 4), lengthOffset); - const deflated = deflate(source.subarray(position)); - // DICOM requires an even-length deflated stream with a trailing NULL if needed. - return Buffer.concat([prefix, deflated, Buffer.alloc(deflated.length % 2)]); -} - -export function nonOCTDicom(source: Uint8Array) { - const bytes = Buffer.from(source); - const dicom = dicomParser.parseDicom(bytes); - for (const [tag, value] of [ - ['x00020002', '1.2.840.10008.5.1.4.1.1.7.3'], - ['x00080016', '1.2.840.10008.5.1.4.1.1.7.3'], - ['x00080060', 'CT'], - ]) - overwriteDicomString(dicom, tag, value, tag === 'x00080060' ? 0x20 : 0); - return bytes; -} +/** The synthetic raster declared as an ordinary CT. */ +export const nonOCTDicom = () => + createSyntheticOCT({ + set: { + '00020002': '1.2.840.10008.5.1.4.1.1.7.3', + '00080016': '1.2.840.10008.5.1.4.1.1.7.3', + '00080060': 'CT', + }, + }); type Volume = { scalars: Uint16Array; diff --git a/tests/nativePixelDicom.ts b/tests/nativePixelDicom.ts index 821f4849c..6f278c43f 100644 --- a/tests/nativePixelDicom.ts +++ b/tests/nativePixelDicom.ts @@ -2,7 +2,7 @@ // for comparing frame decoders. Stored words are written as given, so high // bits above Bits Stored can carry anything a test wants. -import { concatBytes } from '@/packages/dicom/core/utils'; +import { combine } from '@/tests/specs/syntheticDicom'; export const IMPLICIT_LE = '1.2.840.10008.1.2'; export const EXPLICIT_LE = '1.2.840.10008.1.2.1'; @@ -62,10 +62,10 @@ const numbers = (vr: string, values: number[], littleEndian: boolean) => { }; const tagBytes = (tag: number, littleEndian: boolean) => - concatBytes([ + combine( uint(tag >>> 16, 2, littleEndian), - uint(tag & 0xffff, 2, littleEndian), - ]); + uint(tag & 0xffff, 2, littleEndian) + ); function valueBytes(element: DataElement, encoding: Encoding): Uint8Array { const { vr, value } = element; @@ -74,16 +74,16 @@ function valueBytes(element: DataElement, encoding: Encoding): Uint8Array { return new TextEncoder().encode(value.length % 2 ? value + pad : value); } if (value instanceof Uint8Array) - return value.length % 2 ? concatBytes([value, new Uint8Array(1)]) : value; + return value.length % 2 ? combine(value, new Uint8Array(1)) : value; if (vr === 'SQ') - return concatBytes( - (value as DataElement[][]).map((item) => { + return combine( + ...(value as DataElement[][]).map((item) => { const body = encodeElements(item, encoding); - return concatBytes([ + return combine( tagBytes(0xfffee000, encoding.littleEndian), uint(body.length, 4, encoding.littleEndian), - body, - ]); + body + ); }) ); return numbers(vr, value as number[], encoding.littleEndian); @@ -104,12 +104,12 @@ function encodeElement(element: DataElement, encoding: Encoding) { uint(value.length, 2, littleEndian), ] : [uint(value.length, 4, littleEndian)]; - return concatBytes([tagBytes(element.tag, littleEndian), ...head, value]); + return combine(tagBytes(element.tag, littleEndian), ...head, value); } const encodeElements = (elements: DataElement[], encoding: Encoding) => - concatBytes( - [...elements] + combine( + ...[...elements] .sort((a, b) => a.tag - b.tag) .map((element) => encodeElement(element, encoding)) ); @@ -138,13 +138,13 @@ function part10( explicit: transferSyntaxUid !== IMPLICIT_LE, littleEndian: transferSyntaxUid !== EXPLICIT_BE, }; - return concatBytes([ + return combine( new Uint8Array(128), new TextEncoder().encode('DICM'), groupLength, meta, - encodeElements(dataset, encoding), - ]); + encodeElements(dataset, encoding) + ); } export type NativePixelOptions = { diff --git a/tests/specs/dicom-frame-reconstruction.e2e.ts b/tests/specs/dicom-frame-reconstruction.e2e.ts index 349705f7c..5ff78af4b 100644 --- a/tests/specs/dicom-frame-reconstruction.e2e.ts +++ b/tests/specs/dicom-frame-reconstruction.e2e.ts @@ -2,10 +2,10 @@ import { createHash } from 'node:crypto'; import { writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { TEMP_DIR } from '../../wdio.shared.conf'; -import { openDicomConsumer } from '../dicomConsumer'; -import { enhancedFixtureBytes } from '../fixtures/dicom-consumer/enhancedFixtures'; -import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; -import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { openDicomPage } from '../dicomPages'; +import { enhancedFixtureBytes } from '../fixtures/dicom-pages/enhancedFixtures'; +import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { volViewPage } from '../pageobjects/volview.page'; const frames = { @@ -80,9 +80,9 @@ const scenarios = [ ]; describe('Encoded multiframe reconstruction contracts', () => { - let fixture: Awaited>; + let fixture: Awaited>; before(async () => { - fixture = await startDicomConsumerFixtures(fixtureBytes(), { + fixture = await startDicomPages(fixtureBytes(), { kinds: ['corpus'], fixtures: frames, }); @@ -95,10 +95,7 @@ describe('Encoded multiframe reconstruction contracts', () => { const params = new URLSearchParams({ name: scenario.name, source }); if (scenario.policy) params.set('policy', scenario.policy); if (scenario.decoder) params.set('decoder', scenario.decoder); - await openDicomConsumer( - `${fixture.urls.corpus}?${params}`, - scenario.error - ); + await openDicomPage(`${fixture.urls.corpus}?${params}`, scenario.error); if (scenario.values) { await expect($('#pixel-hash')).toHaveText( hashFrames(scenario.values) diff --git a/tests/specs/dicom-package.e2e.ts b/tests/specs/dicom-module-pages.e2e.ts similarity index 71% rename from tests/specs/dicom-package.e2e.ts rename to tests/specs/dicom-module-pages.e2e.ts index e6076d630..17aa8346c 100644 --- a/tests/specs/dicom-package.e2e.ts +++ b/tests/specs/dicom-module-pages.e2e.ts @@ -1,21 +1,19 @@ import { PNG } from 'pngjs'; import { resolve } from 'node:path'; import { TEMP_DIR } from '../../wdio.shared.conf'; -import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; -import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; -import { openDicomConsumer } from '../dicomConsumer'; +import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; +import { openDicomPage } from '../dicomPages'; -// Both pages consume emitted JavaScript; metadata workers and GDCM assets are -// served from the same standalone output, without VolView startup. -describe('Independent DICOM package consumers', () => { - let fixture: Awaited>; +describe('DICOM module pages without VolView startup', () => { + let fixture: Awaited>; before(async () => { - fixture = await startDicomConsumerFixtures(fixtureBytes()); + fixture = await startDicomPages(fixtureBytes()); }); after(async () => fixture?.close()); it('rejects a failed worker startup and finishes queued and later reads', async () => { - await openDicomConsumer(`${fixture.urls.core}?scenario=worker-recovery`); + await openDicomPage(`${fixture.urls.core}?scenario=worker-recovery`); await expect($('#first-error')).toHaveText('DICOM decoder worker failed'); await expect($('#queued-pixels')).toHaveText( Array(16).fill('-10').join(', ') @@ -28,7 +26,7 @@ describe('Independent DICOM package consumers', () => { for (const kind of ['core', 'vtk'] as const) { for (const source of ['file', 'http']) { it(`${kind} preserves metadata and calibrated pixels from ${source}`, async () => { - await openDicomConsumer(`${fixture.urls[kind]}?source=${source}`); + await openDicomPage(`${fixture.urls[kind]}?source=${source}`); await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); await expect($('#position')).toHaveText('10, 20, 30'); await expect($('#pixel-spacing')).toHaveText('2, 3'); diff --git a/tests/specs/dicom-native-parity.e2e.ts b/tests/specs/dicom-native-parity.e2e.ts index 4cc40b13a..c3777b2cf 100644 --- a/tests/specs/dicom-native-parity.e2e.ts +++ b/tests/specs/dicom-native-parity.e2e.ts @@ -4,9 +4,9 @@ import JSZip from 'jszip'; import corpus from '../dicomVolumeCorpus.json'; import composition from '../dicomCompositionCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; -import { openDicomConsumer } from '../dicomConsumer'; -import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; -import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +import { openDicomPage } from '../dicomPages'; +import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { EXPLICIT_BE, EXPLICIT_LE, @@ -137,7 +137,7 @@ type ParityResult = { }; describe('Native frame decoding parity with GDCM', () => { - let fixture: Awaited>; + let fixture: Awaited>; const expectedNative = new Map(); let cases: string[] = []; before(async () => { @@ -167,7 +167,7 @@ describe('Native frame decoding parity with GDCM', () => { if (!expectedNative.has(name)) expectedNative.set(name, !/US_multiframe|jpeg_baseline/.test(name)); }); - fixture = await startDicomConsumerFixtures(fixtureBytes(), { + fixture = await startDicomPages(fixtureBytes(), { kinds: ['parity'], fixtures: { ...Object.fromEntries(files), @@ -186,7 +186,7 @@ describe('Native frame decoding parity with GDCM', () => { it(`writes the volume natively as GDCM does from ${source}, page ${page + 1}`, async () => { const wanted = pageOf(page); const from = page * pageSize(); - await openDicomConsumer( + await openDicomPage( `${fixture.urls.parity}?source=${source}&from=${from}&to=${from + wanted.length}` ); const results: ParityResult[] = JSON.parse( diff --git a/tests/specs/dicom-spacing-details.e2e.ts b/tests/specs/dicom-spacing-details.e2e.ts index 4738dfac6..deb1ee55f 100644 --- a/tests/specs/dicom-spacing-details.e2e.ts +++ b/tests/specs/dicom-spacing-details.e2e.ts @@ -7,7 +7,7 @@ import { newUid, type SyntheticSliceOptions, } from './syntheticDicom'; -import { enhancedFixtureBytes } from '../fixtures/dicom-consumer/enhancedFixtures'; +import { enhancedFixtureBytes } from '../fixtures/dicom-pages/enhancedFixtures'; import { dropFiles, SESSION_SAVE_TIMEOUT, waitForFileExists } from './utils'; const dialog = () => $('[data-testid="image-spacing-details"]'); diff --git a/tests/specs/dicom-volume-composition.e2e.ts b/tests/specs/dicom-volume-composition.e2e.ts index fe685c2fe..3f7f617d6 100644 --- a/tests/specs/dicom-volume-composition.e2e.ts +++ b/tests/specs/dicom-volume-composition.e2e.ts @@ -2,9 +2,9 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import corpus from '../dicomCompositionCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; -import { waitForDicomConsumer } from '../dicomConsumer'; -import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; -import { fixtureBytes } from '../fixtures/dicom-consumer/fixtureData'; +import { waitForDicomPage } from '../dicomPages'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; +import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { volViewPage } from '../pageobjects/volview.page'; import { waitForRenderedSlice } from './dicomRenderedSlice'; @@ -53,7 +53,7 @@ async function expectComposedVolumes( } describe('Downloaded DICOM volume composition', () => { - let fixture: Awaited>; + let fixture: Awaited>; before(async () => { const fixtures = Object.fromEntries( corpus.datasets.map(({ name }) => [ @@ -61,7 +61,7 @@ describe('Downloaded DICOM volume composition', () => { readFileSync(resolve(DATASET_CACHE, name)), ]) ); - fixture = await startDicomConsumerFixtures(fixtureBytes(), { + fixture = await startDicomPages(fixtureBytes(), { kinds: ['composition'], fixtures, }); @@ -76,11 +76,11 @@ describe('Downloaded DICOM volume composition', () => { `${fixture.urls.composition}?${new URLSearchParams({ case: scenario.id, source, mode })}` ); if (mode === 'incremental') { - await waitForDicomConsumer(undefined, 'partial'); + await waitForDicomPage(undefined, 'partial'); await expectComposedVolumes(scenario.volumes, true); await $('#complete-import').click(); } - await waitForDicomConsumer(); + await waitForDicomPage(); await expectComposedVolumes(scenario.volumes, false); }); } diff --git a/tests/specs/dicom-volume-corpus.e2e.ts b/tests/specs/dicom-volume-corpus.e2e.ts index 7af3d4893..10f545a3b 100644 --- a/tests/specs/dicom-volume-corpus.e2e.ts +++ b/tests/specs/dicom-volume-corpus.e2e.ts @@ -4,12 +4,12 @@ import { resolve } from 'node:path'; import { Key } from 'webdriverio'; import corpus from '../dicomVolumeCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; -import { openDicomConsumer } from '../dicomConsumer'; +import { openDicomPage } from '../dicomPages'; import { fixtureBytes, nullPaddedFixtureBytes, -} from '../fixtures/dicom-consumer/fixtureData'; -import { startDicomConsumerFixtures } from '../fixtures/dicom-consumer/server.mjs'; +} from '../fixtures/dicom-pages/fixtureData'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { volViewPage } from '../pageobjects/volview.page'; import { waitForRenderedSlice, @@ -69,7 +69,7 @@ async function expectNumbers(id: string, expected: number[]) { } describe('Public DICOM volume corpus', () => { - let fixture: Awaited>; + let fixture: Awaited>; before(async () => { const files = Object.fromEntries( corpus.map(({ name }) => [ @@ -77,7 +77,7 @@ describe('Public DICOM volume corpus', () => { readFileSync(resolve(DATASET_CACHE, name)), ]) ); - fixture = await startDicomConsumerFixtures(fixtureBytes(), { + fixture = await startDicomPages(fixtureBytes(), { kinds: ['corpus'], fixtures: { ...files, @@ -95,10 +95,7 @@ describe('Public DICOM volume corpus', () => { const behavior = expectedError ? 'rejects' : 'preserves'; it(`${behavior} ${name} pixels and geometry from ${source}`, async () => { const params = new URLSearchParams({ name, source }); - await openDicomConsumer( - `${fixture.urls.corpus}?${params}`, - expectedError - ); + await openDicomPage(`${fixture.urls.corpus}?${params}`, expectedError); if (expectedError) return; if (!expected) throw new Error(`Missing expectations for ${name}`); await expect($('#dimensions')).toHaveText( diff --git a/tests/specs/dicomElementFixtures.ts b/tests/specs/dicomElementFixtures.ts new file mode 100644 index 000000000..f1402ca0e --- /dev/null +++ b/tests/specs/dicomElementFixtures.ts @@ -0,0 +1,337 @@ +import { + attributeTagValue, + buildSyntheticCineDicom, + buildSyntheticDicom, + rawElement, + SyntheticSliceOptions, + undefinedLengthItem, + undefinedLengthSequence, +} from './syntheticDicom'; + +const concat = (...parts: Uint8Array[]) => { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + parts.reduce((offset, part) => { + out.set(part, offset); + return offset + part.length; + }, 0); + return out; +}; + +const bytes = (...values: number[]) => new Uint8Array(values); +const ascii = (text: string) => new TextEncoder().encode(text); + +// ESC $ B designates JIS X 0208, ESC ( B returns to ASCII, as ISO 2022 IR 87 +// requires around every run of ideographic or phonetic characters. +const jisX0208 = (...codes: number[]) => + bytes(0x1b, 0x24, 0x42, ...codes, 0x1b, 0x28, 0x42); + +const JAPANESE_CHARACTER_SET = 'ISO 2022 IR 6\\ISO 2022 IR 87'; + +export const JAPANESE_NAME = 'Yamada^Tarou=山田^太郎=やまだ^たろう'; +export const JAPANESE_NAME_BYTES = concat( + ascii('Yamada^Tarou='), + jisX0208(0x3b, 0x33, 0x45, 0x44), + ascii('^'), + jisX0208(0x42, 0x40, 0x4f, 0x3a), + ascii('='), + jisX0208(0x24, 0x64, 0x24, 0x5e, 0x24, 0x40), + ascii('^'), + jisX0208(0x24, 0x3f, 0x24, 0x6d, 0x24, 0x26) +); + +// ISO 2022 IR 149 carries KS X 1001 in the high half, no escape needed. +export const KOREAN_NAME = 'Hong^Gildong=洪^吉洞=홍^길동'; +export const KOREAN_NAME_BYTES = concat( + ascii('Hong^Gildong='), + bytes(0xfb, 0xf3), + ascii('^'), + bytes(0xd1, 0xce, 0xd4, 0xd7), + ascii('='), + bytes(0xc8, 0xab), + ascii('^'), + bytes(0xb1, 0xe6, 0xb5, 0xbf) +); + +// GB 2312 in the high half. Odd length, so DICOM pads it with a space. +export const CHINESE_NAME_PADDED = '王^小明 '; +export const CHINESE_NAME_BYTES = concat( + bytes(0xcd, 0xf5), + ascii('^'), + bytes(0xd0, 0xa1, 0xc3, 0xf7) +); + +// 0x81 0x39 0xee 0x39 is a four-byte GB18030 code no two-byte charset reaches. +export const GB18030_NAME_PADDED = '王^㐀 '; +export const GB18030_NAME_BYTES = concat( + bytes(0xcd, 0xf5), + ascii('^'), + bytes(0x81, 0x39, 0xee, 0x39) +); + +export const UTF8_NAME = 'Wang^Xiaoming=王^小明'; +export const UTF8_NAME_BYTES = ascii(UTF8_NAME); + +export const LATIN1_NAME_PADDED = 'Bäcker^Jörg '; +export const LATIN1_NAME_BYTES = bytes( + 0x42, + 0xe4, + 0x63, + 0x6b, + 0x65, + 0x72, + 0x5e, + 0x4a, + 0xf6, + 0x72, + 0x67 +); + +const doubles = (...values: number[]) => { + const out = new Uint8Array(values.length * 8); + const view = new DataView(out.buffer); + values.forEach((value, i) => view.setFloat64(i * 8, value, true)); + return out; +}; + +const floats = (...values: number[]) => { + const out = new Uint8Array(values.length * 4); + const view = new DataView(out.buffer); + values.forEach((value, i) => view.setFloat32(i * 4, value, true)); + return out; +}; + +/** + * Elements the named writers cannot emit: a binary buffer VR, an attribute tag, + * binary floats, and the private elements every clinical vendor writes. Tags + * sort after (0028,1053) so the data set stays ascending. + */ +export const KATAKANA_NAME = 'アイウ^エオ'; +export const KATAKANA_NAME_BYTES = bytes(0xb1, 0xb2, 0xb3, 0x5e, 0xb4, 0xb5); + +// Half width katakana and JIS X 0208 runs in one value, which ISO 2022 allows +// and no single decoder covers. GDCM stopped at the first escape here, so this +// fixture stays out of the differential corpus. +export const MIXED_JIS_NAME = 'ヤマダ^タロウ=山田^太郎'; +export const MIXED_JIS_NAME_BYTES = concat( + bytes(0xd4, 0xcf, 0xc0, 0xde), + ascii('^'), + bytes(0xc0, 0xdb, 0xb3), + ascii('='), + jisX0208(0x3b, 0x33, 0x45, 0x44), + ascii('^'), + jisX0208(0x42, 0x40, 0x4f, 0x3a) +); + +export const MIXED_VR_ELEMENTS = [ + // (0028,2000) ICC Profile, OB. + rawElement(0x0028, 0x2000, 'OB', new Uint8Array(8).fill(0x7f)), + // (0028,9445) is FL in the dictionary; written UN, as a vendor would. + rawElement(0x0028, 0x9445, 'UN', bytes(0x01, 0x02, 0x03, 0x04)), + // Odd groups, which every clinical vendor writes and GDCM never reported. + rawElement(0x0029, 0x0010, 'LO', ascii('SIEMENS CSA HEADER ')), + rawElement(0x0029, 0x1010, 'OB', new Uint8Array(6).fill(0x41)), + rawElement(0x0029, 0x1020, 'UN', new Uint8Array(4).fill(0x02)), + rawElement(0x0009, 0x1001, 'SH', ascii('GEPRIV ')), + // (0018,9087) Diffusion b-value FD, (0018,9089) gradient orientation FD x 3. + rawElement(0x0018, 0x9087, 'FD', doubles(1234567)), + rawElement(0x0018, 0x9089, 'FD', doubles(3, 0.000012345678, -0.1 - 0.2)), + // (0028,9459) LUT Frame Range, FL. + rawElement(0x0028, 0x9459, 'FL', floats(-2.5, 1e-30)), + // (0028,0009) Frame Increment Pointer, AT, single and multi valued. + rawElement(0x0028, 0x0009, 'AT', attributeTagValue(0x0018, 0x10ab)), + rawElement( + 0x0028, + 0x000a, + 'AT', + concat(attributeTagValue(0x0018, 0x1063), attributeTagValue(0x0028, 0x00ff)) + ), +]; + +/** Fixed UIDs, so a fixture's tag values are the same on every run. */ +const sliceOptions = ( + overrides: Partial = {} +): SyntheticSliceOptions => ({ + studyUid: '1.2.826.0.1.3680043.10.999.1', + seriesUid: '1.2.826.0.1.3680043.10.999.2', + sopUid: '1.2.826.0.1.3680043.10.999.3', + instanceNumber: 1, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, 0], + ...overrides, +}); + +export const buildSlice = (overrides: Partial = {}) => + buildSyntheticDicom(sliceOptions(overrides)); + +/** + * Every shape `tests/specs/syntheticDicom.ts` can emit, one entry per encoding + * or value-formatting concern the tag reader has to get right. `itkDivergence` + * names the tags where the itk-wasm reader is known to depart from the + * standard, with the value this reader returns instead. + */ +export const tagReaderCorpus = (): Array<{ + name: string; + bytes: Uint8Array; + itkDivergence?: Record; +}> => [ + { name: 'explicit VR little endian', bytes: buildSlice() }, + { + name: 'implicit VR little endian', + bytes: buildSlice({ implicitVr: true }), + }, + { + name: '8 bit pixels', + bytes: buildSlice({ + bitsAllocated: 8, + bitsStored: 8, + highBit: 7, + rows: 3, + cols: 5, + pixelValue: 3, + }), + }, + { + name: 'signed pixels', + bytes: buildSlice({ pixelRepresentation: 1, pixelValue: 0xfff0 }), + }, + { + name: 'rescale, slice spacing and a CT modality', + bytes: buildSlice({ + modality: 'CT', + rescaleSlope: 2.5, + rescaleIntercept: -1024, + spacingBetweenSlices: 1.5, + sliceThickness: 2, + }), + }, + { + name: 'fractional and negative geometry', + bytes: buildSlice({ + imageOrientationPatient: [1, 0, 0, 0, -1, 0], + imagePositionPatient: [1.5, -2, 3], + pixelSpacing: [0.5, 0.75], + }), + }, + { + name: 'odd length UIDs and a person name', + bytes: buildSlice({ + studyUid: '1.2.3', + seriesUid: '1.2.4', + sopUid: '1.2.5', + patientName: 'DOE^JOHN', + }), + }, + { + name: 'zero length patient name', + bytes: buildSlice({ patientNameBytes: new Uint8Array(0) }), + }, + { + name: 'ultrasound region sequence', + bytes: buildSlice({ + ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, + }), + }, + { + name: 'implicit VR ultrasound region sequence', + bytes: buildSlice({ + implicitVr: true, + ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, + }), + }, + { + name: 'ISO 2022 IR 87 japanese name', + bytes: buildSlice({ + specificCharacterSet: JAPANESE_CHARACTER_SET, + patientNameBytes: JAPANESE_NAME_BYTES, + }), + }, + { + // A sequence item may declare a character set of its own, which every + // Japanese and Korean study writes as a default plus an extension. + name: 'ISO 2022 IR 87 japanese name with a sequence item character set', + bytes: buildSlice({ + specificCharacterSet: JAPANESE_CHARACTER_SET, + patientNameBytes: JAPANESE_NAME_BYTES, + extraElements: [ + undefinedLengthSequence( + 0x0040, + 0x0275, + undefinedLengthItem( + concat( + rawElement(0x0008, 0x0005, 'CS', ascii(JAPANESE_CHARACTER_SET)), + rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES) + ) + ) + ), + ], + }), + }, + { + name: 'ISO 2022 IR 149 korean name', + bytes: buildSlice({ + specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 149', + patientNameBytes: KOREAN_NAME_BYTES, + }), + }, + { + name: 'ISO 2022 IR 58 chinese name', + bytes: buildSlice({ + specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 58', + patientNameBytes: CHINESE_NAME_BYTES, + }), + }, + { + name: 'GB18030 chinese name', + bytes: buildSlice({ + specificCharacterSet: 'GB18030', + patientNameBytes: GB18030_NAME_BYTES, + }), + }, + { + name: 'ISO_IR 192 utf-8 name', + bytes: buildSlice({ + specificCharacterSet: 'ISO_IR 192', + patientNameBytes: UTF8_NAME_BYTES, + }), + }, + { + name: 'ISO_IR 100 latin-1 name', + bytes: buildSlice({ + specificCharacterSet: 'ISO_IR 100', + patientNameBytes: LATIN1_NAME_BYTES, + }), + }, + { + name: 'binary, attribute tag, float and private elements', + bytes: buildSlice({ extraElements: MIXED_VR_ELEMENTS }), + }, + { + name: 'implicit VR binary, attribute tag, float and private elements', + bytes: buildSlice({ implicitVr: true, extraElements: MIXED_VR_ELEMENTS }), + }, + { + name: 'ISO 2022 IR 13 half width katakana name', + bytes: buildSlice({ + specificCharacterSet: 'ISO 2022 IR 13\\ISO 2022 IR 87', + patientNameBytes: KATAKANA_NAME_BYTES, + }), + // GDCM converted every string VR under the declared character set, so its + // CS and DS values carry the JIS X 0201 yen sign where the file wrote the + // 0x5c value delimiter. PS3.5 6.1.2 limits that conversion to SH, LO, ST, + // PN, LT, UC and UT, and the delimiter is never part of a value. + itkDivergence: { + '0008|0005': 'ISO 2022 IR 13\\ISO 2022 IR 87 ', + '0020|0032': '0\\0\\0 ', + '0020|0037': '1\\0\\0\\0\\1\\0 ', + '0028|0030': '1\\1 ', + }, + }, + { + name: 'multi frame cine', + bytes: buildSyntheticCineDicom({ + studyUid: '1.2.826.0.1.3680043.10.999.4', + seriesUid: '1.2.826.0.1.3680043.10.999.5', + sopUid: '1.2.826.0.1.3680043.10.999.6', + }), + }, +]; diff --git a/tests/specs/oct-en-face.e2e.ts b/tests/specs/oct-en-face.e2e.ts index 4c4918be0..eb05496c5 100644 --- a/tests/specs/oct-en-face.e2e.ts +++ b/tests/specs/oct-en-face.e2e.ts @@ -29,8 +29,7 @@ import { waitForModuleTransitions, } from './utils'; import { selectBasePalette } from './layerDisplayTestUtils'; -import { deflatedExplicitVR, nonOCTDicom } from '../fixtures/oct/volumes'; -import { createSyntheticOCT } from '../fixtures/oct/dicom'; +import { nonOCTDicom } from '../fixtures/oct/volumes'; import { paddedSyntheticOCT } from '../fixtures/oct/padding'; import { reference, @@ -278,10 +277,9 @@ describe('Retinal OCT en-face', () => { it('renders declared padding through the standard image contrast and palette', async () => { const name = STEM + '/retina-padding.dcm'; - const padded = paddedSyntheticOCT(createSyntheticOCT()); fs.writeFileSync( path.join(makeTempDir(STEM), 'retina-padding.dcm'), - padded.bytes + paddedSyntheticOCT() ); await openVolViewPage(name); await selectEnFace(); @@ -305,8 +303,7 @@ describe('Retinal OCT en-face', () => { it('imports deflated OCT through the file dialog with calibrated geometry and padding', async () => { const directory = makeTempDir(STEM); const file = path.join(directory, 'retina-padding-deflated.dcm'); - const padded = paddedSyntheticOCT(createSyntheticOCT()); - fs.writeFileSync(file, deflatedExplicitVR(padded.bytes)); + fs.writeFileSync(file, paddedSyntheticOCT({ deflate: true })); await volViewPage.open(); await openThroughDialog(file); await volViewPage.waitForViews(); @@ -321,7 +318,7 @@ describe('Retinal OCT en-face', () => { const image = STEM + '/ordinary-volume.dcm'; fs.writeFileSync( path.join(makeTempDir(STEM), 'ordinary-volume.dcm'), - nonOCTDicom(createSyntheticOCT()) + nonOCTDicom() ); await openVolViewPage(image); await selectEnFace(); diff --git a/tests/specs/pet-ct-sample.e2e.ts b/tests/specs/pet-ct-sample.e2e.ts index a2e3e7be9..8be49d489 100644 --- a/tests/specs/pet-ct-sample.e2e.ts +++ b/tests/specs/pet-ct-sample.e2e.ts @@ -1,6 +1,7 @@ import * as path from 'path'; import { readFileSync, writeFileSync } from 'node:fs'; -import dicomParser from 'dicom-parser'; +import dcmjs from 'dcmjs'; +import { getDatasetTag, readDicomDataset } from '@/packages/dicom/core'; import { TEMP_DIR } from '@/wdio.shared.conf'; import { PET_CT_DICOM_DATASETS } from '../datasets'; import { setValueVueInput, volViewPage } from '../pageobjects/volview.page'; @@ -225,6 +226,18 @@ async function reopenSample( ); } +/** Rewrites the windows through a full read and write; null removes the tag. */ +function withWindow(file: Buffer, window: Record) { + const message = dcmjs.data.DicomMessage.readFile( + Uint8Array.from(file).buffer + ); + Object.entries(window).forEach(([tag, value]) => { + if (value === null) delete message.dict[tag]; + else message.dict[tag]!.Value = [value]; + }); + return Buffer.from(message.write()); +} + async function openPetMetadataVariant( variant: 'valid' | 'different' | 'missing' | 'invalid' ) { @@ -232,29 +245,17 @@ async function openPetMetadataVariant( const petFiles = PET_CT_DICOM_DATASETS.filter(({ name }) => name.startsWith('PET-CT-PT-') ); + const lastWidth = { + valid: '6000', + different: '7000', + invalid: '0', + missing: null, + }; for (const [index, { name }] of petFiles.entries()) { - const bytes = Buffer.from(readFileSync(path.join(TEMP_DIR, name))); - const dataset = dicomParser.parseDicom(bytes); - for (const [tag, value] of [ - ['x00281050', '3000'], - ['x00281051', '6000'], - ]) { - const element = dataset.elements[tag]; - let replacement = value; - if (index === petFiles.length - 1 && tag === 'x00281051') { - if (variant === 'different') replacement = '7000'; - if (variant === 'invalid') replacement = '0'; - if (variant === 'missing') - bytes.writeUInt16LE(0x7777, element.dataOffset - 8); - } - expect(replacement.length).toBeLessThanOrEqual(element.length); - bytes.write( - replacement.padEnd(element.length, ' '), - element.dataOffset, - element.length, - 'ascii' - ); - } + const bytes = withWindow(readFileSync(path.join(TEMP_DIR, name)), { + '00281050': '3000', + '00281051': index === petFiles.length - 1 ? lastWidth[variant] : '6000', + }); writeFileSync(path.join(directory, name), bytes); } await useLocalSampleFiles( @@ -308,11 +309,13 @@ describe('PET/CT sample', () => { const ctFile = PET_CT_DICOM_DATASETS.find(({ name }) => name.startsWith('PET-CT-CT-') )!; - const tags = dicomParser.parseDicom( + const dataset = readDicomDataset( new Uint8Array(readFileSync(path.join(TEMP_DIR, ctFile.name))) ); - const width = Number(tags.string('x00281051')!.split('\\')[0]); - const level = Number(tags.string('x00281050')!.split('\\')[0]); + const firstValue = (tag: string) => + Number(getDatasetTag(dataset, tag)!.split('\\')[0]); + const width = firstValue('00281051'); + const level = firstValue('00281050'); expect(width).toBeGreaterThan(0); expect(Number.isFinite(level)).toBe(true); await volViewPage.open(); diff --git a/tests/specs/syntheticDicom.ts b/tests/specs/syntheticDicom.ts index c5269b055..a41596f35 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -9,6 +9,7 @@ const SOP_CLASS_MR = '1.2.840.10008.5.1.4.1.1.4'; const SOP_CLASS_ULTRASOUND_MULTIFRAME = '1.2.840.10008.5.1.4.1.1.3.1'; const TS_EXPLICIT_VR_LE = '1.2.840.10008.1.2.1'; const TS_IMPLICIT_VR_LE = '1.2.840.10008.1.2'; +const TS_JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; const enc = new TextEncoder(); @@ -35,7 +36,7 @@ const tagBytes = (group: number, element: number) => { return b; }; -const combine = (...arr: Uint8Array[]) => { +export const combine = (...arr: Uint8Array[]) => { const total = arr.reduce((acc, a) => acc + a.length, 0); const out = new Uint8Array(total); let off = 0; @@ -506,6 +507,50 @@ export const stripFileMeta = (bytes: Uint8Array) => { return meta.slice(12 + bodyLength); }; +/** One item of an encapsulated Pixel Data value, written with the length given. */ +export const pixelItem = (bytes: Uint8Array) => + combine(tagBytes(ITEM_GROUP, ITEM_TAG), writeLong(bytes.length), bytes); + +export type EncapsulatedFrames = { + /** Each frame's fragments, in order. */ + frames: readonly (readonly Uint8Array[])[]; + /** Whether the Basic Offset Table lists where each frame starts. */ + offsetTable?: boolean; +}; + +/** An encapsulated Pixel Data value: offset table item, fragments, delimiter. */ +export function encapsulatedPixelData({ + frames, + offsetTable = false, +}: EncapsulatedFrames) { + const items = frames.map((fragments) => combine(...fragments.map(pixelItem))); + const starts = items.reduce( + (offsets, _, index) => + index === 0 + ? [0] + : [...offsets, offsets[index - 1] + items[index - 1].length], + [] + ); + const table = offsetTable + ? combine(...starts.map(writeLong)) + : new Uint8Array(); + return combine( + pixelItem(table), + ...items, + tagBytes(ITEM_GROUP, SEQUENCE_DELIMITER_TAG), + writeLong(0) + ); +} + +const encapsulatedElement = (value: Uint8Array) => + combine( + tagBytes(0x7fe0, 0x0010), + enc.encode('OB'), + new Uint8Array(2), + writeLong(UNDEFINED_LENGTH), + value + ); + export type SyntheticCineOptions = { studyUid: string; seriesUid: string; @@ -518,6 +563,10 @@ export type SyntheticCineOptions = { patientId?: string; seriesNumber?: number; studyDate?: string; + /** JPEG Baseline frames to encapsulate in place of native pixels. */ + encapsulated?: EncapsulatedFrames; + /** Written just before Pixel Data. */ + extraElements?: readonly Uint8Array[]; }; export function buildSyntheticCineDicom( @@ -535,7 +584,11 @@ export function buildSyntheticCineDicom( patientId = 'TEST001', seriesNumber = 1, studyDate = '20260101', + encapsulated, + extraElements = [], } = opts; + const frames = encapsulated?.frames.length ?? numberOfFrames; + const transferSyntax = encapsulated ? TS_JPEG_BASELINE : TS_EXPLICIT_VR_LE; const pixelData = new Uint8Array(numberOfFrames * rows * cols); for (let i = 0; i < pixelData.length; i++) pixelData[i] = i % 251; @@ -557,7 +610,7 @@ export function buildSyntheticCineDicom( is(0x0020, 0x0011, String(seriesNumber)), us(0x0028, 0x0002, 1), cs(0x0028, 0x0004, 'MONOCHROME2'), - is(0x0028, 0x0008, String(numberOfFrames)), + is(0x0028, 0x0008, String(frames)), us(0x0028, 0x0010, rows), us(0x0028, 0x0011, cols), ds(0x0028, 0x0030, pixelSpacing.map((n) => n.toString()).join('\\')), @@ -565,14 +618,17 @@ export function buildSyntheticCineDicom( us(0x0028, 0x0101, 8), us(0x0028, 0x0102, 7), us(0x0028, 0x0103, 0), - elemLong(0x7fe0, 0x0010, 'OB', pixelData) + ...extraElements, + encapsulated + ? encapsulatedElement(encapsulatedPixelData(encapsulated)) + : elemLong(0x7fe0, 0x0010, 'OB', pixelData) ); const fileMetaBody = combine( elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), ui(0x0002, 0x0002, SOP_CLASS_ULTRASOUND_MULTIFRAME), ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, TS_EXPLICIT_VR_LE) + ui(0x0002, 0x0010, transferSyntax) ); const fileMeta = combine( elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), diff --git a/tests/unit/octFixture.ts b/tests/unit/octFixture.ts index 279fa52ee..40ca29f84 100644 --- a/tests/unit/octFixture.ts +++ b/tests/unit/octFixture.ts @@ -1,48 +1,21 @@ -import dicomParser from 'dicom-parser'; import { + allocateVolume, + createDicomRuntime, + fromBlob, + getDatasetTag, readInstance, type Instance, -} from '@/packages/dicom/core/instance/readInstance'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import { readGeometryFacts } from '@/packages/dicom/core/collections/instanceFacts'; -import type { DicomCollection } from '@/packages/dicom/core/collections/planDicomCollections'; -import { allocateVolume } from '@/packages/dicom/core/volume/allocateVolume'; -import { - createDicomRuntime, - type PixelDecoder, -} from '@/packages/dicom/core/runtime/createDicomRuntime'; + type InstanceCollectionUpdate, + type WholeInstanceDecode, +} from '@/packages/dicom/core'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; -import { - Tags, - toDicomParserKey, -} from '@/packages/dicom/core/metadata/dicomTags'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useViewStore } from '@/src/store/views'; import { untilLoaded } from '@/src/composables/untilLoaded'; import type { Maybe } from '@/src/types'; -import { - createSyntheticOCT, - overwriteDicomString, -} from '../fixtures/oct/dicom'; - -/** Reads raw named tags for assertions, independently of the structured loader. */ -export async function readDicomTags(file: Blob) { - const data = dicomParser.parseDicom( - new Uint8Array(await file.arrayBuffer()), - { - untilTag: 'x7fe00010', - } - ); - return Object.values(Tags).flatMap((tag): Array<[string, string]> => { - const key = toDicomParserKey(tag); - const element = data.elements[key]; - if (!element || element.vr === 'SQ') return []; - const value = - element.vr === 'US' ? String(data.uint16(key)) : data.string(key); - return value === undefined ? [] : [[tag, value]]; - }); -} +import { createSyntheticOCT } from '../fixtures/oct/dicom'; /** Reads a file's header the way the importer does, on the main thread. */ export const readFixtureInstance = (file: Blob) => @@ -53,36 +26,28 @@ export const readFixtureInstance = (file: Blob) => * deliberate groups, so geometry is judged by allocation, not by the planner. */ export function volumeOf(instances: Instance[]) { - const { orientation } = readGeometryFacts(instances[0].dataset); - const allocation = allocateVolume({ + // The first member planned alone gives the validated orientation. + const { orientation } = plannedUpdate([instances[0]]).collection; + return allocateVolume({ + kind: 'image', id: 'fixture', members: instances, - collection: { orientation } as DicomCollection, + collection: { orientation } as InstanceCollectionUpdate['collection'], }); - if (allocation.kind !== 'volume') - throw new Error(`Expected a volume, got ${allocation.kind}`); - return allocation.volume; } // Decodes every frame of an uncompressed little endian 16 bit instance. -const decodeOCT: PixelDecoder = async ({ bytes }) => { - const data = dicomParser.parseDicom(bytes); - const pixel = data.elements.x7fe00010; - const values = new DataView( - bytes.buffer, - bytes.byteOffset + pixel.dataOffset, - pixel.length - ); +const decodeOCT: WholeInstanceDecode = ({ instance, bytes }) => { + const { valueOffset, length } = instance.pixelData!; + const values = new DataView(bytes.buffer, bytes.byteOffset + valueOffset); + const count = (tag: string, fallback?: number) => + Number(getDatasetTag(instance.dataset, tag) ?? fallback); return { - size: [ - data.uint16('x00280011')!, - data.uint16('x00280010')!, - data.intString('x00280008')!, - ], - data: Uint16Array.from({ length: pixel.length / 2 }, (_, index) => + size: [count('00280011'), count('00280010'), count('00280008', 1)], + data: Uint16Array.from({ length: length! / 2 }, (_, index) => values.getUint16(index * 2, true) ), - imageType: { components: data.uint16('x00280002')! }, + components: count('00280002', 1), }; }; @@ -90,15 +55,9 @@ const decodeOCT: PixelDecoder = async ({ bytes }) => { export async function createOCTFixture( options: { scanPattern?: string; deferDecode?: boolean } = {} ) { - const bytes = Uint8Array.from(createSyntheticOCT()); - if (options.scanPattern) { - const data = dicomParser.parseDicom(bytes, { untilTag: 'x7fe00010' }); - overwriteDicomString( - data.elements.x00221618.items![0].dataSet!, - 'x00080100', - options.scanPattern - ); - } + const bytes = Uint8Array.from( + createSyntheticOCT({ scanPattern: options.scanPattern }) + ); const instance = await readFixtureInstance( new File([bytes], 'synthetic-oct.dcm') ); @@ -108,12 +67,12 @@ export async function createOCTFixture( }); if (!options.deferDecode) releaseDecode(); const image = new DicomVolumeImage({ - runtime: createDicomRuntime({ - decoder: async (request, signal) => { + runtime: createDicomRuntime( + decodingWith(async (request, signal) => { await decodeGate; return decodeOCT(request, signal); - }, - }), + }) + ), }); return { image, instance, releaseDecode }; } diff --git a/tsconfig.json b/tsconfig.json index 5a2d8c7b1..c7a479f9d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -24,9 +24,7 @@ "@wdio/visual-service" ], "paths": { - "@/*": ["./*"], - "@volview/dicom/core/*": ["./packages/dicom/core/*"], - "@volview/dicom/vtk/*": ["./packages/dicom/vtk/*"] + "@/*": ["./*"] }, "lib": ["esnext", "dom", "dom.iterable", "scripthost", "WebWorker"] }, @@ -40,7 +38,7 @@ "tests/**/*.tsx", "packages/dicom/**/*.ts" ], - "exclude": ["node_modules", "packages/dicom/dist"], + "exclude": ["node_modules"], "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" From 6efdbc739f92b3f63f91de0f271185e4c4b89f60 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sat, 14 Nov 2026 17:02:17 -0500 Subject: [PATCH 03/32] fix(dicom): settle the thumbnail of a SEG object that fails to load A SEG whose bytes could not be read or parsed left its thumbnail pending, so the patient browser showed a spinner indefinitely. The thumbnail now resolves to none once the load fails, and a retry clears the failure. --- .../__tests__/dicomVolumeImage.spec.ts | 14 ++++++++++ src/core/streaming/dicomVolumeImage.ts | 27 +++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts index 0481725ce..d41b255ee 100644 --- a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts +++ b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts @@ -556,4 +556,18 @@ describe('DicomVolumeImage segmentation', () => { ]); expect(image.isLoaded()).toBe(false); }); + + it('has no thumbnail when the segmentation reader fails', async () => { + const { image } = holder(constantSlices().decoder, { + readSegmentation: async () => { + throw new Error('unreadable SEG'); + }, + }); + + image.setSegmentation([segInstance()]); + const thumbnail = image.getThumbnail(); + image.startLoad(); + + expect(await thumbnail).toBeNull(); + }); }); diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 17c0a8e0a..323128b31 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -59,6 +59,8 @@ type Content = kind: 'segmentation'; instances: readonly Instance[]; loaded: boolean; + /** The last load failed, so no thumbnail is coming. */ + failed: boolean; }; const readSegmentationFile = async (file: File) => { @@ -166,7 +168,12 @@ export default class DicomVolumeImage extends BaseProgressiveImage { /** A SEG object, which the segmentation reader turns into a labelmap. */ setSegmentation(instances: readonly Instance[]) { - this.replaceContent({ kind: 'segmentation', instances, loaded: false }); + this.replaceContent({ + kind: 'segmentation', + instances, + loaded: false, + failed: false, + }); this.settleThumbnail?.(); } @@ -283,7 +290,10 @@ export default class DicomVolumeImage extends BaseProgressiveImage { private thumbnailSlice() { const { content } = this; if (!content) return undefined; - if (content.kind === 'segmentation') return content.loaded ? 0 : undefined; + if (content.kind === 'segmentation') { + if (content.loaded) return 0; + return content.failed ? null : undefined; + } const middle = middleSlot(content.volume); if (content.volume.loaded[middle]) return middle; if (!volumeSettled(content)) return undefined; @@ -332,6 +342,19 @@ export default class DicomVolumeImage extends BaseProgressiveImage { private async loadSegmentation( content: Content & { kind: 'segmentation' }, signal: AbortSignal + ) { + content.failed = false; + try { + await this.readSegmentationContent(content, signal); + } catch (error) { + if (!signal.aborted) content.failed = true; + throw error; + } + } + + private async readSegmentationContent( + content: Content & { kind: 'segmentation' }, + signal: AbortSignal ) { if (content.instances.length !== 1) throw new Error( From 0554aded13553bb397ae9ef3013672a35115fa00 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sat, 14 Nov 2026 17:02:26 -0500 Subject: [PATCH 04/32] fix(dicomweb): show a series volume when some of its files fail One unreadable file in a downloaded series marked the whole download as failed, even though the rest of the series loaded as a volume. The loaded volume is now shown and each failed file is reported, warning that the volume may be incomplete. A download that loads no volume still fails. --- src/store/__tests__/dicom-web-store.spec.ts | 68 ++++++++++++++++----- src/store/dicom-web/dicom-web-store.ts | 51 ++++++++++------ 2 files changed, 87 insertions(+), 32 deletions(-) diff --git a/src/store/__tests__/dicom-web-store.spec.ts b/src/store/__tests__/dicom-web-store.spec.ts index e7551141f..dc203009c 100644 --- a/src/store/__tests__/dicom-web-store.spec.ts +++ b/src/store/__tests__/dicom-web-store.spec.ts @@ -1,6 +1,11 @@ import { useDicomMetaStore } from '@/src/store/dicom-web/dicom-meta-store'; import { useViewStore } from '@/src/store/views'; -import { asOkayResult } from '@/src/io/import/common'; +import { + asErrorResult, + asLoadableResult, + asOkayResult, +} from '@/src/io/import/common'; +import { useMessageStore } from '@/src/store/messages'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; @@ -89,23 +94,26 @@ describe('DICOMweb loaded-series tracking', () => { }); }); +/** A remote series listed by the DICOMweb browser, and a spy on view selection. */ +function remoteSeries() { + useDicomMetaStore().importMeta({ + ...patient, + ...study, + ...volume('remote', 'series-uid'), + SopInstanceUID: 'instance', + StudyName: '', + InstanceNumber: '1', + Rows: '4', + Columns: '4', + }); + const select = vi.spyOn(useViewStore(), 'setDataForAllViews'); + return { select, store: useDicomWebStore() }; +} + describe('unsupported DICOMweb downloads', () => { beforeEach(() => setActivePinia(createPinia())); it('keeps existing views and a retryable card when every result was skipped', async () => { - const remote = useDicomMetaStore(); - remote.importMeta({ - ...patient, - ...study, - ...volume('remote', 'series-uid'), - SopInstanceUID: 'instance', - StudyName: '', - InstanceNumber: '1', - Rows: '4', - Columns: '4', - }); - const views = useViewStore(); - const select = vi.spyOn(views, 'setDataForAllViews'); - const store = useDicomWebStore(); + const { select, store } = remoteSeries(); const retrieve = vi.fn(async () => [new File([], 'rt.dcm')]); const importSources = async ( sources: Parameters[0][] @@ -117,3 +125,33 @@ describe('unsupported DICOMweb downloads', () => { expect(retrieve).toHaveBeenCalledTimes(2); }); }); + +describe('partly failed DICOMweb downloads', () => { + beforeEach(() => setActivePinia(createPinia())); + it('shows the loaded volume and tells the user which files failed', async () => { + const { select, store } = remoteSeries(); + const retrieve = async () => [ + new File([], 'good.dcm'), + new File([], 'bad.dcm'), + ]; + const importSources = async ([good, bad]: Parameters< + typeof asOkayResult + >[0][]) => [ + asLoadableResult('volume-1', good, 'image'), + asErrorResult(new Error('bad.dcm is not DICOM'), bad), + ]; + + await store.downloadVolume('series-uid', retrieve, importSources); + + expect(store.volumes['series-uid'].state).toBe('Done'); + expect(select).toHaveBeenCalledWith('volume-1'); + expect(useMessageStore().messages).toEqual([ + expect.objectContaining({ + title: expect.stringMatching(/may be incomplete/), + options: expect.objectContaining({ + details: expect.stringMatching(/bad\.dcm is not DICOM/), + }), + }), + ]); + }); +}); diff --git a/src/store/dicom-web/dicom-web-store.ts b/src/store/dicom-web/dicom-web-store.ts index 1d6a74ced..ee9727777 100644 --- a/src/store/dicom-web/dicom-web-store.ts +++ b/src/store/dicom-web/dicom-web-store.ts @@ -22,7 +22,10 @@ import { Instance, } from '@/src/core/dicom-web-api'; import { useViewStore } from '@/src/store/views'; -import { isVolumeResult } from '@/src/io/import/common'; +import { + isVolumeResult, + type ImportDataSourcesResult, +} from '@/src/io/import/common'; import { trimDicomPadding } from '@/packages/dicom/core'; const DICOM_WEB_URL_PARAM = 'dicomweb'; @@ -74,6 +77,35 @@ const importSettled = (results: PromiseSettledResult[]) => { }); }; +/** + * The volume to show from a series download. Files that failed beside a + * loaded volume are reported without hiding it. + */ +function primaryVolumeResult(results: ImportDataSourcesResult[]) { + const failures = results.filter((result) => result.type === 'error'); + const selectable = results.filter(isVolumeResult); + if (selectable.length === 0) + throw ( + failures[0]?.error ?? + new Error('The series contains no supported image data') + ); + failures.forEach(({ error }) => + useMessageStore().addError( + 'Some files of the DICOM series failed to load; the volume may be incomplete', + { error } + ) + ); + // A series holding overlapping acquisitions loads as several volumes; + // show the one with the most slices rather than whichever import + // happened to finish first. + const dicomStore = useDICOMStore(); + const sliceCount = (result: (typeof selectable)[number]) => + dicomStore.volumeInfo[result.dataID]?.NumberOfSlices ?? 0; + return selectable.reduce((best, result) => + sliceCount(result) > sliceCount(best) ? result : best + ); +} + /** * Collect DICOM data from DICOMWeb */ @@ -214,22 +246,7 @@ export const useDicomWebStore = defineStore('dicom-web', () => { if (results.length === 0) { throw new Error('Did not receive a load result'); } - const failed = results.find((result) => result.type === 'error'); - if (failed) throw failed.error; - - // A series holding overlapping acquisitions loads as several volumes; - // show the one with the most slices rather than whichever import - // happened to finish first. - const dicomStore = useDICOMStore(); - const selectable = results.filter(isVolumeResult); - if (selectable.length === 0) - throw new Error('The series contains no supported image data'); - const sliceCount = (result: (typeof selectable)[number]) => - dicomStore.volumeInfo[result.dataID]?.NumberOfSlices ?? 0; - const primaryResult = selectable.reduce((best, result) => - sliceCount(result) > sliceCount(best) ? result : best - ); - + const primaryResult = primaryVolumeResult(results); const selection = convertSuccessResultToDataSelection(primaryResult); useViewStore().setDataForAllViews(selection); volumes.value[volumeKey] = { From 18f7a26e92f160140b95ecf6f9763b26afc7372e Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sat, 14 Nov 2026 17:02:35 -0500 Subject: [PATCH 05/32] refactor(dicom): merge duplicate utils imports in loadVolume --- packages/dicom/core/volume/loadVolume.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/dicom/core/volume/loadVolume.ts b/packages/dicom/core/volume/loadVolume.ts index 3630fc1d6..3c9da58f1 100644 --- a/packages/dicom/core/volume/loadVolume.ts +++ b/packages/dicom/core/volume/loadVolume.ts @@ -2,8 +2,7 @@ import type { DicomRuntime } from '../runtime/createDicomRuntime'; import type { Instance } from '../instance/readInstance'; import { getDatasetTag } from '../metadata/datasetAccess'; import { Tags } from '../metadata/dicomTags'; -import { numberOr } from '../utils'; -import { abortError, linkedController } from '../utils'; +import { abortError, linkedController, numberOr } from '../utils'; import { readBytes } from '../source/byteSource'; import { planDecode, type DecoderTable } from '../pixels/decoderTable'; import { From 6d94b1b02c8cfa7a9be267bc15a7bfaf8a670880 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 15 Nov 2026 02:32:17 -0500 Subject: [PATCH 06/32] refactor(dicom): tighten the loading module after review Report failures where they happen. A read or decode failure names the file, and the frame when it lost one, and keeps the thrown value as its cause. A failed load raises one notification per attempt, titled with the series name. An uncompressed file cut short loads the frames it still holds and fails the rest instead of showing zeros. GDCM declines an instance whose frames differ in modality rescale from its header, before any pixel bytes are read. An HTTP failure reports its status. Fix what the registry tells the store. A collection's change is decided from its members, orientation and reconstruction, so a relabel no longer reallocates its volume, and an update is emitted when a sibling changes its label or warnings. A positionless image is named and warned about only beside a positioned volume of its series. Patient, study and series text is trimmed, a series with no identifying tags is named "Unnamed series", a thumbnail settles again after a retry, and an import no longer reports a volume it brought no file for. Load faster and release what is done. A Blob range is one slice, so a local frame is one read. Decodes that return at once run for a few milliseconds and then hand the thread back. A pooled request is released once its body is read. The header scan steps over defined-length sequences, and private elements are dropped in the metadata worker. Remove what nothing needs: the resume path of CachedStreamFetcher, the GDCM-shaped tag projection in readDicomTags, the archive target handler, the DICOM series worker pool, the partial import error classes, the planner's dedupe and self-check, Reconstruction.slots, the irregular geometry option, and test cases that restated others or pinned internal structure. The corpus manifests print number arrays on one line, and a pydicom script checks the volume corpus. --- packages/dicom/README.md | 122 +- .../__tests__/assignCollectionIds.spec.ts | 126 +- .../collections/__tests__/dicomTags.spec.ts | 12 - .../__tests__/idcSeriesFixtures.ts | 260 ++-- .../__tests__/instanceFacts.spec.ts | 116 +- .../__tests__/instanceFactsFixture.ts | 3 - .../__tests__/instanceRegistry.spec.ts | 288 +++- .../__tests__/multiframeGeometry.spec.ts | 99 ++ .../__tests__/planDicomCollections.spec.ts | 609 ++------ .../__tests__/reconstructVolume.spec.ts | 133 +- .../__tests__/registryAcrossImports.spec.ts | 456 ------ .../collections/__tests__/sliceFixture.ts | 10 +- .../splitOverlappingAcquisitions.spec.ts | 332 +---- .../core/collections/assignCollectionIds.ts | 34 +- .../dicom/core/collections/instanceFacts.ts | 7 +- .../core/collections/instanceRegistry.ts | 53 +- .../core/collections/multiframeGeometry.ts | 24 +- .../core/collections/planDicomCollections.ts | 288 +--- .../core/collections/reconstructVolume.ts | 68 +- .../splitOverlappingAcquisitions.ts | 102 +- .../core/header/__tests__/byteDeque.spec.ts | 38 +- .../__tests__/dicomHeaderEncodings.spec.ts | 51 +- packages/dicom/core/header/byteDeque.ts | 96 +- packages/dicom/core/header/dicomParser.ts | 219 +-- packages/dicom/core/header/readDicomHeader.ts | 33 +- .../dicom/core/header/streamingByteReader.ts | 52 +- packages/dicom/core/index.ts | 7 +- .../instance/__tests__/readInstance.spec.ts | 102 -- .../__tests__/readInstanceSources.spec.ts | 76 +- packages/dicom/core/instance/readInstance.ts | 9 +- .../metadata/__tests__/dcmjsParser.spec.ts | 10 +- .../__tests__/dicomCharacterSets.spec.ts | 104 ++ .../metadata/__tests__/dicomDataset.spec.ts | 22 - .../__tests__/ultrasoundRegion.spec.ts | 8 +- packages/dicom/core/metadata/dcmjsParser.ts | 6 +- .../dicom/core/metadata/dicomCharacterSet.ts | 3 - packages/dicom/core/metadata/dicomDataset.ts | 87 +- packages/dicom/core/metadata/dicomLayout.ts | 7 +- .../dicom/core/metadata/functionalGroups.ts | 2 +- .../dicom/core/metadata/modalityRescale.ts | 8 - .../core/metadata/readDicomDataset.worker.ts | 8 +- .../dicom/core/metadata/ultrasoundRegion.ts | 2 +- .../__tests__/encapsulatedFrames.spec.ts | 43 +- .../core/pixels/__tests__/frameIndex.spec.ts | 57 +- packages/dicom/core/pixels/decoderTable.ts | 14 +- .../dicom/core/pixels/encapsulatedFrames.ts | 3 +- packages/dicom/core/pixels/frameIndex.ts | 81 +- packages/dicom/core/pixels/nativeFrame.ts | 87 +- packages/dicom/core/pixels/pixelDecoder.ts | 13 +- .../__tests__/decoderCalibration.spec.ts | 39 - .../runtime/__tests__/dicomRuntime.spec.ts | 21 +- .../__tests__/metadataReader.spec.ts | 21 +- .../runtime/__tests__/requestPool.spec.ts | 33 +- .../dicom/core/runtime/createDicomRuntime.ts | 25 +- packages/dicom/core/runtime/gdcmDecoder.ts | 44 +- packages/dicom/core/runtime/metadataReader.ts | 30 +- packages/dicom/core/runtime/requestPool.ts | 63 +- .../core/source/__tests__/byteSource.spec.ts | 71 +- packages/dicom/core/source/byteSource.ts | 19 +- packages/dicom/core/source/httpCodes.ts | 6 - .../core/source/parseContentRangeHeader.ts | 8 +- packages/dicom/core/utils.ts | 27 - .../volume/__tests__/allocateVolume.spec.ts | 37 +- .../core/volume/__tests__/enhancedFixture.ts | 69 + ...alGroups.spec.ts => frameGeometry.spec.ts} | 284 +--- .../core/volume/__tests__/loadFrames.spec.ts | 236 ++-- .../core/volume/__tests__/loadVolume.spec.ts | 74 +- .../core/volume/__tests__/pixelFormat.spec.ts | 264 ++++ .../core/volume/__tests__/volumeFixture.ts | 13 +- .../volume/__tests__/volumeLayout.spec.ts | 522 +------ packages/dicom/core/volume/allocateVolume.ts | 31 +- packages/dicom/core/volume/loadVolume.ts | 157 ++- packages/dicom/core/volume/nmGeometry.ts | 1 - packages/dicom/core/volume/pixelFormat.ts | 81 +- packages/dicom/core/volume/pixelValidation.ts | 13 - .../dicom/core/volume/ultrasoundSpacing.ts | 61 +- packages/dicom/core/volume/volumeLayout.ts | 150 +- .../dicom/vtk/__tests__/thumbnail.spec.ts | 49 +- .../dicom/vtk/__tests__/volumeImage.spec.ts | 16 + packages/dicom/vtk/thumbnail.ts | 13 +- packages/dicom/vtk/volumeImage.ts | 11 +- scripts/checks/conventions.mjs | 1 - ...tientStudyVolumeBrowser.thumbnails.spec.ts | 14 +- src/core/cine/DicomCineImage.ts | 9 - src/core/cine/__tests__/cineInstance.spec.ts | 25 - src/core/cine/cineInstance.ts | 47 +- .../__tests__/cachedStreamFetcher.spec.ts | 197 +-- .../__tests__/dicomVolumeImage.spec.ts | 136 +- src/core/streaming/cachedStreamFetcher.ts | 308 +--- .../dicom/__tests__/octMetadata.spec.ts | 109 +- .../__tests__/octStructuredMetadata.spec.ts | 106 -- src/core/streaming/dicom/octDataset.ts | 21 - src/core/streaming/dicom/octMetadata.ts | 48 +- src/core/streaming/dicomVolumeImage.ts | 12 +- src/core/streaming/httpCodes.ts | 2 - src/core/streaming/types.ts | 9 - src/enface/__tests__/seriesGeometry.spec.ts | 4 +- src/enface/availability.ts | 4 +- src/enface/occupiedDepthSupport.ts | 4 +- .../readDicomTags.differential.spec.ts | 51 - src/io/__tests__/readDicomTags.spec.ts | 469 ------- src/io/__tests__/readDicomTagsFixtures.ts | 5 - .../__tests__/dicomImportResults.spec.ts | 92 -- .../__tests__/dicomInstanceProvenance.spec.ts | 78 -- .../importDicomInstanceSources.spec.ts | 233 +++ src/io/import/importDataSources.ts | 132 +- .../processors/__tests__/handleDicom.spec.ts | 24 +- .../import/processors/extractArchiveTarget.ts | 42 - src/io/itk/worker.ts | 29 +- src/io/readDicomTags.ts | 102 -- src/io/zip.ts | 16 - .../datasets-dicom-acquisition-split.spec.ts | 129 +- .../__tests__/datasets-dicom-cine.spec.ts | 66 +- .../__tests__/datasets-dicom-geometry.spec.ts | 13 +- .../__tests__/datasets-dicom-reimport.spec.ts | 25 +- .../datasets-dicom-transaction.spec.ts | 313 +---- src/store/__tests__/dicomImportFixtures.ts | 66 + src/store/__tests__/image-cache.spec.ts | 28 +- src/store/datasets-dicom.ts | 211 ++- src/store/datasets-layers.ts | 2 +- src/store/image-cache.ts | 8 +- src/utils/parseContentRangeHeader.ts | 40 - tests/datasets.ts | 5 +- tests/dicomCompositionCorpus.json | 376 +---- tests/dicomPages.ts | 5 +- tests/dicomVolumeCorpus.json | 1247 ++++++----------- tests/fixtures/dicom-pages/composition.ts | 5 +- tests/fixtures/dicom-pages/corpus.ts | 33 +- .../fixtures/dicom-pages/enhancedFixtures.ts | 30 +- tests/fixtures/dicom-pages/loadVolume.ts | 17 +- tests/fixtures/dicom-pages/parity.ts | 9 +- tests/fixtures/dicom-pages/server.mjs | 44 +- tests/fixtures/dicom-pages/shared.ts | 2 +- .../dicom-pages/volumeCorpusReference.py | 86 ++ tests/nativePixelDicom.ts | 15 +- tests/pageobjects/volview.page.ts | 65 +- tests/specs/crosshairs-multi-image.e2e.ts | 5 +- tests/specs/dicom-dimension-mismatch.e2e.ts | 83 +- tests/specs/dicom-frame-reconstruction.e2e.ts | 101 +- tests/specs/dicom-import-regressions.e2e.ts | 91 +- tests/specs/dicom-japanese-name.e2e.ts | 109 +- tests/specs/dicom-modality-rescale.e2e.ts | 65 - tests/specs/dicom-module-pages.e2e.ts | 59 +- tests/specs/dicom-native-parity.e2e.ts | 102 +- tests/specs/dicom-spacing-details.e2e.ts | 35 +- tests/specs/dicom-volume-composition.e2e.ts | 45 +- tests/specs/dicom-volume-corpus.e2e.ts | 67 +- tests/specs/dicomElementFixtures.ts | 43 +- tests/specs/dicomRenderedSlice.ts | 56 +- tests/specs/imageCacheUtils.ts | 45 +- .../incremental-positionless-import.e2e.ts | 109 +- tests/specs/multi-acquisition-series.e2e.ts | 78 -- tests/specs/pet-ct-sample.e2e.ts | 8 +- tests/specs/sample-rendering.e2e.ts | 23 +- .../specs/session-overlapping-imports.e2e.ts | 54 +- tests/specs/syntheticDicom.ts | 17 +- tests/specs/utils.ts | 55 + tests/unit/octFixture.ts | 20 +- tsconfig.json | 16 +- vite.config.ts | 3 - 160 files changed, 4590 insertions(+), 8747 deletions(-) delete mode 100644 packages/dicom/core/collections/__tests__/dicomTags.spec.ts create mode 100644 packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts delete mode 100644 packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts delete mode 100644 packages/dicom/core/instance/__tests__/readInstance.spec.ts create mode 100644 packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts delete mode 100644 packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts rename packages/dicom/core/{metadata => runtime}/__tests__/metadataReader.spec.ts (78%) create mode 100644 packages/dicom/core/volume/__tests__/enhancedFixture.ts rename packages/dicom/core/volume/__tests__/{functionalGroups.spec.ts => frameGeometry.spec.ts} (59%) create mode 100644 packages/dicom/core/volume/__tests__/pixelFormat.spec.ts delete mode 100644 src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts delete mode 100644 src/core/streaming/dicom/octDataset.ts delete mode 100644 src/io/__tests__/readDicomTags.differential.spec.ts delete mode 100644 src/io/__tests__/readDicomTags.spec.ts delete mode 100644 src/io/__tests__/readDicomTagsFixtures.ts delete mode 100644 src/io/import/__tests__/dicomImportResults.spec.ts delete mode 100644 src/io/import/__tests__/dicomInstanceProvenance.spec.ts create mode 100644 src/io/import/__tests__/importDicomInstanceSources.spec.ts delete mode 100644 src/io/import/processors/extractArchiveTarget.ts delete mode 100644 src/io/readDicomTags.ts delete mode 100644 src/utils/parseContentRangeHeader.ts create mode 100644 tests/fixtures/dicom-pages/volumeCorpusReference.py delete mode 100644 tests/specs/dicom-modality-rescale.e2e.ts delete mode 100644 tests/specs/multi-acquisition-series.e2e.ts diff --git a/packages/dicom/README.md b/packages/dicom/README.md index 9f0202dbd..a2ffa62e6 100644 --- a/packages/dicom/README.md +++ b/packages/dicom/README.md @@ -83,13 +83,18 @@ if (update.kind === 'image') { ## Sources A `ByteSource` opens a fresh stream for every `read(signal, range?)` and -holds nothing open between reads. `fromBlob` reads slices of a Blob or File. +holds nothing open between reads. `fromBlob` reads a Blob or File: a range +with an end in one slice, an open read in slices that double from 64 KiB, +since each slice costs a turn of the calling thread. `fromUrl` issues HTTP Range requests and accepts a server that ignores Range; pass `runtime.fetch` so requests share the runtime's pool, or any `fetch` for authentication and other request policies. Its `rangeSupport()` reports whether the latest ranged response honoured Range. Ranged URL reads bypass the HTTP cache, since Chrome can answer a Range from an entry an earlier cancelled -read left behind with status 200 and only the range's bytes. +read left behind with status 200 and only the range's bytes. A status other +than 200, 206 or 416 fails with `HTTP for `. The `fetch` it was +given sees its signal abort once a body has been read to the end, which is how +a pooled request is released. `readBytes(source, signal, range?)` reads a source or a range into memory. Instances keep no bytes; read the source again when the original bytes are needed. @@ -100,14 +105,17 @@ needed. thread, stopping where Pixel Data begins, parses the dataset in a worker and returns a frozen `Instance`: its source, dataset, Part 10 layout, transfer syntax, ultrasound regions and where the Pixel Data element and its value sit. -`readInstance` does both on the calling thread. +The free function `readInstance(source, signal)` does both on the calling +thread. A source without a preamble or file meta information is read with its transfer syntax assumed and reported in `layout`. The runtime's `imageImportPolicy: 'skip-radiotherapy'` returns after the Modality element of RT objects; `'complete-header'` (the default) reads through the header. The dataset omits private elements, including those nested in public -sequences; `readDicomDataset(bytes)` reads every element of a Part 10 file. +sequences; `readDicomDataset(bytes)` reads every element before Pixel Data, +private ones included, from a file with or without the Part 10 preamble and +file meta information. `getDatasetTag(dataset, tag)` returns an element's values as backslash separated text, `getDatasetModality` the trimmed Modality, `sequenceItems` the items of a sequence, and `trimDicomPadding` strips the space and NUL @@ -119,35 +127,39 @@ reads every item of the Sequence of Ultrasound Regions. `registerInstances(state, instances)` is a pure reducer. It returns the next `state`; `updates`, the collections of each touched series that are new or -changed, or that the batch re-supplied a member of; `removed`, the committed -ids a replan dissolved; and `conflictingInstanceUids`, SOP Instance UIDs -re-supplied with different geometry. The first registration of a SOP Instance -UID is kept; instances without one are identified by object. Abandoning an -import is not assigning the returned state. +changed, whose label or warnings changed, or that the batch re-supplied a +member of; `removed`, the committed ids a replan dissolved; and +`conflictingInstanceUids`, SOP Instance UIDs re-supplied with different header +facts. The first registration of a SOP Instance UID is kept; instances without +one are identified by object. Abandoning an import is not assigning the +returned state. Register a series in batches: each call replans every series +the batch touches. Each `InstanceCollectionUpdate` carries a stable `id` that starts with the -Series Instance UID, its `seriesKey`, the planned `collection`, `members` in -planned order and, aligned with them, `provenance`: the batch's own instance -wherever it re-supplied one. `kind` is `image`, or `segmentation` when the -first member's Modality is SEG; a segmentation reader turns those labels into -its own image. `change` says how the collection differs from what was last -committed under its id: `new`, `unchanged` (same members, key and geometry) or -`changed`. +Series Instance UID, the planned `collection`, `members` in planned order and, +aligned with them, `provenance`: the batch's own instance wherever it +re-supplied one. `kind` is `image`, or `segmentation` when the first member's +Modality is SEG; a segmentation reader turns those labels into its own image. +`change` says how the collection differs from what was last committed under +its id: `new`, `unchanged` (same members and geometry, so an allocated volume +stands; it is still reported when its label or warnings changed) or `changed`. +A collection's `label` names what separated it from the rest of its series and +is null when nothing did. `forgetCollection(state, id)` drops a collection and its instances, so a later import plans them afresh. `seriesKeyOf` gives the series an instance plans in. ## Volumes and loading -`allocateVolume(update, options?, previous?)` allocates the `Volume` an image -collection fills: a typed array, dimensions, components, origin, row-major -direction, spacing, spatial metadata, reconstruction, members, allocation -warnings and a per-slice `loaded` mask. With `previous`, slices it already -decoded are copied by instance identity, so growing a volume never decodes -them again. `irregularGeometry: 'preserve-order'` (the default) keeps -approximate spacing for irregular stacks; `'reject'` refuses them. Neither -resamples. Slots must start at zero because the first member anchors the -origin; gaps such as `[0, 2]` are allowed. +`allocateVolume(update, previous?)` allocates the `Volume` an image collection +fills: a typed array, dimensions, components, origin, row-major direction, +spacing, spatial metadata, members, allocation warnings and a per-slice +`loaded` mask. With `previous`, slices it already decoded are copied by +instance identity, so growing a volume never decodes them again. In a +multi-file volume member i fills slice i. An irregular stack keeps its planned +order with approximate spacing and is not resampled; +`volume.spatialMetadata.reconstruction` says whether a volume is regular and, +when it is not, why. The buffer type comes from the headers' rescaled value ranges (`getVolumeBufferType(instancePixelFormats(dataset))` for one instance). @@ -162,13 +174,19 @@ generator of `{ slot, extent, range }` or `{ slot, extent, error }` updates. It writes each unit's samples into `volume.data` as soon as they decode, and marks its slices in `volume.loaded` only when its update is yielded, so a consumer that awaits between updates never holds up decoding and never sees a -slice loaded before its update. Nothing is written after the load stops. A -failure's extent spans the slices it leaves unloaded, and loading continues. -Units load focus first, then coarse to fine across the stack; `focus` -(default `() => middleSlot(volume)`) is a function called before every read -and decode, so moving the focus reorders the remaining work. At most -`readAhead` units, defaulting to the runtime's `readConcurrency`, are being -read or waiting to decode, and at most `decodeConcurrency` decode at once. Aborting `signal`, leaving the loop or +slice loaded before its update. Decodes that return synchronously run back to +back for a few milliseconds and then hand the thread back, so a batch of +frames read at once does not hold it. +Nothing is written after the load stops. A failure's extent spans the slices +it leaves unloaded, and loading continues. Its message names the file, and the +frame when it lost one, and says whether it could not be read or decoded; the +thrown value is its `cause`. A file cut short loads the frames it +still holds and fails the rest. Units load focus first, then coarse to fine +across the stack; `focus` (default `() => middleSlot(volume)`) is a function +called before every read and decode, so moving the focus reorders the +remaining work. At most `readAhead` units, defaulting to the runtime's +`readConcurrency`, are being read or waiting to decode, and at most +`decodeConcurrency` decode at once. Aborting `signal`, leaving the loop or disposing the runtime ends the iteration without throwing. ## Decoders @@ -177,7 +195,9 @@ A `PixelDecoder` has a `name` and a `plan(instance, target)` that, from the header alone, returns the `DecodeUnit`s it would load the instance in, or `{ declined: reason }`. A unit covers consecutive frames: `firstFrame`, `frames`, the byte `range` of the source to read (null for the whole source) -and `decode(bytes, signal)`, which returns `DecodedPixels`. A decoder's units +and `decode(bytes, signal)`, which returns `DecodedPixels`. `bytes` may view a +buffer other units share, so a decoder transfers it only when it spans its +whole buffer. A decoder's units must cover the instance's frames exactly once, in any order; otherwise every slice of that instance fails with an error naming the decoder. Every unit is read, decoded, validated and written the same way. @@ -197,9 +217,10 @@ accepts only instances whose result is identical to GDCM's: MONOCHROME2 or unscaled unsigned 8 bit RGB samples, 8, 16 or 32 bit words with Bits Stored ending at High Bit (fewer stored bits only in 16 bit words), big endian only for 16 bit words, one modality rescale for all frames, and no overlay, curve, -Modality LUT, palette or ICC data. GDCM plans the whole instance as one unit. Both -apply one modality transform to the entire instance and reject differing -per-frame slopes or intercepts. Once a URL source shows that its server +Modality LUT, palette or ICC data. GDCM plans the whole instance as one unit. +Both apply one modality transform to the entire instance and decline, from the +header, an instance whose frames differ in slope or intercept. Once a URL +source shows that its server ignores Range, the remaining ranged units of that instance come from one read instead of one download each. @@ -235,9 +256,9 @@ pad byte. ## Runtime `createDicomRuntime(options)` owns the request pool (`requestConcurrency`, -default 24, exposed as `readConcurrency`), the metadata parser workers -(`metadataConcurrency`, default 2, or `metadataWorkerFactory` for another -asset layout) and the GDCM decoder, which runs at most `decodeConcurrency` +default 24, exposed as `readConcurrency`), two metadata parser workers +(`metadataWorkerFactory` for another asset layout; its worker exposes +`readPublicDataset`) and the GDCM decoder, which runs at most `decodeConcurrency` workers at once (default half the cores, at most four; each worker carries its own WASM heap) and terminates a worker whose decode is aborted. `assets` locates the ITK pipeline worker and the GDCM image reader; reading headers @@ -252,8 +273,8 @@ copying; before any slice decodes its scalar range is a 0 to 255 placeholder. `applyVolumeUpdate(image, update)` widens the scalar range by a decoded unit and marks the image modified. `sliceThumbnail(image, slice)` downsamples one slice to at most 256 pixels on its longer side and windows it to an 8 bit -greyscale `ThumbnailSlice` on the loaded range, or on luminance across the -volume for color. `encodeThumbnailToUri` turns a thumbnail into a PNG data +greyscale `ThumbnailSlice` on the loaded range, or on the slice's own +luminance for color. `encodeThumbnailToUri` turns a thumbnail into a PNG data URI. ## Byte streaming @@ -306,19 +327,22 @@ module through the entry points, as the app does. - `dicom-volume-corpus.e2e.ts` loads pinned public CT, MR and SPECT files through File and HTTP sources, plus numeric-padding fixtures, and checks dimensions, physical geometry, explicit unsupported-topology errors and the - hash of every calibrated voxel. Inputs, checksums, independently decoded - hashes and provenance are in `tests/dicomVolumeCorpus.json`. + hash of every calibrated voxel. One multiframe file is also read from a + route that ignores Range. Inputs, checksums, independently decoded hashes + and provenance are in `tests/dicomVolumeCorpus.json`; + `volumeCorpusReference.py` beside the pages checks dimensions, ranges and + hashes with pydicom and NumPy. - `dicom-native-parity.e2e.ts` decodes synthesized instances across the native - format matrix and every cached uncompressed dataset through GDCM and frame by - frame natively, from File and HTTP sources. Wherever the table plans native + format matrix and a sample of cached public files through GDCM and frame by + frame natively, over HTTP. Wherever the table plans native frames, both must write identical samples, which for a fractional rescale means equal after the same float32 rounding. - `dicom-volume-composition.e2e.ts` composes downloaded classic CT and PET series and two MR acquisitions sharing one Series UID, and checks every collection's ordered SOP membership, calibrated voxel hash and physical - geometry after shuffled batch and incremental File and HTTP imports. - `tests/dicomCompositionCorpus.json` records the inputs and expectations; - `compositionReference.py` beside the pages reproduces them with pydicom and - NumPy. + geometry after a shuffled batch import from Files and a shuffled incremental + import over HTTP. `tests/dicomCompositionCorpus.json` records the inputs and + expectations; `compositionReference.py` beside the pages checks them with + pydicom and NumPy. - `dicom-frame-reconstruction.e2e.ts` and `dicom-spacing-details.e2e.ts` check multiframe reconstruction and spacing reports. diff --git a/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts b/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts index 6efd79e2f..a85ae6f7a 100644 --- a/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts +++ b/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts @@ -1,14 +1,11 @@ import { describe, it, expect } from 'vitest'; import { assignIds, encodeCollectionKey } from '../assignCollectionIds'; import type { CommittedCollection } from '../assignCollectionIds'; -import { - ORIENTATION_TOLERANCE, - planDicomCollections, -} from '../planDicomCollections'; +import { ORIENTATION_TOLERANCE } from '../orientation'; +import { planDicomCollections } from '../planDicomCollections'; import type { CollectionKey, DicomCollection } from '../planDicomCollections'; import { IDENTITY_ORIENTATION, - clone, makeFacts, tiltedOrientation, } from './instanceFactsFixture'; @@ -33,32 +30,18 @@ const collectionOf = ( ): DicomCollection => ({ key, members: uids.map((uid) => makeFacts(uid)), - order: 'spatial', - reconstruction: { - kind: 'regular', - sliceSpacing: null, - slots: uids.map((_, index) => index), - }, + reconstruction: { kind: 'regular', sliceSpacing: null }, orientation: [1, 0, 0, 0, 1, 0], label: null, - diagnostics: [], warnings: [], }); -const planOf = (...collections: DicomCollection[]) => ({ collections }); - const idsOf = (collections: Array<{ id: string }>) => collections.map((c) => c.id); describe('encodeCollectionKey', () => { - it('encodes equal keys identically', () => { - expect(encodeCollectionKey(keyOf('1,0,0,0,1,0'))).toBe( - encodeCollectionKey(keyOf('1,0,0,0,1,0')) - ); - }); - // The structured key this encodes: the same characters the encoding joins on, - // smuggled inside a series key, a rule name or a value. + // smuggled inside a series key or a value. const structured: CollectionKey = { seriesKey: SERIES_KEY, parts: [ @@ -72,10 +55,6 @@ describe('encodeCollectionKey', () => { 'the series key', { seriesKey: `${SERIES_KEY}|rows=.4`, parts: [['columns', '8']] }, ], - [ - 'a rule name', - { seriesKey: SERIES_KEY, parts: [['rows=.4|columns', '8']] }, - ], ['a value', { seriesKey: SERIES_KEY, parts: [['rows', '4|columns=.8']] }], ]; @@ -100,52 +79,24 @@ describe('encodeCollectionKey', () => { expect(new Set(encodings).size).toBe(literals.length); }); - - it('separates keys differing only in series key or rule name', () => { - const base: CollectionKey = { - seriesKey: 'series-1', - parts: [['rows', '4']], - }; - const otherSeries: CollectionKey = { - seriesKey: 'series-2', - parts: [['rows', '4']], - }; - const otherRule: CollectionKey = { - seriesKey: 'series-1', - parts: [['columns', '4']], - }; - - const encodings = [base, otherSeries, otherRule].map(encodeCollectionKey); - - expect(new Set(encodings).size).toBe(3); - }); }); describe('assignIds', () => { it('mints the encoded key when nothing is committed', () => { const collection = collectionOf(['a', 'b']); - const { collections } = assignIds(planOf(collection), []); + const collections = assignIds([collection], []); expect(collections[0].id).toBe(encodeCollectionKey(collection.key)); }); - it('gives distinct collections distinct ids', () => { - const first = collectionOf(['a'], keyOf('1,0,0,0,1,0')); - const second = collectionOf(['b'], keyOf('0,1,0,0,0,1')); - - const { collections } = assignIds(planOf(first, second), []); - - expect(new Set(idsOf(collections)).size).toBe(2); - }); - it('keeps the committed id when key and members are unchanged', () => { const collection = collectionOf(['a', 'b']); const committed: CommittedCollection[] = [ { id: 'visible-1', sopInstanceUids: ['a', 'b'] }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).toBe('visible-1'); }); @@ -172,7 +123,7 @@ describe('assignIds', () => { planDicomCollections({ seriesKey: SERIES_KEY, instances: firstBatch }), [] ); - const committed = before.collections.map((collection) => ({ + const committed = before.map((collection) => ({ id: collection.id, sopInstanceUids: collection.members.flatMap((member) => member.sopInstanceUid === null ? [] : [member.sopInstanceUid] @@ -186,14 +137,12 @@ describe('assignIds', () => { committed ); - expect(after.collections).toHaveLength(1); - expect(encodeCollectionKey(after.collections[0].key)).not.toBe( - encodeCollectionKey(before.collections[0].key) - ); - expect(after.collections[0].id).toBe(before.collections[0].id); - expect(after.collections[0].id).not.toBe( - encodeCollectionKey(after.collections[0].key) + expect(after).toHaveLength(1); + expect(encodeCollectionKey(after[0].key)).not.toBe( + encodeCollectionKey(before[0].key) ); + expect(after[0].id).toBe(before[0].id); + expect(after[0].id).not.toBe(encodeCollectionKey(after[0].key)); }); it('gives a committed id to the collection holding most of its members', () => { @@ -203,7 +152,7 @@ describe('assignIds', () => { { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, ]; - const { collections } = assignIds(planOf(majority, remainder), committed); + const collections = assignIds([majority, remainder], committed); expect(collections[0].id).toBe('visible-1'); expect(collections[1].id).not.toBe('visible-1'); @@ -216,7 +165,7 @@ describe('assignIds', () => { { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, ]; - const { collections } = assignIds(planOf(left, right), committed); + const collections = assignIds([left, right], committed); expect(idsOf(collections)).not.toContain('visible-1'); expect(new Set(idsOf(collections)).size).toBe(2); @@ -228,7 +177,7 @@ describe('assignIds', () => { { id: 'visible-1', sopInstanceUids: ['x', 'y'] }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).not.toBe('visible-1'); expect(collections[0].id).toBe(encodeCollectionKey(collection.key)); @@ -243,7 +192,7 @@ describe('assignIds', () => { }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).not.toBe(committed[0].id); }); @@ -255,7 +204,7 @@ describe('assignIds', () => { { id: 'large', sopInstanceUids: ['c', 'd', 'e'] }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).toBe('large'); }); @@ -267,7 +216,7 @@ describe('assignIds', () => { { id: 'alpha', sopInstanceUids: ['c', 'd'] }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).toBe('alpha'); }); @@ -278,7 +227,7 @@ describe('assignIds', () => { { id: 'visible-1', sopInstanceUids: ['a'] }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).toBe('visible-1'); }); @@ -289,43 +238,8 @@ describe('assignIds', () => { { id: 'visible-1', sopInstanceUids: ['a'] }, ]; - const { collections } = assignIds(planOf(collection), committed); + const collections = assignIds([collection], committed); expect(collections[0].id).not.toBe('visible-1'); }); - - it('carries the planned collections through in order, only adding an id', () => { - const first = collectionOf(['a'], keyOf('1,0,0,0,1,0')); - const second: DicomCollection = { - ...collectionOf(['b'], keyOf('0,1,0,0,0,1')), - order: 'instance-number', - diagnostics: ['b has no position'], - }; - - const { collections } = assignIds(planOf(first, second), []); - - expect(collections).toHaveLength(2); - expect(collections[0].key).toEqual(first.key); - expect(collections[0].members).toEqual(first.members); - expect(collections[1].order).toBe('instance-number'); - expect(collections[1].diagnostics).toEqual(['b has no position']); - expect(collections[1].members[0]).toBe(second.members[0]); - }); - - it('does not mutate the plan or the committed collections', () => { - const plan = planOf( - collectionOf(['a', 'b'], keyOf('1,0,0,0,1,0')), - collectionOf(['c'], keyOf('0,1,0,0,0,1')) - ); - const committed: CommittedCollection[] = [ - { id: 'visible-1', sopInstanceUids: ['a', 'b'] }, - ]; - const planBefore = clone(plan); - const committedBefore = clone(committed); - - assignIds(plan, committed); - - expect(clone(plan)).toEqual(planBefore); - expect(clone(committed)).toEqual(committedBefore); - }); }); diff --git a/packages/dicom/core/collections/__tests__/dicomTags.spec.ts b/packages/dicom/core/collections/__tests__/dicomTags.spec.ts deleted file mode 100644 index d808e36d0..000000000 --- a/packages/dicom/core/collections/__tests__/dicomTags.spec.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { Tags } from '../../metadata/dicomTags'; - -describe('dicomTags', () => { - it.each([ - ['SliceThickness', '0018|0050'], - ['SequenceName', '0018|0024'], - ['SeriesDate', '0008|0021'], - ])('names %s', (name, tag) => { - expect(Tags[name]).toBe(tag); - }); -}); diff --git a/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts b/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts index 4d87b9fd4..0c37f42d5 100644 --- a/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts +++ b/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts @@ -3,7 +3,7 @@ import { Tags } from '../../metadata/dicomTags'; /** * Real Imaging Data Commons (IDC) series behind the acquisition-split rules. * - * Entries are keyed by SeriesInstanceUID: bucket paths, folder UUIDs, and + * Each fixture names its SeriesInstanceUID: bucket paths, folder UUIDs, and * portal URLs all change between IDC releases, the UID does not. Fetch one by * searching the UID at portal.imaging.datacommons.cancer.gov, or with the * idc-index package: @@ -12,7 +12,7 @@ import { Tags } from '../../metadata/dicomTags'; * IDCClient().download_from_selection( * seriesInstanceUID='', downloadDir='.') * - * `groups` mirrors the real per-group tag values and slice layout, with + * The groups mirror the real per-group tag values and slice layout, with * positions projected onto the slice normal, in mm. */ @@ -23,98 +23,53 @@ export type SliceGroup = { zs: number[]; }; -export type IdcSeriesFixture = { - seriesInstanceUID: string; - seriesDescription: string; - vendor: string; - /** What the series is and why it forces the rule it tests. */ - why: string; - groups?: SliceGroup[]; -}; - const steps = (start: number, count: number, step: number) => Array.from({ length: count }, (_, i) => start + i * step); -export const dceEightPhase: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.7695.4164.334885423614895574619945040495', - seriesDescription: 'ISPY2: VOLSER: uni-lateral cropped: original DCE', - vendor: 'GE', - why: - 'DCE breast MR: eight timepoints re-scan one identical 80-slice Z range ' + - 'in a single series. No AcquisitionNumber at all; only ' + - 'TemporalPositionIdentifier separates the timepoints. Loaded merged, ' + - 'every position appears eight times.', - groups: steps(0, 8, 1).map((phase) => ({ - tags: { [Tags.TemporalPositionIdentifier]: String(phase) }, - zs: steps(-81.198, 80, 2.0), - })), -}; +// 1.3.6.1.4.1.14519.5.2.1.7695.4164.334885423614895574619945040495 +// "ISPY2: VOLSER: uni-lateral cropped: original DCE" (GE). DCE breast MR: +// eight timepoints re-scan one identical 80-slice Z range in a single series. +// No AcquisitionNumber at all; only TemporalPositionIdentifier separates the +// timepoints. Loaded merged, every position appears eight times. +export const dceEightPhase: SliceGroup[] = steps(0, 8, 1).map((phase) => ({ + tags: { [Tags.TemporalPositionIdentifier]: String(phase) }, + zs: steps(-81.198, 80, 2.0), +})); -export const dceSevenPhasePhilips: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.7695.4164.327395145625810010102069976322', - seriesDescription: 'ISPY2: 15ML OMNI T1 FS DYN SENSE 5', - vendor: 'Philips', - why: - 'DCE breast MR: seven timepoints (TemporalPositionIdentifier 1 through ' + - '7), 158 slices each over one Z range. Shows the split holds across ' + - 'vendors and with 1-based numbering.', - groups: steps(1, 7, 1).map((phase) => ({ - tags: { [Tags.TemporalPositionIdentifier]: String(phase) }, - zs: steps(-83.107, 158, 1.0), - })), -}; +// 1.3.6.1.4.1.14519.5.2.1.9203.4004.413147664284321913537786821717 +// "T1 AX IN_OUT_160 TR MBH" (Siemens). In-phase/opposed-phase Dixon in one +// series: two echoes (TE 2.4/5.04) over one identical 34-slice range, one +// AcquisitionNumber, no TemporalPositionIdentifier. Only EchoNumbers separates +// them: SequenceName is *fl2d2 for both echoes. +export const dixonDualEcho: SliceGroup[] = ['1', '2'].map((echo) => ({ + tags: { + [Tags.AcquisitionNumber]: '1', + [Tags.EchoNumbers]: echo, + }, + zs: steps(-107.502, 34, 7.8), +})); -export const dixonDualEcho: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.9203.4004.413147664284321913537786821717', - seriesDescription: 'T1 AX IN_OUT_160 TR MBH', - vendor: 'Siemens', - why: - 'In-phase/opposed-phase Dixon in one series: two echoes (TE 2.4/5.04) ' + - 'over one identical 34-slice range, one AcquisitionNumber, no ' + - 'TemporalPositionIdentifier. Only EchoNumbers separates them; the ' + - 'categorize pipeline cannot (SequenceName is *fl2d2 for both echoes).', - groups: ['1', '2'].map((echo) => ({ - tags: { - [Tags.AcquisitionNumber]: '1', - [Tags.EchoNumbers]: echo, - }, - zs: steps(-107.502, 34, 7.8), - })), -}; - -export const dixonUnevenEchoes: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.1620.1226.196512451812657389463383990773', - seriesDescription: 'AXL_IN_OUT_ABD', - vendor: 'Siemens', - why: - 'Dixon dual-echo where echo 1 has 13 slices and echo 2 has 12 over the ' + - 'same range; unequal group sizes must still split.', - groups: [ - { - tags: { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: '1' }, - zs: steps(0, 13, 7.8), - }, - { - tags: { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: '2' }, - zs: steps(0, 12, 7.8), - }, - ], -}; +// 1.3.6.1.4.1.14519.5.2.1.1620.1226.196512451812657389463383990773 +// "AXL_IN_OUT_ABD" (Siemens). Dixon dual-echo where echo 1 has 13 slices and +// echo 2 has 12 over the same range; unequal group sizes must still split. +export const dixonUnevenEchoes: SliceGroup[] = [ + { + tags: { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: '1' }, + zs: steps(0, 13, 7.8), + }, + { + tags: { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: '2' }, + zs: steps(0, 12, 7.8), + }, +]; -export const dwiMultiBValue: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.7695.4164.198361347871486858845671445367', - seriesDescription: 'ACRIN-6698: DWI_Multi_bValue', - vendor: 'Philips', - why: - 'Diffusion MR: 30 positions repeated at b-values 0, 100, 600, and 800. ' + - 'AcquisitionNumber, TemporalPositionIdentifier, and EchoNumbers are ' + - 'constant, so DiffusionBValue is the only standard discriminator.', - groups: [0, 100, 600, 800].map((bValue) => ({ +// 1.3.6.1.4.1.14519.5.2.1.7695.4164.198361347871486858845671445367 +// "ACRIN-6698: DWI_Multi_bValue" (Philips). Diffusion MR: 30 positions +// repeated at b-values 0, 100, 600, and 800. AcquisitionNumber, +// TemporalPositionIdentifier, and EchoNumbers are constant, so DiffusionBValue +// is the only standard discriminator. +export const dwiMultiBValue: SliceGroup[] = [0, 100, 600, 800].map( + (bValue) => ({ tags: { [Tags.AcquisitionNumber]: '6', [Tags.TemporalPositionIdentifier]: '1', @@ -122,81 +77,62 @@ export const dwiMultiBValue: IdcSeriesFixture = { [Tags.DiffusionBValue]: String(bValue), }, zs: steps(-67.0785, 30, 4.0), - })), -}; + }) +); -export const bilateralSagittalSlabs: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.66737955842913643997059729379406867951', - seriesDescription: 'ISPY2: SAG IR', - vendor: 'GE', - why: - 'Bilateral sagittal breast slabs: StackID 1 and 2 cover two 4mm stacks ' + - 'with a 42mm gap, one orientation, one acquisition, all positions ' + - 'distinct. This series is why StackID is NOT a split discriminator: ' + - 'nothing overlaps, so the overlap gate keeps a StackID-like tag from ' + - 'tearing it apart. One collection is not one regular volume, though: no ' + - 'even lattice holds both slabs, so the reconstruction reports an ' + - 'irregular stack and warns, rather than fitting the endpoints to a ' + - 'fabricated 4.59mm spacing.', - groups: [ - { - tags: { [Tags.AcquisitionNumber]: '1', '0020|9056': '1' }, - zs: steps(-156.488, 31, 4.0), - }, - { - tags: { [Tags.AcquisitionNumber]: '1', '0020|9056': '2' }, - zs: steps(5.951, 35, 4.0), - }, - ], -}; +// 1.3.6.1.4.1.14519.5.2.1.66737955842913643997059729379406867951 +// "ISPY2: SAG IR" (GE). Bilateral sagittal breast slabs: StackID 1 and 2 cover +// two 4mm stacks with a 42mm gap, one orientation, one acquisition, all +// positions distinct. This series is why StackID is NOT a split discriminator: +// nothing overlaps, so the overlap gate keeps a StackID-like tag from tearing +// it apart. One collection is not one regular volume, though: no even lattice +// holds both slabs, so the reconstruction reports an irregular stack and +// warns, rather than fitting the endpoints to a fabricated 4.59mm spacing. +export const bilateralSagittalSlabs: SliceGroup[] = [ + { + tags: { [Tags.AcquisitionNumber]: '1', '0020|9056': '1' }, + zs: steps(-156.488, 31, 4.0), + }, + { + tags: { [Tags.AcquisitionNumber]: '1', '0020|9056': '2' }, + zs: steps(5.951, 35, 4.0), + }, +]; -export const partialTemporalTags: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.7695.4164.232713885104107279235403827078', - seriesDescription: 'ISPY2: Ax Vibrant PRE/POST', - vendor: 'GE', - why: - 'Seven acquisitions re-scanning one range, but ' + - 'TemporalPositionIdentifier is present on only part of the slices. ' + - 'AcquisitionNumber must do the split, and the incomplete temporal tag ' + - 'must not sub-split or block anything.', - groups: [ - { - tags: { - [Tags.AcquisitionNumber]: '1', - [Tags.TemporalPositionIdentifier]: '1', - }, - zs: steps(-60, 36, 2.0), +// 1.3.6.1.4.1.14519.5.2.1.7695.4164.232713885104107279235403827078 +// "ISPY2: Ax Vibrant PRE/POST" (GE). Seven acquisitions re-scanning one range, +// but TemporalPositionIdentifier is present on only part of the slices. +// AcquisitionNumber must do the split, and the incomplete temporal tag must +// not sub-split or block anything. +export const partialTemporalTags: SliceGroup[] = [ + { + tags: { + [Tags.AcquisitionNumber]: '1', + [Tags.TemporalPositionIdentifier]: '1', }, - // The rest of acquisition 1 carries no temporal tag at all. - { tags: { [Tags.AcquisitionNumber]: '1' }, zs: steps(12, 36, 2.0) }, - ...steps(2, 6, 1).map((acq) => ({ - tags: { - [Tags.AcquisitionNumber]: String(acq), - [Tags.TemporalPositionIdentifier]: String(acq), - }, - zs: steps(-60, 72, 2.0), - })), - ], -}; - -export const doubledAcquisition: IdcSeriesFixture = { - seriesInstanceUID: - '1.3.6.1.4.1.14519.5.2.1.7695.1700.103847508594300579711113977161', - seriesDescription: 'IR-SPGR-SAG', - vendor: 'GE', - why: - 'Acquisition 1 holds 74 slices; acquisition 2 holds 148 slices at those ' + - 'same 74 positions. The split is right and the acquisition-2 volume must ' + - 'still carry the duplicate-position warning. Same shape in IDC series ' + - '1.3.6.1.4.1.14519.5.2.1.7695.2311.133871731749882407434486842181 ' + - '(LEFT - Dynamic-3dfgre, acquisition values 0 and 2).', - groups: [ - { tags: { [Tags.AcquisitionNumber]: '1' }, zs: steps(-214.177, 74, 2.5) }, - { - tags: { [Tags.AcquisitionNumber]: '2' }, - zs: [...steps(-214.177, 74, 2.5), ...steps(-214.177, 74, 2.5)], + zs: steps(-60, 36, 2.0), + }, + // The rest of acquisition 1 carries no temporal tag at all. + { tags: { [Tags.AcquisitionNumber]: '1' }, zs: steps(12, 36, 2.0) }, + ...steps(2, 6, 1).map((acq) => ({ + tags: { + [Tags.AcquisitionNumber]: String(acq), + [Tags.TemporalPositionIdentifier]: String(acq), }, - ], -}; + zs: steps(-60, 72, 2.0), + })), +]; + +// 1.3.6.1.4.1.14519.5.2.1.7695.1700.103847508594300579711113977161 +// "IR-SPGR-SAG" (GE). Acquisition 1 holds 74 slices; acquisition 2 holds 148 +// slices at those same 74 positions. The split is right and the acquisition-2 +// volume must still carry the duplicate-position warning. Same shape in IDC +// series 1.3.6.1.4.1.14519.5.2.1.7695.2311.133871731749882407434486842181 +// ("LEFT - Dynamic-3dfgre", acquisition values 0 and 2). +export const doubledAcquisition: SliceGroup[] = [ + { tags: { [Tags.AcquisitionNumber]: '1' }, zs: steps(-214.177, 74, 2.5) }, + { + tags: { [Tags.AcquisitionNumber]: '2' }, + zs: [...steps(-214.177, 74, 2.5), ...steps(-214.177, 74, 2.5)], + }, +]; diff --git a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts index c200bf49f..bb0c07f79 100644 --- a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts @@ -2,14 +2,14 @@ import { datasetFromTags } from '@/tests/dicomDataset'; import { describe, expect, it } from 'vitest'; import { Tags } from '../../metadata/dicomTags'; import { - readInstanceFacts as readStructuredFacts, + readInstanceDetails, seriesKeyOf as structuredSeriesKeyOf, } from '../instanceFacts'; const INSTANCE_NUMBER_TAG = '0020|0013'; -// readDicomTags hands back DICOM's own padding, so every fixture value here is -// written the way the reader returns it. +// Dataset text keeps DICOM's own padding, so every fixture value here is +// written the way a parsed header holds it. const metadata = (overrides: Record = {}) => { const entries: Array<[string, string]> = [ [Tags.SOPInstanceUID, '1.2.3.4'], @@ -37,13 +37,9 @@ const metadata = (overrides: Record = {}) => { const without = (tag: string) => metadata().filter((entry) => entry[0] !== tag); -describe('readInstanceFacts', () => { - it('names the instance number tag the planner orders on', () => { - expect(Tags.InstanceNumber).toBe(INSTANCE_NUMBER_TAG); - }); - +describe('instance facts', () => { it('reads every fact the planner compares', () => { - expect(readInstanceFacts(metadata())).toEqual({ + expect(factsOf(metadata())).toEqual({ sopInstanceUid: '1.2.3.4', seriesInstanceUid: '1.2.3', seriesNumber: '1', @@ -67,7 +63,7 @@ describe('readInstanceFacts', () => { }); it('reads an instance with no tags at all as entirely unknown', () => { - expect(readInstanceFacts([])).toEqual({ + expect(factsOf([])).toEqual({ sopInstanceUid: null, seriesInstanceUid: null, seriesNumber: null, @@ -91,56 +87,41 @@ describe('readInstanceFacts', () => { }); it.each([ - ['SeriesNumber', Tags.SeriesNumber, 'seriesNumber'], ['SequenceName', Tags.SequenceName, 'sequenceName'], - ['SliceThickness', Tags.SliceThickness, 'sliceThickness'], - ['SeriesDate', Tags.SeriesDate, 'seriesDate'], ['Rows', Tags.Rows, 'rows'], - ['Columns', Tags.Columns, 'columns'], - ['SamplesPerPixel', Tags.SamplesPerPixel, 'samplesPerPixel'], ] as const)( 'reads a zero length %s as absent, not as an empty string', (_name, tag, fact) => { - expect(readInstanceFacts(metadata({ [tag]: '' }))[fact]).toBeNull(); - expect(readInstanceFacts(metadata({ [tag]: ' ' }))[fact]).toBeNull(); + expect(factsOf(metadata({ [tag]: '' }))[fact]).toBeNull(); + expect(factsOf(metadata({ [tag]: ' ' }))[fact]).toBeNull(); } ); - it.each([ - ['SeriesNumber', Tags.SeriesNumber, 'seriesNumber'], - ['SliceThickness', Tags.SliceThickness, 'sliceThickness'], - ['Rows', Tags.Rows, 'rows'], - ['Columns', Tags.Columns, 'columns'], - ['SamplesPerPixel', Tags.SamplesPerPixel, 'samplesPerPixel'], - ['NumberOfFrames', Tags.NumberOfFrames, 'numberOfFrames'], - ] as const)( - 'normalizes the numeric spelling of %s so 04 and 4.0 are one value', - (_name, tag, fact) => { - const readFact = (value: string) => - readInstanceFacts(metadata({ [tag]: value }))[fact]; - expect(readFact('4')).toBe('4'); - expect(readFact('04')).toBe('4'); - expect(readFact('4.0')).toBe('4'); - expect(readFact(' 4 ')).toBe('4'); - expect(readFact('1.50')).toBe('1.5'); - } - ); + it('normalizes a numeric spelling so 04 and 4.0 are one value', () => { + const readFact = (value: string) => + factsOf(metadata({ [Tags.SliceThickness]: value })).sliceThickness; + expect(readFact('4')).toBe('4'); + expect(readFact('04')).toBe('4'); + expect(readFact('4.0')).toBe('4'); + expect(readFact(' 4 ')).toBe('4'); + expect(readFact('1.50')).toBe('1.5'); + }); // A study date's leading zeros are part of the value, so it stays text. it('keeps a series date as text rather than as a number', () => { expect( - readInstanceFacts(metadata({ [Tags.SeriesDate]: '00240101 ' })).seriesDate + factsOf(metadata({ [Tags.SeriesDate]: '00240101 ' })).seriesDate ).toBe('00240101'); }); it('keeps a sequence name as text', () => { expect( - readInstanceFacts(metadata({ [Tags.SequenceName]: '007 ' })).sequenceName + factsOf(metadata({ [Tags.SequenceName]: '007 ' })).sequenceName ).toBe('007'); }); it('trims the padding DICOM adds to odd length identifiers', () => { - const facts = readInstanceFacts( + const facts = factsOf( metadata({ [Tags.SOPInstanceUID]: '1.2.3.4 ', [Tags.SeriesInstanceUID]: '1.2.3 ', @@ -161,7 +142,7 @@ describe('readInstanceFacts', () => { metadata({ [Tags.ImageOrientationPatient]: '1\\0\\0\\0\\x\\0' }), ], ])('reads an orientation with %s as unknown', (_case, entries) => { - const facts = readInstanceFacts(entries); + const facts = factsOf(entries); expect(facts.orientation).toBeNull(); expect(facts.projectedPosition).toBeNull(); }); @@ -174,7 +155,7 @@ describe('readInstanceFacts', () => { metadata({ [Tags.ImagePositionPatient]: '1\\2\\z' }), ], ])('reads a position with %s as unknown', (_case, entries) => { - const facts = readInstanceFacts(entries); + const facts = factsOf(entries); expect(facts.position).toBeNull(); expect(facts.projectedPosition).toBeNull(); }); @@ -184,9 +165,7 @@ describe('readInstanceFacts', () => { ['a trailing blank component', '1\\2\\'], ['a whitespace component', '1\\ \\3'], ])('reads a position with %s as unknown, not as a zero', (_case, value) => { - const facts = readInstanceFacts( - metadata({ [Tags.ImagePositionPatient]: value }) - ); + const facts = factsOf(metadata({ [Tags.ImagePositionPatient]: value })); expect(facts.position).toBeNull(); expect(facts.projectedPosition).toBeNull(); }); @@ -198,16 +177,14 @@ describe('readInstanceFacts', () => { ['a row and column 45 degrees apart', '1\\0\\0\\0.7071\\0.7071\\0'], ['a blank cosine', '1\\0\\0\\0\\\\0'], ])('reads %s as no orientation at all', (_case, value) => { - const facts = readInstanceFacts( - metadata({ [Tags.ImageOrientationPatient]: value }) - ); + const facts = factsOf(metadata({ [Tags.ImageOrientationPatient]: value })); expect(facts.orientation).toBeNull(); expect(facts.projectedPosition).toBeNull(); }); // A DS value carries a printed decimal, so exact unit length is not on offer. it('normalizes cosines that are within the tolerance of unit length', () => { - const facts = readInstanceFacts( + const facts = factsOf( metadata({ [Tags.ImageOrientationPatient]: '0.99998\\0\\0\\0\\1.00002\\0', }) @@ -234,9 +211,7 @@ describe('readInstanceFacts', () => { [1, 0, 0, 0, 1, 0], ], ])('rescales %s to unit axes', (_case, value, expected) => { - const facts = readInstanceFacts( - metadata({ [Tags.ImageOrientationPatient]: value }) - ); + const facts = factsOf(metadata({ [Tags.ImageOrientationPatient]: value })); expect(facts.orientation).not.toBeNull(); facts.orientation!.forEach((cosine, index) => @@ -246,7 +221,7 @@ describe('readInstanceFacts', () => { }); it('accepts cosines a printed digit away from square', () => { - const facts = readInstanceFacts( + const facts = factsOf( metadata({ [Tags.ImageOrientationPatient]: '0.7071\\0.7071\\0\\-0.7072\\0.7070\\0', }) @@ -262,13 +237,13 @@ describe('readInstanceFacts', () => { ['blank', '\\0.5'], ])('reads a %s pixel spacing as unknown', (_case, value) => { expect( - readInstanceFacts(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing + factsOf(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing ).toBeNull(); }); it('projects the position onto the slice normal, not onto z', () => { // Rows run along +y and columns along +z, so the normal is +x. - const facts = readInstanceFacts( + const facts = factsOf( metadata({ [Tags.ImageOrientationPatient]: '0\\1\\0\\0\\0\\1' }) ); expect(facts.projectedPosition).toBeCloseTo(10, 10); @@ -276,7 +251,7 @@ describe('readInstanceFacts', () => { it('projects onto the normal with the cosines in row then column order', () => { // Swapping the two rows of the case above flips the normal to -x. - const facts = readInstanceFacts( + const facts = factsOf( metadata({ [Tags.ImageOrientationPatient]: '0\\0\\1\\0\\1\\0' }) ); expect(facts.projectedPosition).toBeCloseTo(-10, 10); @@ -291,7 +266,7 @@ describe('readInstanceFacts', () => { null, ], ])('reads a pixel spacing with %s as unknown', (_case, entries) => { - expect(readInstanceFacts(entries).pixelSpacing).toBeNull(); + expect(factsOf(entries).pixelSpacing).toBeNull(); }); it.each([ @@ -300,8 +275,7 @@ describe('readInstanceFacts', () => { ['-3', -3], ])('reads the instance number %s as a number', (value, expected) => { expect( - readInstanceFacts(metadata({ [INSTANCE_NUMBER_TAG]: value })) - .instanceNumber + factsOf(metadata({ [INSTANCE_NUMBER_TAG]: value })).instanceNumber ).toBe(expected); }); @@ -310,14 +284,7 @@ describe('readInstanceFacts', () => { ['an empty value', metadata({ [INSTANCE_NUMBER_TAG]: ' ' })], ['a non numeric value', metadata({ [INSTANCE_NUMBER_TAG]: 'first' })], ])('reads an instance number with %s as unknown', (_case, entries) => { - expect(readInstanceFacts(entries).instanceNumber).toBeNull(); - }); - - it('does not mutate the metadata it reads', () => { - const entries = metadata(); - const before = JSON.parse(JSON.stringify(entries)); - readInstanceFacts(entries); - expect(entries).toEqual(before); + expect(factsOf(entries).instanceNumber).toBeNull(); }); }); @@ -363,17 +330,10 @@ describe('seriesKeyOf', () => { expect(key('a|b', 'c')).not.toBe(key('a', 'b|c')); expect(key('a:b', 'c')).not.toBe(key('a', 'b:c')); }); - - it('does not mutate the metadata it reads', () => { - const entries = metadata(); - const before = JSON.parse(JSON.stringify(entries)); - seriesKeyOf(entries); - expect(entries).toEqual(before); - }); }); -function readInstanceFacts(tags: Iterable) { - return readStructuredFacts(datasetFromTags(tags)); +function factsOf(tags: Iterable) { + return readInstanceDetails(datasetFromTags(tags)).facts; } function seriesKeyOf(tags: Iterable) { return structuredSeriesKeyOf(datasetFromTags(tags)); @@ -384,11 +344,11 @@ describe('single-frame and spacing normalization', () => { 'defaults NumberOfFrames %s to one', (frames) => { expect( - readStructuredFacts( + readInstanceDetails( datasetFromTags( frames === undefined ? [] : [[Tags.NumberOfFrames, frames]] ) - ).numberOfFrames + ).facts.numberOfFrames ).toBe('1'); } ); @@ -397,7 +357,7 @@ describe('single-frame and spacing normalization', () => { 'retains the first two PixelSpacing values in %s', (value) => { expect( - readInstanceFacts(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing + factsOf(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing ).toEqual([0.5, 0.75]); } ); diff --git a/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts b/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts index 7e22ea469..bd8af1cf8 100644 --- a/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts +++ b/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts @@ -12,9 +12,6 @@ export const tiltedOrientation = (theta: number) => [ Math.sin(theta), ]; -export const orientationKeyValue = (orientation: number[]) => - orientation.map(String).join(','); - // The position and its projection are one fact, so a fixture naming only the // projection gets the axial position that produces it. const positionFor = (overrides: Partial) => { diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts index 777b9e393..3b06558c9 100644 --- a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -6,11 +6,11 @@ import { instanceFor } from '@/tests/dicomDataset'; import { emptyRegistry, forgetCollection, - isRegistered, registerInstances, type RegistryState, } from '../instanceRegistry'; -import { mergingInstances } from '@/tests/dicomOrientationFixtures'; +import { UNREADABLE_POSITION_WARNING } from '../planDicomCollections'; +import { mergingInstances, tilt } from '@/tests/dicomOrientationFixtures'; import { OTHER_SERIES_UID, SERIES_UID, @@ -39,6 +39,16 @@ const registerAll = (batches: Instance[][], initial = emptyRegistry) => const lastUpdates = (batches: Instance[][]) => registerAll(batches).at(-1)!.updates; +const acquisition = (number: string, zs: number[], orientation?: string) => + zs.map((z) => + slice({ + sop: `${number}-${z}`, + z, + orientation, + tags: { [Tags.AcquisitionNumber]: number }, + }) + ); + describe('pure instance registry', () => { it('orders a series into one collection whose members align with the plan', () => { const [a, b, c] = [0, 1, 2].map((z) => slice({ sop: `s${z}`, z })); @@ -75,10 +85,9 @@ describe('pure instance registry', () => { const [first, second] = registerAll([[original], [resupplied]]); expect(second.updates[0].id).toBe(first.updates[0].id); - expect(second.updates[0].members).toEqual([original]); - expect(second.updates[0].provenance).toEqual([resupplied]); - expect(isRegistered(second.state, original)).toBe(true); - expect(isRegistered(second.state, resupplied)).toBe(false); + expect(second.updates[0].members).toHaveLength(1); + expect(second.updates[0].members[0]).toBe(original); + expect(second.updates[0].provenance[0]).toBe(resupplied); }); it('reports a conflicting copy under a registered UID and keeps the first', () => { @@ -88,8 +97,8 @@ describe('pure instance registry', () => { const second = registerAll([[original], [conflicting]])[1]; expect(second.conflictingInstanceUids).toEqual(['same']); - expect(second.updates[0].members).toEqual([original]); - expect(second.updates[0].provenance).toEqual([original]); + expect(second.updates[0].members[0]).toBe(original); + expect(second.updates[0].provenance[0]).toBe(original); }); it('identifies instances without a UID by object', () => { @@ -102,10 +111,92 @@ describe('pure instance registry', () => { expect(results[1].updates[0].members).toEqual([first, second]); }); - it('recognizes a NUL padded UID as the registered instance', () => { - const padded = slice({ sop: '1.2.3\0\0' }); - const { state } = registerInstances(emptyRegistry, [padded]); - expect(isRegistered(state, padded)).toBe(true); + it.each([ + { sop: ' a ', series: ` ${SERIES_UID} ` }, + { sop: '1.2.3\0\0', series: SERIES_UID }, + { sop: 'a', series: ' ' }, + ])('recognizes a copy of the padded identity %j', (identity) => { + const original = slice(identity); + + const [update] = lastUpdates([[original], [slice(identity)]]); + + expect(update.members).toHaveLength(1); + expect(update.members[0]).toBe(original); + }); + + it.each([ + { sop: null, series: null }, + { sop: '', series: SERIES_UID }, + { sop: ' ', series: '' }, + ])('never merges copies of the blank identity %j', (identity) => { + const [update] = lastUpdates([[slice(identity), slice(identity)]]); + + expect(update.members).toHaveLength(2); + }); + + it('keeps anonymous clip ownership stable after deletion and another import', () => { + const clips = [0, 1, 2].map(() => + slice({ sop: null, tags: { [Tags.NumberOfFrames]: '3' } }) + ); + const before = registerInstances(emptyRegistry, clips.slice(0, 2)); + const idOf = (clip: Instance) => + before.updates.find((update) => update.members[0] === clip)!.id; + + const after = registerInstances( + forgetCollection(before.state, idOf(clips[0])), + [clips[2]] + ); + const again = registerInstances(after.state, [clips[1], clips[0]]); + + expect(after.removed).toEqual([]); + expect( + again.updates.map(({ id, members, change }) => [id, members[0], change]) + ).toContainEqual([idOf(clips[1]), clips[1], 'unchanged']); + expect( + again.updates.find((update) => update.members[0] === clips[0])!.change + ).toBe('new'); + }); + + it('does not confuse a numeric UID with an anonymous clip identity', () => { + const clips = ['1', null].map((sop) => + slice({ sop, tags: { [Tags.NumberOfFrames]: '2' } }) + ); + + const updates = lastUpdates([clips]); + + expect(updates).toHaveLength(2); + expect(new Set(updates.map((update) => update.id)).size).toBe(2); + expect(new Set(updates.flatMap((update) => update.members))).toEqual( + new Set(clips) + ); + }); + + it('keeps slices with absent and explicit single-frame counts in one volume', () => { + const [update] = lastUpdates([ + [ + slice({ sop: 'first', z: 0 }), + slice({ sop: 'second', z: 1, tags: { [Tags.NumberOfFrames]: '1' } }), + ], + ]); + + expect(update.members).toHaveLength(2); + expect(update.collection.reconstruction.sliceSpacing).toBe(1); + }); + + it('splits one batch of incompatible instances into two collections', () => { + const scout = slice({ sop: 'scout', rows: '8', z: 0 }); + const slices = [slice({ sop: 'a', z: 0 }), slice({ sop: 'b', z: 1 })]; + + const updates = lastUpdates([[scout, ...slices]]); + + expect(updates.map((update) => sopsOf(update.members)).sort()).toEqual([ + ['a', 'b'], + ['scout'], + ]); + expect(new Set(updates.map((update) => update.id)).size).toBe(2); + updates.forEach((update) => + expect(update.id.startsWith(SERIES_UID)).toBe(true) + ); }); it('reports the id a replan dissolves when two collections merge', () => { @@ -123,16 +214,65 @@ describe('pure instance registry', () => { ); }); - it('leaves an untouched collection out and reports a relabelled one', () => { + it('reports a collection that lost members without gaining an instance', () => { + const straight = slice({ sop: 'sop-2', z: 0, orientation: tilt(0) }); + const near = slice({ sop: 'sop-3', z: 1, orientation: tilt(0.01) }); + // Agrees with the straight instance but not with the near one, so the + // bucket it seeds as the new reference leaves the near one behind. + const splitter = slice({ sop: 'sop-1', z: 2, orientation: tilt(-0.005) }); + + const [first, second] = registerAll([[straight, near], [splitter]]); + + expect(first.updates).toHaveLength(1); + const orphaned = second.updates.find( + (update) => !update.members.includes(splitter) + )!; + expect(sopsOf(orphaned.members)).toEqual(['sop-3']); + expect(second.removed).toEqual([first.updates[0].id]); + }); + + it('keeps the members a replan moved when the dissolved id is forgotten', () => { + const { between, straight, tilted } = mergingInstances(slice); + + const [, merged] = registerAll([[straight, tilted], [between]]); + const state = merged.removed.reduce(forgetCollection, merged.state); + const third = registerInstances(state, [between]); + + expect(third.updates[0].members).toHaveLength(3); + }); + + it('says how each collection differs from what was committed', () => { + const [a, b] = [0, 1].map((z) => slice({ sop: `c${z}`, z })); + + const changes = registerAll([[a], [slice({ sop: 'c0', z: 0 })], [b]]).map( + ({ updates }) => updates.map((update) => update.change) + ); + + expect(changes).toEqual([['new'], ['unchanged'], ['changed']]); + }); + + it('reports a collection a sibling relabelled without calling its volume changed', () => { + const [first, second] = registerAll([ + acquisition('1', [0, 2]), + acquisition('2', [1, 3]), + ]); + + expect(first.updates[0].collection.label).toBeNull(); + expect( + second.updates.map(({ id, change, collection }) => [ + id === first.updates[0].id, + change, + collection.label, + ]) + ).toEqual([ + [true, 'unchanged', 'acquisition 1'], + [false, 'new', 'acquisition 2'], + ]); + expect(second.removed).toEqual([]); + }); + + it('reports a collection whose label another pixel shape changed, and leaves an untouched one out', () => { const scout = slice({ sop: 'scout', rows: '8' }); - const acquisition = (number: string, zs: number[]) => - zs.map((z) => - slice({ - sop: `${number}-${z}`, - z, - tags: { [Tags.AcquisitionNumber]: number }, - }) - ); const [first, second, third] = registerAll([ acquisition('1', [0, 2]), @@ -140,9 +280,21 @@ describe('pure instance registry', () => { acquisition('2', [1, 3]), ]); - expect(second.updates.map((update) => sopsOf(update.members))).toEqual([ - ['scout'], + expect( + second.updates + .map(({ members, change, collection }) => [ + sopsOf(members), + change, + collection.label, + ]) + .sort() + ).toEqual([ + [['1-0', '1-2'], 'unchanged', 'rows 4'], + [['scout'], 'new', 'rows 8'], ]); + expect( + third.updates.map((update) => sopsOf(update.members)) + ).not.toContainEqual(['scout']); const relabelled = third.updates.find( (update) => update.id === first.updates[0].id )!; @@ -151,49 +303,49 @@ describe('pure instance registry', () => { expect(third.removed).toEqual([]); }); - it('says how each collection differs from what was committed', () => { - const [a, b] = [0, 1].map((z) => slice({ sop: `c${z}`, z })); + it('reports a positionless image again once a positioned sibling gives it a warning', () => { + const blind = slice({ sop: 'blind', z: null }); - const changes = registerAll([[a], [slice({ sop: 'c0', z: 0 })], [b]]).map( - ({ updates }) => updates.map((update) => update.change) - ); + const [first, second] = registerAll([[blind], [slice({ sop: 'seen' })]]); - expect(changes).toEqual([['new'], ['unchanged'], ['changed']]); + expect(first.updates[0].collection.warnings).toEqual([]); + const again = second.updates.find( + (update) => update.id === first.updates[0].id + )!; + expect(again.change).toBe('unchanged'); + expect(again.collection.label).toBe('position unknown'); + expect(again.collection.warnings).toEqual([UNREADABLE_POSITION_WARNING]); }); - it('reports a relabelled collection as changed', () => { - const acquisition = (number: string, zs: number[]) => - zs.map((z) => - slice({ - sop: `${number}-${z}`, - z, - tags: { [Tags.AcquisitionNumber]: number }, - }) - ); - - const [, second] = registerAll([ - acquisition('1', [0, 2]), - acquisition('2', [1, 3]), + // The positions of the two passes already earned their separation; a later + // slice nothing spatial can be said about must not dissolve it. + it('keeps two separated acquisitions when a positionless instance arrives later', () => { + const passes = [ + ...acquisition('1', [0, 2, 4]), + ...acquisition('2', [1, 3, 5]), + ]; + const blind = slice({ sop: 'blind', z: null, instanceNumber: 9 }); + + const [separated, later, again] = registerAll([passes, [blind], passes]); + + expect(separated.updates).toHaveLength(2); + expect(later.removed).toEqual([]); + expect(later.updates.map((update) => sopsOf(update.members))).toEqual([ + ['blind'], ]); - - expect(second.updates.map((update) => update.change)).toEqual([ - 'changed', - 'new', + expect(later.updates[0].collection.warnings).toEqual([ + UNREADABLE_POSITION_WARNING, ]); + expect( + again.updates.map(({ id, members, change }) => [id, members, change]) + ).toEqual( + separated.updates.map(({ id, members }) => [id, members, 'unchanged']) + ); }); it('reports a collection whose axes a sibling pass outvoted as changed', () => { // Within the orientation tolerance, so one bucket, but leaning the normal. const tilted = '1\\0\\0\\0\\0.99995\\0.0099998'; - const acquisition = (number: string, zs: number[], orientation?: string) => - zs.map((z) => - slice({ - sop: `${number}-${z}`, - z, - orientation, - tags: { [Tags.AcquisitionNumber]: number }, - }) - ); const [first, second] = registerAll([ [...acquisition('1', [0, 2]), ...acquisition('2', [1, 3], tilted)], @@ -238,14 +390,14 @@ describe('pure instance registry', () => { it('leaves the input state untouched, so discarding a result undoes it', () => { const kept = slice({ sop: 'a', z: 0 }); const { state } = registerInstances(emptyRegistry, [kept]); - const discarded = slice({ sop: 'b', z: 1 }); - registerInstances(state, [discarded]); + registerInstances(state, [slice({ sop: 'b', z: 1 })]); const retried = slice({ sop: 'b', z: 1 }); const { updates } = registerInstances(state, [retried]); - expect(isRegistered(state, discarded)).toBe(false); - expect(updates[0].members).toEqual([kept, retried]); + expect(updates[0].members).toHaveLength(2); + expect(updates[0].members[0]).toBe(kept); + expect(updates[0].members[1]).toBe(retried); }); it('forgets a collection so a re-import plans it afresh under the same id', () => { @@ -256,13 +408,19 @@ describe('pure instance registry', () => { const forgotten = forgetCollection(state, scoutId); const resupplied = slice({ sop: 'scout', rows: '8' }); - const again = registerInstances(forgotten, [resupplied]); - - expect(isRegistered(forgotten, scout)).toBe(false); - expect(isRegistered(forgotten, kept)).toBe(true); - expect(again.updates.map((update) => [update.id, update.members])).toEqual([ - [scoutId, [resupplied]], + const again = registerInstances(forgotten, [ + resupplied, + slice({ sop: 'kept' }), ]); + + // Identity, not shape: the forgotten instance is an equal but stale object. + const membersOf = (sop: string) => + again.updates.find((update) => sopsOf(update.members)[0] === sop)! + .members; + expect(membersOf('scout')).toHaveLength(1); + expect(membersOf('scout')[0]).toBe(resupplied); + expect(membersOf('kept')[0]).toBe(kept); + expect(again.updates.map((update) => update.id)).toContain(scoutId); expect(again.removed).toEqual([]); expect(forgetCollection(forgotten, 'unknown')).toBe(forgotten); }); diff --git a/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts b/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts new file mode 100644 index 000000000..f64748a9b --- /dev/null +++ b/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from 'vitest'; +import type { DicomDataset } from '../../metadata/dicomDataset'; +import { getFrameTag } from '../../metadata/functionalGroups'; +import { readGeometryFacts, readInstanceDetails } from '../instanceFacts'; +import { + planDicomCollections, + IRREGULAR_VOLUME_WARNING, + REPEATED_POSITIONS_WARNING, + UNREADABLE_FRAME_GEOMETRY_WARNING, +} from '../planDicomCollections'; +import { + ctShared, + enhanced, + groups, + positioned, + sequence, + sharedPlaneTemporal, + tags, +} from '../../volume/__tests__/enhancedFixture'; + +const collectionOf = (metadata: DicomDataset, seriesKey = 'frames') => + planDicomCollections({ + seriesKey, + instances: [readInstanceDetails(metadata).facts], + })[0]; + +describe('multiframe geometry', () => { + it('reads exact macro paths without changing raw tags or importing referenced-image geometry', () => { + const metadata = enhanced(ctShared(), [positioned('1\\2\\3')], { + '00280030': '9\\9', + }); + metadata.elements.push( + sequence('00081140', [tags({ '00200037': '0\\1\\0\\0\\0\\1' })]) + ); + const before = JSON.stringify(metadata); + expect(readGeometryFacts(metadata)).toEqual({ + orientation: [-1, 0, 0, 0, 1, 0], + position: [1, 2, 3], + pixelSpacing: [0.388672, 0.388672], + }); + expect(getFrameTag(metadata, '00280030')).toBe('.388672\\.388672'); + expect(JSON.stringify(metadata)).toBe(before); + const rootOnly = tags({ '00280030': '2\\3' }); + rootOnly.elements.push( + sequence('00081140', [tags({ '00200037': '0\\1\\0\\0\\0\\1' })]) + ); + expect(readGeometryFacts(rootOnly).orientation).toBeNull(); + }); + + it('plans shared-plane temporal frames as irregular, with a warning', () => { + const metadata = sharedPlaneTemporal(); + const collection = collectionOf(metadata); + expect(collection.reconstruction.kind).toBe('irregular'); + expect(collection.warnings).toContain(UNREADABLE_FRAME_GEOMETRY_WARNING); + }); + + it('keeps an unreadable frame geometry warning for a lone multiframe source', () => { + const metadata = enhanced( + ctShared(), + [1, 2].map((index) => + groups([sequence('00209111', [tags({ '00209057': String(index) })])]) + ) + ); + const collection = collectionOf(metadata); + expect(collection.reconstruction).toMatchObject({ + kind: 'irregular', + reason: 'unreadable-geometry', + }); + expect(collection.warnings).toContain(UNREADABLE_FRAME_GEOMETRY_WARNING); + }); + + it.each([ + [[0, 1, 3], 'uneven-slice-spacing', IRREGULAR_VOLUME_WARNING], + [[0, 0, 2], 'repeated-position', REPEATED_POSITIONS_WARNING], + ] as const)( + 'reports intra-instance geometry %s', + (positions, reason, warning) => { + const metadata = enhanced( + ctShared(), + positions.map((z) => positioned(`0\\0\\${z}`)) + ); + const collection = collectionOf(metadata); + expect(collection.reconstruction).toMatchObject({ + kind: 'irregular', + reason, + }); + expect(collection.warnings).toContain(warning); + } + ); + + it('does not report normal segment-major SEG frames as an irregular volume', () => { + const metadata = enhanced( + ctShared(), + [0, 1, 0, 1].map((z) => positioned(`0\\0\\${z}`)), + { '00080060': 'SEG' } + ); + expect(collectionOf(metadata, 'seg').warnings).toEqual([]); + }); +}); diff --git a/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts b/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts index abc58e4d9..e037764a6 100644 --- a/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts +++ b/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts @@ -1,26 +1,18 @@ import { describe, it, expect } from 'vitest'; +import { ORIENTATION_TOLERANCE } from '../orientation'; import { - HARD_FACT_RULES, - ORIENTATION_RULE, - ORIENTATION_TOLERANCE, IN_PLANE_SHIFT_WARNING, NONPARALLEL_SLICES_WARNING, IRREGULAR_VOLUME_WARNING, REPEATED_POSITIONS_WARNING, UNREADABLE_POSITION_WARNING, planDicomCollections, - validateCollections, } from '../planDicomCollections'; -import { - SEMANTIC_AXES, - DESCRIPTOR_AXES, -} from '../splitOverlappingAcquisitions'; import type { DicomCollection, InstanceFacts } from '../planDicomCollections'; import { IDENTITY_ORIENTATION, clone, makeFacts, - orientationKeyValue, tiltedOrientation, } from './instanceFactsFixture'; @@ -40,15 +32,6 @@ function collectionWith(collections: DicomCollection[], uid: string) { return found; } -const partValue = (collection: DicomCollection, rule: string) => { - const part = collection.key.parts.find(([name]) => name === rule); - if (!part) throw new Error(`no key part named ${rule}`); - return part[1]; -}; - -const mentions = (diagnostics: string[], needle: string) => - diagnostics.some((d) => d.includes(needle)); - // Second orientation row rotations, measured against the dot-product tolerance. const WITHIN = Math.acos(1 - ORIENTATION_TOLERANCE / 2); const BEYOND = Math.acos(1 - ORIENTATION_TOLERANCE * 2); @@ -57,91 +40,43 @@ const CHAIN = Math.sqrt(ORIENTATION_TOLERANCE); describe('planDicomCollections', () => { it('plans nothing for an empty instance list', () => { - expect(plan([])).toEqual({ collections: [] }); + expect(plan([])).toEqual([]); }); it('keeps one consistent series in a single collection', () => { const a = makeFacts('uid-a', { projectedPosition: 0, instanceNumber: 1 }); const b = makeFacts('uid-b', { projectedPosition: 1, instanceNumber: 2 }); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(1); - expect(collections[0].key.seriesKey).toBe(SERIES_KEY); expect(collections[0].members[0]).toBe(a); expect(collections[0].members[1]).toBe(b); - expect(collections[0].order).toBe('spatial'); - expect(collections[0].diagnostics).toEqual([]); - }); - - it('names the hard facts then orientation, in a fixed key order', () => { - const { collections } = plan([makeFacts('uid-a')]); - - expect(collections[0].key.parts.map(([rule]) => rule)).toEqual([ - ...HARD_FACT_RULES, - ORIENTATION_RULE, - ...SEMANTIC_AXES.map((axis) => axis.rule), - ]); - expect(collections[0].key.parts).toEqual([ - ['rows', '4'], - ['columns', '4'], - ['samplesPerPixel', '1'], - ['numberOfFrames', null], - ['orientation', orientationKeyValue(IDENTITY_ORIENTATION)], - ['acquisition', null], - ['phase', null], - ['echo', null], - ['b-value', null], - ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), - ]); + expect(collections[0].label).toBeNull(); + expect(collections[0].warnings).toEqual([]); }); - const differingFacts: Array<[string, Partial, string]> = [ - ['rows', { rows: '8' }, '8'], - ['columns', { columns: '8' }, '8'], - ['samplesPerPixel', { samplesPerPixel: '3' }, '3'], - ['numberOfFrames', { numberOfFrames: '2' }, '2'], + const differingFacts: Array<[string, Partial]> = [ + ['rows', { rows: '8' }], + ['columns', { columns: '8' }], + ['samplesPerPixel', { samplesPerPixel: '3' }], + ['numberOfFrames', { numberOfFrames: '2' }], + ['rows', { rows: null }], + ['columns', { columns: null }], + ['samplesPerPixel', { samplesPerPixel: null }], ]; it.each(differingFacts)( - 'partitions on a differing %s', - (rule, overrides, expected) => { + 'partitions on %s differing as %j', + (_rule, facts) => { const a = makeFacts('uid-a'); - const b = makeFacts('uid-b', overrides); + const b = makeFacts('uid-b', facts); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(2); expect(uidsOf(collectionWith(collections, 'uid-a'))).toEqual(['uid-a']); expect(uidsOf(collectionWith(collections, 'uid-b'))).toEqual(['uid-b']); - expect(partValue(collectionWith(collections, 'uid-b'), rule)).toBe( - expected - ); - } - ); - - const missingFacts: Array< - [string, Partial, Partial] - > = [ - ['rows', { rows: '4' }, { rows: null }], - ['columns', { columns: '4' }, { columns: null }], - ['samplesPerPixel', { samplesPerPixel: '1' }, { samplesPerPixel: null }], - ['numberOfFrames', { numberOfFrames: '2' }, { numberOfFrames: null }], - ]; - - it.each(missingFacts)( - 'buckets a missing %s on its own', - (rule, present, absent) => { - const a = makeFacts('uid-a', present); - const b = makeFacts('uid-b', absent); - - const { collections } = plan([a, b]); - - expect(collections).toHaveLength(2); - expect(partValue(collectionWith(collections, 'uid-b'), rule)).toBeNull(); - expect( - partValue(collectionWith(collections, 'uid-a'), rule) - ).not.toBeNull(); } ); @@ -159,25 +94,17 @@ describe('planDicomCollections', () => { instanceNumber: 9, }); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(1); expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); }); - it('keys on the given series key, not the instances own series UID', () => { - const a = makeFacts('uid-a', { seriesInstanceUid: 'somewhere-else' }); - - const { collections } = plan([a], 'series-9'); - - expect(collections[0].key.seriesKey).toBe('series-9'); - }); - it('buckets orientations whose rows agree within the tolerance', () => { const a = makeFacts('uid-a', { orientation: IDENTITY_ORIENTATION }); const b = makeFacts('uid-b', { orientation: tiltedOrientation(WITHIN) }); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(1); expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); @@ -187,25 +114,11 @@ describe('planDicomCollections', () => { const a = makeFacts('uid-a', { orientation: IDENTITY_ORIENTATION }); const b = makeFacts('uid-b', { orientation: tiltedOrientation(BEYOND) }); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(2); - expect( - partValue(collectionWith(collections, 'uid-b'), ORIENTATION_RULE) - ).toBe(orientationKeyValue(tiltedOrientation(BEYOND))); - }); - - it('buckets identical cosines that are slightly over normalized', () => { - const overNormalized = [1.0001, 0, 0, 0, 1, 0]; - const a = makeFacts('uid-a', { orientation: overNormalized }); - const b = makeFacts('uid-b', { orientation: overNormalized }); - - const { collections } = plan([a, b]); - - expect(collections).toHaveLength(1); - expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); - expect(partValue(collections[0], ORIENTATION_RULE)).toBe( - orientationKeyValue(overNormalized) + expect(collectionWith(collections, 'uid-b').orientation).toEqual( + tiltedOrientation(BEYOND) ); }); @@ -218,14 +131,12 @@ describe('planDicomCollections', () => { const backward = plan([c, b, a]); const shuffled = plan([b, c, a]); - expect(forward.collections).toHaveLength(2); - expect(uidsOf(collectionWith(forward.collections, 'uid-a'))).toEqual([ + expect(forward).toHaveLength(2); + expect(uidsOf(collectionWith(forward, 'uid-a'))).toEqual([ 'uid-a', 'uid-b', ]); - expect(uidsOf(collectionWith(forward.collections, 'uid-c'))).toEqual([ - 'uid-c', - ]); + expect(uidsOf(collectionWith(forward, 'uid-c'))).toEqual(['uid-c']); expect(backward).toEqual(forward); expect(shuffled).toEqual(forward); }); @@ -249,92 +160,40 @@ describe('planDicomCollections', () => { const [x, y, z] = anonymousChain(); const forward = plan([x, y, z]); - expect(forward.collections.map((c) => c.members.length)).toEqual([2, 1]); + expect(forward.map((c) => c.members.length)).toEqual([1, 2]); expect(plan([z, y, x])).toEqual(forward); expect(plan([y, x, z])).toEqual(forward); }); - it('takes the orientation key from the smallest SOP UID, not the first input', () => { - const late = makeFacts('uid-z', { orientation: IDENTITY_ORIENTATION }); - const early = makeFacts('uid-a', { - orientation: tiltedOrientation(WITHIN), - }); - - const { collections } = plan([late, early]); - - expect(collections).toHaveLength(1); - expect(partValue(collections[0], ORIENTATION_RULE)).toBe( - orientationKeyValue(tiltedOrientation(WITHIN)) - ); - }); - - it('never represents a bucket with an instance that has no SOP UID', () => { - const anonymous = makeFacts(null, { orientation: IDENTITY_ORIENTATION }); - const identified = makeFacts('uid-z', { - orientation: tiltedOrientation(WITHIN), - }); - - const { collections } = plan([anonymous, identified]); - - expect(collections).toHaveLength(1); - expect(partValue(collections[0], ORIENTATION_RULE)).toBe( - orientationKeyValue(tiltedOrientation(WITHIN)) - ); - }); - - it('buckets an unreadable orientation on its own and diagnoses it', () => { + it('buckets an unreadable orientation on its own', () => { const a = makeFacts('uid-a'); const b = makeFacts('uid-b', { orientation: null }); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(2); - const orphan = collectionWith(collections, 'uid-b'); - expect(partValue(orphan, ORIENTATION_RULE)).toBeNull(); - expect(mentions(orphan.diagnostics, 'uid-b')).toBe(true); - }); - - it('deduplicates by SOP Instance UID, keeping the last occurrence', () => { - const stale = makeFacts('uid-a', { instanceNumber: 1 }); - const fresh = makeFacts('uid-a', { instanceNumber: 7 }); - - const { collections } = plan([stale, fresh]); - - expect(collections).toHaveLength(1); - expect(collections[0].members).toHaveLength(1); - expect(collections[0].members[0]).toBe(fresh); - expect(mentions(collections[0].diagnostics, 'uid-a')).toBe(true); + expect(uidsOf(collectionWith(collections, 'uid-b'))).toEqual(['uid-b']); + expect(collectionWith(collections, 'uid-b').orientation).toBeNull(); }); it('never merges instances that have no SOP Instance UID', () => { const a = makeFacts(null, { projectedPosition: 0, instanceNumber: 1 }); const b = makeFacts(null, { projectedPosition: 1, instanceNumber: 2 }); - const { collections } = plan([a, b]); + const collections = plan([a, b]); expect(collections).toHaveLength(1); expect(collections[0].members).toHaveLength(2); }); - it('keeps both entries when one anonymous instance is listed twice', () => { - const shared = makeFacts(null); - - const { collections } = plan([shared, shared]); - - expect(collections).toHaveLength(1); - expect(collections[0].members).toEqual([shared, shared]); - }); - it('orders members by projected position ascending', () => { const high = makeFacts('uid-a', { projectedPosition: 10 }); const low = makeFacts('uid-b', { projectedPosition: -5 }); const mid = makeFacts('uid-c', { projectedPosition: 0 }); - const { collections } = plan([high, low, mid]); + const collections = plan([high, low, mid]); expect(uidsOf(collections[0])).toEqual(['uid-b', 'uid-c', 'uid-a']); - expect(collections[0].order).toBe('spatial'); - expect(collections[0].diagnostics).toEqual([]); }); // The tied members keep the scanner's own sequence, but position stays the @@ -356,7 +215,7 @@ describe('planDicomCollections', () => { instanceNumber: 9, }); - const { collections } = plan([later, far, earlier, near]); + const collections = plan([later, far, earlier, near]); expect(uidsOf(collections[0])).toEqual([ 'uid-d', @@ -364,7 +223,6 @@ describe('planDicomCollections', () => { 'uid-a', 'uid-c', ]); - expect(collections[0].order).toBe('spatial'); expect(collections[0].warnings).toEqual([REPEATED_POSITIONS_WARNING]); }); @@ -372,10 +230,9 @@ describe('planDicomCollections', () => { const second = makeFacts('uid-b', { projectedPosition: 3 }); const first = makeFacts('uid-a', { projectedPosition: 3 }); - const { collections } = plan([second, first]); + const collections = plan([second, first]); expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); - expect(collections[0].order).toBe('spatial'); }); it('orders an unnumbered member after a numbered one at the same position', () => { @@ -386,13 +243,12 @@ describe('planDicomCollections', () => { }); const low = makeFacts('uid-c', { projectedPosition: 0 }); - const { collections } = plan([unnumbered, numbered, low]); + const collections = plan([unnumbered, numbered, low]); expect(uidsOf(collections[0])).toEqual(['uid-c', 'uid-b', 'uid-a']); - expect(collections[0].order).toBe('spatial'); }); - it('breaks a shared position between anonymous members on content', () => { + it('breaks a shared position between anonymous members on instance number', () => { const anonymousPair = () => [ makeFacts(null, { projectedPosition: 0, instanceNumber: 1 }), makeFacts(null, { projectedPosition: 0, instanceNumber: 2 }), @@ -401,25 +257,7 @@ describe('planDicomCollections', () => { const [a, b] = anonymousPair(); const forward = plan([a, b]); - expect(forward.collections[0].members.map((m) => m.instanceNumber)).toEqual( - [1, 2] - ); - expect(plan([b, a])).toEqual(forward); - }); - - it('breaks an anonymous tie on facts outside the ordering keys', () => { - const anonymousPair = () => [ - makeFacts(null, { position: [0, 0, 0] }), - makeFacts(null, { position: [9, 9, 9] }), - ]; - - const [a, b] = anonymousPair(); - const forward = plan([a, b]); - - expect(forward.collections[0].members.map((m) => m.position)).toEqual([ - [0, 0, 0], - [9, 9, 9], - ]); + expect(forward[0].members.map((m) => m.instanceNumber)).toEqual([1, 2]); expect(plan([b, a])).toEqual(forward); }); @@ -437,15 +275,15 @@ describe('planDicomCollections', () => { instanceNumber: 1, }); - const { collections } = plan([blind, seen, alsoBlind]); + const collections = plan([blind, seen, alsoBlind]); expect(collections).toHaveLength(2); expect(uidsOf(collectionWith(collections, 'uid-b'))).toEqual(['uid-b']); + expect(collectionWith(collections, 'uid-b').label).toBeNull(); const unknown = collectionWith(collections, 'uid-a'); expect(uidsOf(unknown)).toEqual(['uid-c', 'uid-a']); - expect(unknown.order).toBe('instance-number'); - expect(mentions(unknown.diagnostics, 'uid-a')).toBe(true); + expect(unknown.label).toBe('position unknown'); expect(unknown.warnings).toEqual([UNREADABLE_POSITION_WARNING]); }); @@ -455,12 +293,29 @@ describe('planDicomCollections', () => { instanceNumber: 1, }); - const { collections } = plan([alone]); + const collections = plan([alone]); expect(collections).toHaveLength(1); + expect(collections[0].label).toBeNull(); expect(collections[0].warnings).toEqual([]); }); + // Two radiograph views of one series: no volume holds either out. + it('names only what differs between positionless images with no positioned sibling', () => { + const collections = plan([ + makeFacts('uid-a', { projectedPosition: null, rows: '4' }), + makeFacts('uid-b', { projectedPosition: null, rows: '8' }), + ]); + + expect(collections.map((collection) => collection.label)).toEqual([ + 'rows 4', + 'rows 8', + ]); + expect(collections.flatMap((collection) => collection.warnings)).toEqual( + [] + ); + }); + it('warns about a lone positionless instance beside a volume it missed', () => { const alone = makeFacts('uid-a', { projectedPosition: null, @@ -471,14 +326,15 @@ describe('planDicomCollections', () => { instanceNumber: 2, }); - const { collections } = plan([alone, seen]); + const collections = plan([alone, seen]); + expect(collectionWith(collections, 'uid-a').label).toBe('position unknown'); expect(collectionWith(collections, 'uid-a').warnings).toEqual([ UNREADABLE_POSITION_WARNING, ]); }); - it('breaks a shared instance number on SOP Instance UID', () => { + it('orders a positionless stack on instance number, then SOP Instance UID, and warns', () => { const second = makeFacts('uid-b', { projectedPosition: null, instanceNumber: 4, @@ -487,14 +343,19 @@ describe('planDicomCollections', () => { projectedPosition: null, instanceNumber: 4, }); + const earlier = makeFacts('uid-c', { + projectedPosition: null, + instanceNumber: 1, + }); - const { collections } = plan([second, first]); + const collections = plan([second, first, earlier]); - expect(uidsOf(collections[0])).toEqual(['uid-a', 'uid-b']); - expect(collections[0].order).toBe('instance-number'); + expect(uidsOf(collections[0])).toEqual(['uid-c', 'uid-a', 'uid-b']); + expect(collections[0].label).toBeNull(); + expect(collections[0].warnings).toEqual([UNREADABLE_POSITION_WARNING]); }); - it('records input order when neither position nor instance number reads', () => { + it('keeps input order when neither position nor instance number reads', () => { const second = makeFacts('uid-b', { projectedPosition: null, instanceNumber: null, @@ -504,12 +365,9 @@ describe('planDicomCollections', () => { instanceNumber: null, }); - const { collections } = plan([second, first]); + const collections = plan([second, first]); expect(uidsOf(collections[0])).toEqual(['uid-b', 'uid-a']); - expect(collections[0].order).toBe('input'); - expect(mentions(collections[0].diagnostics, 'uid-a')).toBe(true); - expect(mentions(collections[0].diagnostics, 'uid-b')).toBe(true); }); const permutable = () => [ @@ -549,7 +407,7 @@ describe('planDicomCollections', () => { return plan([items[5], items[0], items[3], items[1], items[4], items[2]]); })(); - expect(base.collections).toHaveLength(3); + expect(base).toHaveLength(3); expect(reversed).toEqual(base); expect(rotated).toEqual(base); expect(interleaved).toEqual(base); @@ -564,16 +422,22 @@ describe('planDicomCollections', () => { expect(clone(instances)).toEqual(before); }); - it('holds every instance exactly once across the collections', () => { - const instances = permutable(); + it('holds every instance exactly once, under a key no other collection shares', () => { + const instances = [ + ...permutable(), + makeFacts('uid-7', { projectedPosition: null }), + makeFacts('uid-8', { rows: '8' }), + ]; - const { collections } = plan(instances); + const collections = plan(instances); const members = collections.flatMap((c) => c.members); + expect(collections).toHaveLength(5); expect(members).toHaveLength(instances.length); - expect(new Set(members).size).toBe(instances.length); - instances.forEach((instance) => expect(members).toContain(instance)); - expect(() => validateCollections(instances, collections)).not.toThrow(); + expect(new Set(members)).toEqual(new Set(instances)); + expect(new Set(collections.map((c) => JSON.stringify(c.key))).size).toBe( + collections.length + ); }); }); @@ -587,23 +451,6 @@ describe('planDicomCollections semantic partition', () => { }) ); - it('separates overlapping passes and labels each collection', () => { - const first = pass('1', [0, 2, 4]); - const second = pass('2', [1, 3, 5]); - - const { collections } = plan([...first, ...second]); - - expect(collections).toHaveLength(2); - const [one, two] = collections; - expect(one.label).toBe('acquisition 1'); - expect(partValue(one, 'acquisition')).toBe('1'); - expect(uidsOf(one)).toEqual(['acq1-0', 'acq1-1', 'acq1-2']); - expect(one.order).toBe('spatial'); - expect(two.label).toBe('acquisition 2'); - expect(partValue(two, 'acquisition')).toBe('2'); - expect(collections.every((c) => c.warnings.length === 0)).toBe(true); - }); - // Two members whose cosines agree within the tolerance are one plane. Each // member's own normal would place them at two positions a fraction of a // micron apart, and the repeated slice would go unreported. @@ -618,7 +465,7 @@ describe('planDicomCollections semantic partition', () => { projectedPosition: 10 * Math.cos(WITHIN), }); - const { collections } = plan([straight, tilted]); + const collections = plan([straight, tilted]); expect(collections).toHaveLength(1); expect(collections[0].warnings).toEqual([REPEATED_POSITIONS_WARNING]); @@ -631,33 +478,31 @@ describe('planDicomCollections semantic partition', () => { acquisitionNumber: '1', }); - const { collections } = plan([...stack, scout]); + const collections = plan([...stack, scout]); expect(collections).toHaveLength(3); expect(collectionWith(collections, 'scout').label).toBeNull(); expect(collectionWith(collections, 'acq1-0').label).toBe('acquisition 1'); - }); - - it('leaves an unlabelled collection when nothing overlaps', () => { - const { collections } = plan(pass('1', [0, 2, 4])); - - expect(collections[0].label).toBeNull(); - expect(partValue(collections[0], 'acquisition')).toBeNull(); - expect(collections[0].warnings).toEqual([]); + expect(uidsOf(collectionWith(collections, 'acq1-0'))).toEqual([ + 'acq1-0', + 'acq1-1', + ]); + expect(collectionWith(collections, 'acq2-0').label).toBe('acquisition 2'); }); it('warns that an unevenly spaced collection is not one regular volume', () => { // Two 4mm runs with a gap between them, as the bilateral sagittal slabs // of idcSeriesFixtures.ts are. One collection, but no single lattice. - const { collections } = plan(pass('1', [0, 4, 8, 50, 54, 58])); + const collections = plan(pass('1', [0, 4, 8, 50, 54, 58])); expect(collections).toHaveLength(1); expect(collections[0].warnings).toEqual([IRREGULAR_VOLUME_WARNING]); }); - it('leaves an evenly spaced collection unwarned', () => { - const { collections } = plan(pass('1', [0, 4, 8, 12])); + it('leaves an evenly spaced collection unwarned and unlabelled', () => { + const collections = plan(pass('1', [0, 4, 8, 12])); + expect(collections[0].label).toBeNull(); expect(collections[0].warnings).toEqual([]); }); @@ -675,10 +520,9 @@ describe('planDicomCollections semantic partition', () => { }) ); - const { collections } = plan(stack); + const collections = plan(stack); expect(collections).toHaveLength(1); - expect(collections[0].order).toBe('spatial'); expect(uidsOf(collections[0])).toEqual(stack.map((m) => m.sopInstanceUid)); expect(collections[0].warnings).toEqual([IN_PLANE_SHIFT_WARNING]); }); @@ -699,7 +543,7 @@ describe('planDicomCollections semantic partition', () => { it.each(['a-walked-first', 'z-walked-last'])( 'takes the axes most slices declare when the stray one is %s', (strayUid) => { - const { collections } = plan(wideStack(strayUid, 0.0002)); + const collections = plan(wideStack(strayUid, 0.0002)); expect(collections).toHaveLength(1); expect(collections[0].orientation).toEqual(IDENTITY_ORIENTATION); @@ -708,7 +552,7 @@ describe('planDicomCollections semantic partition', () => { ); it('warns when a slice leans off the volume axes by more than a tenth of a millimetre', () => { - const { collections } = plan(wideStack('wide-stray', 0.001)); + const collections = plan(wideStack('wide-stray', 0.001)); expect(collections).toHaveLength(1); expect(collections[0].orientation).toEqual(IDENTITY_ORIENTATION); @@ -721,147 +565,15 @@ describe('planDicomCollections semantic partition', () => { pixelSpacing: null, })); - expect(plan(members).collections[0].warnings).not.toContain( - NONPARALLEL_SLICES_WARNING - ); - }); - - it('warns about a repeated position no axis separates', () => { - const { collections } = plan(pass('1', [0, 2, 2, 4])); - - expect(collections).toHaveLength(1); - expect(collections[0].warnings).toEqual([REPEATED_POSITIONS_WARNING]); - }); - - // A later import can bring a slice whose geometry cannot be read. Merging it - // back in would undo a separation the positions of the other members - // already earned. - it('keeps two separated acquisitions apart when a positionless member arrives', () => { - const first = pass('1', [0, 2, 4]); - const second = pass('2', [1, 3, 5]); - const before = plan([...first, ...second]); - - const blind = makeFacts('blind', { - projectedPosition: null, - position: null, - instanceNumber: 7, - }); - const after = plan([...first, ...second, blind]); - - expect(before.collections).toHaveLength(2); - expect(after.collections).toHaveLength(3); - - // The two evidence-backed collections survive unchanged, keys included. - before.collections.forEach((collection) => { - const kept = collectionWith( - after.collections, - collection.members[0].sopInstanceUid! - ); - expect(kept.key).toEqual(collection.key); - expect(uidsOf(kept)).toEqual(uidsOf(collection)); - expect(kept.warnings).toEqual([]); - }); - - const unknown = collectionWith(after.collections, 'blind'); - expect(uidsOf(unknown)).toEqual(['blind']); - expect(unknown.warnings).toEqual([UNREADABLE_POSITION_WARNING]); - expect(unknown.key).not.toEqual(before.collections[0].key); - }); - - it('gives the two passes distinct, collision-free keys', () => { - const { collections } = plan([...pass('1', [0, 2]), ...pass('2', [1, 3])]); - - expect(() => - validateCollections( - collections.flatMap((c) => c.members), - collections - ) - ).not.toThrow(); - }); -}); - -describe('validateCollections', () => { - const a = makeFacts('uid-a'); - const b = makeFacts('uid-b'); - - const collectionOf = ( - members: InstanceFacts[], - parts: Array<[string, string | null]> - ): DicomCollection => ({ - key: { seriesKey: SERIES_KEY, parts }, - members, - order: 'input', - reconstruction: { - kind: 'regular', - sliceSpacing: null, - slots: members.map((_, index) => index), - }, - orientation: null, - label: null, - diagnostics: [], - warnings: [], - }); - - const partsOne: Array<[string, string | null]> = [['orientation', 'one']]; - const partsTwo: Array<[string, string | null]> = [['orientation', 'two']]; - - it('accepts a conserving, collision-free plan', () => { - expect(() => - validateCollections( - [a, b], - [collectionOf([a], partsOne), collectionOf([b], partsTwo)] - ) - ).not.toThrow(); - }); - - it('rejects an instance that landed in no collection', () => { - expect(() => - validateCollections([a, b], [collectionOf([a], partsOne)]) - ).toThrow('uid-b'); - }); - - it('rejects an instance that landed in two collections', () => { - expect(() => - validateCollections( - [a], - [collectionOf([a], partsOne), collectionOf([a], partsTwo)] - ) - ).toThrow('uid-a'); - }); - - it('accepts an instance listed twice when it is placed twice', () => { - expect(() => - validateCollections([a, a], [collectionOf([a, a], partsOne)]) - ).not.toThrow(); - }); - - it('rejects an instance listed twice but placed once', () => { - expect(() => - validateCollections([a, a], [collectionOf([a], partsOne)]) - ).toThrow('uid-a'); - }); - - it('rejects a member that was never one of the instances', () => { - expect(() => - validateCollections([a], [collectionOf([a, b], partsOne)]) - ).toThrow('uid-b'); - }); - - it('rejects two collections sharing a key', () => { - expect(() => - validateCollections( - [a, b], - [collectionOf([a], partsOne), collectionOf([b], partsOne)] - ) - ).toThrow(/key/i); + expect(plan(members)[0].warnings).not.toContain(NONPARALLEL_SLICES_WARNING); }); }); describe('independent multi-frame instances', () => { it('keeps anonymous clip keys stable when an earlier clip is removed', () => { const clips = [0, 1, 2].map(() => makeFacts(null, { numberOfFrames: '3' })); - const before = plan(clips.slice(0, 2)).collections; - const after = plan(clips.slice(1)).collections; + const before = plan(clips.slice(0, 2)); + const after = plan(clips.slice(1)); const keyOf = (collections: DicomCollection[], member: InstanceFacts) => collections.find((collection) => collection.members.includes(member))! .key; @@ -871,7 +583,7 @@ describe('independent multi-frame instances', () => { }); it.each([null, 0])( - 'keeps equal-shaped clips separate at position %s', + 'keeps equal-shaped clips separate and unlabelled at position %s', (position) => { const instances = ['clip-a', 'clip-b'].map((uid) => makeFacts(uid, { @@ -880,11 +592,12 @@ describe('independent multi-frame instances', () => { projectedPosition: position, }) ); - const collections = plan(instances).collections; + const collections = plan(instances); expect(collections.map((c) => uidsOf(c))).toEqual([ ['clip-a'], ['clip-b'], ]); + expect(collections.map((c) => c.label)).toEqual([null, null]); expect(new Set(collections.map((c) => JSON.stringify(c.key))).size).toBe( 2 ); @@ -905,30 +618,40 @@ describe('acquisition descriptors', () => { zs.map((z) => makeFacts(`${uid}-${z}`, { projectedPosition: z, ...facts })); it.each(descriptors)( - 'keeps independent single-plane images apart when %s differs', + 'separates and labels overlapping stacks by %s', (fact, value) => { - const { collections } = plan([ - makeFacts('first', { [fact]: '1' }), - makeFacts('second', { [fact]: value }), + const collections = plan([ + ...run('first', [0, 2, 4], { [fact]: '1' }), + ...run('second', [1, 3, 5], { [fact]: value }), ]); expect(collections).toHaveLength(2); - expect( - collections.map((collection) => collection.members.length) - ).toEqual([1, 1]); - expect( - collections.every( - (collection) => collection.reconstruction.kind === 'regular' - ) - ).toBe(true); + expect(collections.every((collection) => collection.label !== null)).toBe( + true + ); expect( new Set(collections.map((collection) => collection.label)).size ).toBe(2); } ); + it('keeps independent single-plane images apart when a descriptor differs', () => { + const collections = plan([ + makeFacts('first', { seriesDate: '20240101' }), + makeFacts('second', { seriesDate: '20240202' }), + ]); + + expect(collections.map((collection) => collection.label)).toEqual([ + 'date 20240101', + 'date 20240202', + ]); + expect( + collections.map((collection) => collection.reconstruction.kind) + ).toEqual(['regular', 'regular']); + }); + it('keeps an unknown sequence separate from a named sequence on one plane', () => { - const { collections } = plan([ + const collections = plan([ makeFacts('unknown', { sequenceName: null }), makeFacts('known', { sequenceName: '*ep_b0' }), ]); @@ -939,55 +662,30 @@ describe('acquisition descriptors', () => { ]); }); - it.each(descriptors)( - 'keeps a stack whole across one differing %s', - (fact, value) => { - const slices = run('slice', [0, 1, 2, 3, 4], {}); - slices[2] = { ...slices[2], [fact]: value }; - const { collections } = plan(slices); + it('keeps a stack whole across one differing descriptor', () => { + const slices = run('slice', [0, 1, 2, 3, 4], {}); + slices[2] = { ...slices[2], sliceThickness: '2' }; + const collections = plan(slices); - expect(collections).toHaveLength(1); - expect(collections[0].reconstruction).toEqual({ - kind: 'regular', - sliceSpacing: 1, - slots: [0, 1, 2, 3, 4], - }); - } - ); - - it.each(descriptors)( - 'keeps adjoining stacks together across %s', - (fact, value) => { - const { collections } = plan([ - ...run('first', [0, 1, 2], { [fact]: '1' }), - ...run('second', [3, 4, 5], { [fact]: value }), - ]); - - expect(collections).toHaveLength(1); - expect(collections[0].reconstruction.kind).toBe('regular'); - } - ); + expect(collections).toHaveLength(1); + expect(collections[0].reconstruction).toEqual({ + kind: 'regular', + sliceSpacing: 1, + }); + }); - it.each(descriptors)( - 'separates and labels overlapping stacks by %s', - (fact, value) => { - const { collections } = plan([ - ...run('first', [0, 2, 4], { [fact]: '1' }), - ...run('second', [1, 3, 5], { [fact]: value }), - ]); + it('keeps adjoining stacks together across a descriptor', () => { + const collections = plan([ + ...run('first', [0, 1, 2], { seriesNumber: '1' }), + ...run('second', [3, 4, 5], { seriesNumber: '2' }), + ]); - expect(collections).toHaveLength(2); - expect(collections.every((collection) => collection.label !== null)).toBe( - true - ); - expect( - new Set(collections.map((collection) => collection.label)).size - ).toBe(2); - } - ); + expect(collections).toHaveLength(1); + expect(collections[0].reconstruction.kind).toBe('regular'); + }); it('labels DWI stacks by b-value when sequence names also differ', () => { - const { collections } = plan([ + const collections = plan([ ...run('b0', [0, 1, 2], { sequenceName: '*ep_b0', diffusionBValue: '0' }), ...run('b1000', [0, 1, 2], { sequenceName: '*ep_b1000t', @@ -1010,7 +708,7 @@ describe('acquisition descriptors', () => { }); it('labels incompatible pixel shapes', () => { - const { collections } = plan([ + const collections = plan([ makeFacts('small', { rows: '4' }), makeFacts('large', { rows: '8' }), ]); @@ -1022,7 +720,7 @@ describe('acquisition descriptors', () => { }); it('keeps incompatible acquisition descriptors apart when geometry is unreadable', () => { - const { collections } = plan( + const collections = plan( ['first', 'second'].map((sequenceName) => makeFacts(sequenceName, { sequenceName, @@ -1032,9 +730,12 @@ describe('acquisition descriptors', () => { ) ); - expect(collections).toHaveLength(2); - expect( - new Set(collections.map((collection) => collection.label)).size - ).toBe(2); + expect(collections.map((collection) => collection.label).sort()).toEqual([ + 'sequence first', + 'sequence second', + ]); + expect(collections.flatMap((collection) => collection.warnings)).toEqual( + [] + ); }); }); diff --git a/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts b/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts index 6142deebb..1e8d49fb4 100644 --- a/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts +++ b/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts @@ -1,24 +1,16 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; import { describe, expect, it } from 'vitest'; import { Tags } from '../../metadata/dicomTags'; -import { readInstanceFacts as readStructuredFacts } from '../instanceFacts'; import { reconstructVolume } from '../reconstructVolume'; -import { - bilateralSagittalSlabs, - type IdcSeriesFixture, -} from './idcSeriesFixtures'; - -// An axial slice at z, read through the fact reader so the fixtures stay in -// the tag vocabulary the real data uses. -const slice = (z: number, tags: Record = {}) => - readInstanceFacts([ - ...Object.entries({ - [Tags.ImageOrientationPatient]: '1\\0\\0\\0\\1\\0', - [Tags.ImagePositionPatient]: `0\\0\\${z}`, - [Tags.PixelSpacing]: '0.5\\0.5', - ...tags, - }), - ]); +import { bilateralSagittalSlabs } from './idcSeriesFixtures'; +import { sliceFacts, type SliceOptions } from './sliceFixture'; + +// An axial slice at z on a half millimetre grid. +const slice = (z: number | null, options: SliceOptions = {}) => + sliceFacts({ + z, + ...options, + tags: { [Tags.PixelSpacing]: '0.5\\0.5', ...options.tags }, + }); const stack = (zs: number[]) => zs.map((z) => slice(z)); @@ -26,23 +18,8 @@ const stack = (zs: number[]) => zs.map((z) => slice(z)); // sideways of the last as the table advances along z. const tiltedSlice = (z: number, theta: number) => slice(z, { - [Tags.ImageOrientationPatient]: [ - 1, - 0, - 0, - 0, - Math.cos(theta), - Math.sin(theta), - ].join('\\'), - }); - -const fixtureSlices = (fixture: IdcSeriesFixture) => - fixture - .groups!.flatMap((group) => group.zs.map((z) => slice(z))) - .sort( - (left, right) => - (left.projectedPosition as number) - (right.projectedPosition as number) - ); + orientation: [1, 0, 0, 0, Math.cos(theta), Math.sin(theta)].join('\\'), + }); describe('reconstructVolume', () => { it('measures an evenly spaced stack and maps every member to its slot', () => { @@ -50,7 +27,6 @@ describe('reconstructVolume', () => { expect(result.kind).toBe('regular'); expect(result.sliceSpacing).toBeCloseTo(4, 12); - expect(result.slots).toEqual([0, 1, 2, 3, 4]); }); it('derives the spacing from the endpoints once every gap matches', () => { @@ -65,7 +41,6 @@ describe('reconstructVolume', () => { expect(result.kind).toBe('regular'); expect(result.sliceSpacing).toBeNull(); - expect(result.slots).toEqual([0]); }); it('accepts a single plane without patient position or orientation', () => { @@ -77,7 +52,7 @@ describe('reconstructVolume', () => { pixelSpacing: null, }, ]) - ).toEqual({ kind: 'regular', sliceSpacing: null, slots: [0] }); + ).toEqual({ kind: 'regular', sliceSpacing: null }); }); it('does not treat a positionless multi-frame instance as a single plane', () => { @@ -106,7 +81,11 @@ describe('reconstructVolume', () => { // The two slabs are 4mm stacks 42.439mm apart. Endpoint distance over slice // count would call that a 4.59mm lattice, which describes neither slab. it('calls the bilateral sagittal slabs an irregular stack', () => { - const members = fixtureSlices(bilateralSagittalSlabs); + const members = stack( + bilateralSagittalSlabs + .flatMap((group) => group.zs) + .sort((left, right) => left - right) + ); const result = reconstructVolume(members); @@ -137,12 +116,7 @@ describe('reconstructVolume', () => { }); it('reports a member whose position cannot be read as irregular', () => { - const blind = readInstanceFacts([ - [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], - [Tags.PixelSpacing, '0.5\\0.5'], - ]); - - const result = reconstructVolume([...stack([0, 4]), blind]); + const result = reconstructVolume([...stack([0, 4]), slice(null)]); expect(result).toMatchObject({ kind: 'irregular', @@ -152,11 +126,9 @@ describe('reconstructVolume', () => { }); it('reports a slice shifted within its own plane as irregular', () => { - const shifted = readInstanceFacts([ - [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], - [Tags.ImagePositionPatient, '0\\30\\8'], - [Tags.PixelSpacing, '0.5\\0.5'], - ]); + const shifted = slice(null, { + tags: { [Tags.ImagePositionPatient]: '0\\30\\8' }, + }); const result = reconstructVolume([...stack([0, 4]), shifted]); @@ -182,11 +154,10 @@ describe('reconstructVolume', () => { // The table stepped 3mm a slice, which is the extent ITK's series reader // keeps too; the shear is warned about, not folded into the spacing. expect(result.sliceSpacing).toBeCloseTo(3, 12); - expect(result.slots).toEqual([0, 1, 2, 3]); }); it('reports two in-plane sample spacings as irregular', () => { - const coarse = slice(8, { [Tags.PixelSpacing]: '0.6\\0.6' }); + const coarse = slice(8, { tags: { [Tags.PixelSpacing]: '0.6\\0.6' } }); const result = reconstructVolume([...stack([0, 4]), coarse]); @@ -198,13 +169,9 @@ describe('reconstructVolume', () => { }); it('steps a stack whose orientation cannot be read by its positions', () => { - const blind = (z: number) => - readInstanceFacts([ - [Tags.ImagePositionPatient, `0\\0\\${z}`], - [Tags.PixelSpacing, '0.5\\0.5'], - ]); - - const result = reconstructVolume([0, 4, 8].map(blind)); + const result = reconstructVolume( + [0, 4, 8].map((z) => slice(z, { orientation: null })) + ); expect(result).toMatchObject({ kind: 'irregular', @@ -213,6 +180,26 @@ describe('reconstructVolume', () => { expect(result.sliceSpacing).toBeCloseTo(4, 12); }); + it('reports positions that repeat out of order as repeated', () => { + const result = reconstructVolume(stack([0, 4, 8, 0, 4, 8])); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'repeated-position', + }); + }); + + // Frames of one instance are judged in stored order. + it('reports distinct positions stored out of order as uneven, not repeated', () => { + const result = reconstructVolume(stack([0, 2, 4, 1, 3, 5])); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'uneven-slice-spacing', + }); + expect(result.sliceSpacing).toBeCloseTo(2, 12); + }); + it('has no step for members that never move', () => { const result = reconstructVolume(stack([5, 5, 5])); @@ -233,20 +220,16 @@ describe('reconstructVolume', () => { reason: 'in-plane-shift', }); }); -}); - -function readInstanceFacts(tags: Iterable) { - return readStructuredFacts(datasetFromTags(tags)); -} -it.each([0.01, 0.05, 0.1])( - 'detects a missing slice in a %s mm stack', - (step) => { - expect( - reconstructVolume(stack([0, 1, 2, 4, 5, 6].map((i) => i * step))) - ).toMatchObject({ - kind: 'irregular', - reason: 'uneven-slice-spacing', - }); - } -); + it.each([0.01, 0.05, 0.1])( + 'detects a missing slice in a %s mm stack', + (step) => { + expect( + reconstructVolume(stack([0, 1, 2, 4, 5, 6].map((i) => i * step))) + ).toMatchObject({ + kind: 'irregular', + reason: 'uneven-slice-spacing', + }); + } + ); +}); diff --git a/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts b/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts deleted file mode 100644 index 56a0c8069..000000000 --- a/packages/dicom/core/collections/__tests__/registryAcrossImports.spec.ts +++ /dev/null @@ -1,456 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { getDatasetTag } from '../../metadata/datasetAccess'; -import { Tags } from '../../metadata/dicomTags'; -import type { Instance } from '../../instance/readInstance'; -import { instanceFor } from '@/tests/dicomDataset'; -import { - emptyRegistry, - forgetCollection, - isRegistered, - registerInstances, - type InstanceCollectionUpdate, -} from '../instanceRegistry'; -import { UNREADABLE_POSITION_WARNING } from '../planDicomCollections'; -import { mergingInstances, tilt } from '@/tests/dicomOrientationFixtures'; -import { SERIES_UID, sliceDataset, type SliceOptions } from './sliceFixture'; - -const sliceInstance = (options: SliceOptions = {}) => - instanceFor(sliceDataset(options)); - -const sops = (instances: readonly Instance[]) => - instances.map((instance) => - getDatasetTag(instance.dataset, Tags.SOPInstanceUID) - ); - -const byId = (updates: InstanceCollectionUpdate[]) => - [...updates].sort((left, right) => (left.id < right.id ? -1 : 1)); - -/** Keeps each returned state, as the store that owns the registry does. */ -function createRegistry() { - let state = emptyRegistry; - return { - register: (batch: Instance[]) => { - const result = registerInstances(state, batch); - state = result.state; - return result; - }, - forget: (id: string) => { - state = forgetCollection(state, id); - }, - has: (instance: Instance) => isRegistered(state, instance), - }; -} - -const collidingMultiframes = (series = SERIES_UID) => - ['1', null].map((sop) => - sliceInstance({ sop, series, tags: { [Tags.NumberOfFrames]: '2' } }) - ); - -describe('instance registry across imports', () => { - it('keeps anonymous clip ownership stable after deletion and another import', () => { - const registry = createRegistry(); - const clips = [0, 1, 2].map(() => - sliceInstance({ - sop: null, - tags: { [Tags.NumberOfFrames]: '3' }, - }) - ); - const before = registry.register(clips.slice(0, 2)).updates; - const first = before.find((update) => update.members.includes(clips[0]))!; - const second = before.find((update) => update.members.includes(clips[1]))!; - expect(first.members).toEqual([clips[0]]); - registry.forget(first.id); - - const after = registry.register([clips[2]]); - - expect(after.removed).not.toContain(second.id); - const updated = after.updates.find((update) => update.id === second.id); - if (updated) expect(updated.members[0]).toBe(clips[1]); - expect(registry.has(clips[1])).toBe(true); - expect(registry.has(clips[0])).toBe(false); - }); - - it('does not confuse a numeric UID with an anonymous clip identity', () => { - const registry = createRegistry(); - const clips = collidingMultiframes(); - const { updates } = registry.register(clips); - - expect(updates).toHaveLength(2); - expect(new Set(updates.map((update) => update.id)).size).toBe(2); - expect(new Set(updates.flatMap((update) => update.members))).toEqual( - new Set(clips) - ); - clips.forEach((clip) => expect(registry.has(clip)).toBe(true)); - }); - - it('plans one consistent series into one ordered collection', () => { - const registry = createRegistry(); - const first = sliceInstance({ sop: 'a', z: 0 }); - const second = sliceInstance({ sop: 'b', z: 1 }); - const third = sliceInstance({ sop: 'c', z: 2 }); - - // Arrival order deliberately differs from slice order. - const { updates } = registry.register([third, first, second]); - - expect(updates).toHaveLength(1); - const [update] = updates; - expect(sops(update.members)).toEqual(['a', 'b', 'c']); - expect(update.provenance).toEqual(update.members); - expect(update.collection.order).toBe('spatial'); - expect(update.collection.diagnostics).toEqual([]); - }); - - it('aligns the instance members with the planned facts', () => { - const registry = createRegistry(); - const instances = [ - sliceInstance({ sop: 'a', z: 2 }), - sliceInstance({ sop: 'b', z: 0 }), - ]; - - const { updates } = registry.register(instances); - const [update] = updates; - - expect(update.collection.members.map((m) => m.sopInstanceUid)).toEqual( - sops(update.members) - ); - }); - - // The DICOMweb store reconciles its own series keyed progress against the - // loaded volume id by prefix. - it('mints an id that starts with the series instance uid', () => { - const registry = createRegistry(); - - const { updates } = registry.register([sliceInstance({ sop: 'a' })]); - - expect(updates[0].id.startsWith(SERIES_UID)).toBe(true); - }); - - it('keeps the collection id and grows its members across two batches', () => { - const registry = createRegistry(); - const first = sliceInstance({ sop: 'a', z: 0 }); - const second = sliceInstance({ sop: 'b', z: 1 }); - - const [firstUpdate] = registry.register([first]).updates; - const [secondUpdate] = registry.register([second]).updates; - - expect(secondUpdate.id).toBe(firstUpdate.id); - expect(sops(secondUpdate.members)).toEqual(['a', 'b']); - // Every member reports its provenance, not just the one the batch brought. - expect(secondUpdate.provenance).toEqual([first, second]); - }); - - it('orders a late arriving earlier slice into its planned position', () => { - const registry = createRegistry(); - const first = sliceInstance({ sop: 'a', z: 0 }); - const second = sliceInstance({ sop: 'b', z: 1 }); - - registry.register([second]); - const [update] = registry.register([first]).updates; - - expect(sops(update.members)).toEqual(['a', 'b']); - expect(update.provenance).toEqual([first, second]); - }); - - const POSITIONS: Record = { a: 0, b: 1, c: 2 }; - - const loadBatches = (batches: ReadonlyArray>) => { - const registry = createRegistry(); - return batches.reduce( - (_, batch) => - registry.register( - batch.map((sop) => sliceInstance({ sop, z: POSITIONS[sop] })) - ).updates, - [] as InstanceCollectionUpdate[] - ); - }; - - it.each([ - ['one batch', [['a', 'b', 'c']]], - ['two batches', [['a'], ['b', 'c']]], - ['two batches in reverse', [['b', 'c'], ['a']]], - ['one slice at a time', [['c'], ['a'], ['b']]], - [ - 'a repeated batch', - [ - ['a', 'b', 'c'], - ['a', 'b', 'c'], - ], - ], - ] as const)( - 'plans the whole series into one collection when loaded as %s', - (_case, batches) => { - const updates = loadBatches(batches); - - expect(updates).toHaveLength(1); - expect(sops(updates[0].members)).toEqual(['a', 'b', 'c']); - } - ); - - it('gives one series the same id however the slices are batched', () => { - const idOf = (batches: ReadonlyArray>) => - loadBatches(batches)[0].id; - - const oneBatch = idOf([['a', 'b', 'c']]); - expect(idOf([['a'], ['b', 'c']])).toBe(oneBatch); - expect(idOf([['b', 'c'], ['a']])).toBe(oneBatch); - expect( - idOf([ - ['a', 'b', 'c'], - ['a', 'b', 'c'], - ]) - ).toBe(oneBatch); - }); - - it.each([ - { sop: ' a ', series: ` ${SERIES_UID} ` }, - { sop: null, series: SERIES_UID }, - { sop: null, series: null }, - { sop: '', series: SERIES_UID }, - { sop: ' ', series: '' }, - { sop: 'a', series: ' ' }, - ])('recognizes only the canonical member for identity %j', (identity) => { - const registry = createRegistry(); - const original = sliceInstance(identity); - const duplicate = sliceInstance(identity); - - const { updates } = registry.register([original]); - - expect(registry.has(original)).toBe(true); - expect(registry.has(duplicate)).toBe(false); - registry.forget(updates[0].id); - expect(registry.has(original)).toBe(false); - }); - - it('counts one instance once however often a batch repeats it', () => { - const registry = createRegistry(); - const instance = sliceInstance({ sop: 'a', z: 0 }); - - const [update] = registry.register([instance, instance]).updates; - - expect(update.members).toEqual([instance]); - }); - - it('re-registers an anonymous instance without duplicating it', () => { - const registry = createRegistry(); - const instance = sliceInstance({ sop: null, z: 0 }); - - registry.register([instance]); - const [update] = registry.register([instance]).updates; - - expect(update.members).toEqual([instance]); - }); - - it('splits one batch of incompatible instances into two collections', () => { - const registry = createRegistry(); - const scout = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); - const slices = [ - sliceInstance({ sop: 'a', z: 0 }), - sliceInstance({ sop: 'b', z: 1 }), - ]; - - const { updates } = registry.register([scout, ...slices]); - - expect(updates).toHaveLength(2); - const membership = updates.map((update) => sops(update.members)); - expect(membership).toContainEqual(['scout']); - expect(membership).toContainEqual(['a', 'b']); - expect(updates[0].id).not.toBe(updates[1].id); - updates.forEach((update) => - expect(update.id.startsWith(SERIES_UID)).toBe(true) - ); - }); - - it('leaves an untouched collection out of a later batch', () => { - const registry = createRegistry(); - const scout = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); - const slice = sliceInstance({ sop: 'a', z: 0 }); - - const [sliceUpdate] = registry.register([slice]).updates; - const { updates } = registry.register([scout]); - - expect(updates).toHaveLength(1); - expect(sops(updates[0].members)).toEqual(['scout']); - expect(updates[0].id).not.toBe(sliceUpdate.id); - }); - - // The positions of the two passes already earned their separation; a later - // slice nothing spatial can be said about must not dissolve it. - it('keeps two separated acquisitions when a positionless instance arrives later', () => { - const registry = createRegistry(); - const first = [0, 2, 4].map((z) => - sliceInstance({ - sop: `one-${z}`, - z, - tags: { [Tags.AcquisitionNumber]: '1' }, - }) - ); - const second = [1, 3, 5].map((z) => - sliceInstance({ - sop: `two-${z}`, - z, - tags: { [Tags.AcquisitionNumber]: '2' }, - }) - ); - - const separated = byId(registry.register([...first, ...second]).updates); - expect(separated).toHaveLength(2); - - const blind = sliceInstance({ sop: 'blind', z: null, instanceNumber: 9 }); - const { updates, removed } = registry.register([blind]); - - // Neither committed collection dissolved, and neither was re-planned. - expect(removed).toEqual([]); - expect(updates).toHaveLength(1); - expect(updates[0].id).not.toBe(separated[0].id); - expect(updates[0].id).not.toBe(separated[1].id); - expect(sops(updates[0].members)).toEqual(['blind']); - expect(updates[0].collection.warnings).toEqual([ - UNREADABLE_POSITION_WARNING, - ]); - - // The two volumes still hold exactly the slices of their own pass. - const again = byId(registry.register([...first, ...second]).updates); - expect(again.map((update) => update.id)).toEqual( - separated.map((update) => update.id) - ); - expect(again.map((update) => sops(update.members))).toEqual([ - sops(separated[0].members), - sops(separated[1].members), - ]); - expect(again.flatMap((update) => update.collection.warnings)).toEqual([]); - }); - - it('reports a collection a later batch re-registers unchanged', () => { - const registry = createRegistry(); - const slice = sliceInstance({ sop: 'a', z: 0 }); - - registry.register([slice]); - const { updates } = registry.register([slice]); - - expect(updates).toHaveLength(1); - expect(updates[0].provenance).toEqual([slice]); - }); - - const merging = () => mergingInstances(sliceInstance); - - it('reports a collection that lost members without gaining an instance', () => { - const registry = createRegistry(); - const straight = sliceInstance({ - sop: 'sop-2', - z: 0, - orientation: tilt(0), - }); - const near = sliceInstance({ sop: 'sop-3', z: 1, orientation: tilt(0.01) }); - // Agrees with the straight instance but not with the near one, so the - // bucket it seeds as the new reference leaves the near one behind. - const splitter = sliceInstance({ - sop: 'sop-1', - z: 2, - orientation: tilt(-0.005), - }); - - const first = registry.register([straight, near]); - expect(first.updates).toHaveLength(1); - - const second = registry.register([splitter]); - - const orphaned = second.updates.find( - (update) => !update.members.includes(splitter) - ); - expect(orphaned).toBeDefined(); - expect(sops(orphaned!.members)).toEqual(['sop-3']); - expect(second.removed).toEqual([first.updates[0].id]); - }); - - it('replans without the instances a forgotten collection held', () => { - const registry = createRegistry(); - const original = sliceInstance({ sop: 'a', z: 0 }); - const { updates } = registry.register([original]); - - registry.forget(updates[0].id); - const resupplied = sliceInstance({ sop: 'a', z: 0 }); - const second = registry.register([resupplied]); - - // Identity, not shape: the released instance is an equal but stale object. - expect(second.updates[0].members).toHaveLength(1); - expect(second.updates[0].members[0]).toBe(resupplied); - expect(second.updates[0].id).toBe(updates[0].id); - }); - - it('keeps the members a replan moved when the dissolved id is forgotten', () => { - const registry = createRegistry(); - const { between, straight, tilted } = merging(); - - registry.register([straight, tilted]); - const merged = registry.register([between]); - merged.removed.forEach((id) => registry.forget(id)); - - const third = registry.register([between]); - - expect(third.updates[0].members).toHaveLength(3); - }); - - it('forgets one collection of a series without touching the others', () => { - const registry = createRegistry(); - const scout = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); - const slice = sliceInstance({ sop: 'a', z: 0 }); - - const { updates } = registry.register([scout, slice]); - const scoutUpdate = updates.find((update) => update.members[0] === scout)!; - registry.forget(scoutUpdate.id); - - const resupplied = sliceInstance({ sop: 'scout', rows: '8', z: 0 }); - const second = registry.register([resupplied]); - - expect(second.updates).toHaveLength(1); - expect(second.updates[0].members).toHaveLength(1); - expect(second.updates[0].members[0]).toBe(resupplied); - expect(second.removed).toEqual([]); - }); - - it('surfaces the planner order and diagnostics for a positionless series', () => { - const registry = createRegistry(); - const instances = [ - sliceInstance({ sop: 'alpha', z: null, instanceNumber: 2 }), - sliceInstance({ sop: 'beta', z: null, instanceNumber: 1 }), - ]; - - const [update] = registry.register(instances).updates; - - expect(sops(update.members)).toEqual(['beta', 'alpha']); - expect(update.collection.order).toBe('instance-number'); - const diagnostics = update.collection.diagnostics.join(' '); - expect(diagnostics).toContain('alpha'); - expect(diagnostics).toContain('beta'); - }); - - it('does not mutate the batch it registers', () => { - const registry = createRegistry(); - const instances = [ - sliceInstance({ sop: 'a', z: 2 }), - sliceInstance({ sop: 'b', z: 0 }), - ]; - const order = [...instances]; - - registry.register(instances); - - expect(instances).toEqual(order); - }); -}); - -describe('registry normalization and conflicting identities', () => { - it('keeps slices with absent and explicit single-frame counts in one volume', () => { - const registry = createRegistry(); - const result = registry.register([ - sliceInstance({ sop: 'first', z: 0 }), - sliceInstance({ - sop: 'second', - z: 1, - tags: { [Tags.NumberOfFrames]: '1' }, - }), - ]); - expect(result.updates).toHaveLength(1); - expect(result.updates[0].members).toHaveLength(2); - expect(result.updates[0].collection.reconstruction.sliceSpacing).toBe(1); - }); -}); diff --git a/packages/dicom/core/collections/__tests__/sliceFixture.ts b/packages/dicom/core/collections/__tests__/sliceFixture.ts index d2c8bdcbd..4f2f94eb6 100644 --- a/packages/dicom/core/collections/__tests__/sliceFixture.ts +++ b/packages/dicom/core/collections/__tests__/sliceFixture.ts @@ -1,5 +1,6 @@ import { datasetFromTags } from '@/tests/dicomDataset'; import { Tags } from '../../metadata/dicomTags'; +import { readInstanceDetails } from '../instanceFacts'; export const SERIES_UID = '1.2.826.0.1.3680043.9.7'; export const OTHER_SERIES_UID = '1.2.826.0.1.3680043.9.8'; @@ -9,7 +10,7 @@ export type SliceOptions = { series?: string | null; z?: number | null; rows?: string; - orientation?: string; + orientation?: string | null; instanceNumber?: number | null; modality?: string; // Extra tags, keyed 'gggg|eeee'. @@ -39,8 +40,9 @@ export function sliceDataset(options: SliceOptions = {}) { [Tags.Rows, rows], [Tags.Columns, '4'], [Tags.SamplesPerPixel, '1'], - [Tags.ImageOrientationPatient, orientation], ]; + if (orientation !== null) + entries.push([Tags.ImageOrientationPatient, orientation]); if (series !== null) entries.push([Tags.SeriesInstanceUID, series]); if (sop !== null) entries.push([Tags.SOPInstanceUID, sop]); if (z !== null) entries.push([Tags.ImagePositionPatient, `0\\0\\${z}`]); @@ -50,3 +52,7 @@ export function sliceDataset(options: SliceOptions = {}) { return datasetFromTags(entries); } + +/** The planner's facts for one slice, read the way a real header is. */ +export const sliceFacts = (options: SliceOptions = {}) => + readInstanceDetails(sliceDataset(options)).facts; diff --git a/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts b/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts index 440e2c8fb..ae2f84d08 100644 --- a/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts +++ b/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts @@ -1,43 +1,31 @@ -import { datasetFromTags } from '@/tests/dicomDataset'; import { describe, it, expect } from 'vitest'; import { Tags } from '../../metadata/dicomTags'; -import { readInstanceFacts as readStructuredFacts } from '../instanceFacts'; import type { InstanceFacts } from '../planDicomCollections'; -import { - GEOMETRY_RULE, - DESCRIPTOR_AXES, - SEMANTIC_AXES, - UNREADABLE_GEOMETRY, - UNREADABLE_GEOMETRY_LABEL, - splitOverlappingAcquisitions, - type SemanticPart, -} from '../splitOverlappingAcquisitions'; +import { splitOverlappingAcquisitions } from '../splitOverlappingAcquisitions'; import { makeFacts } from './instanceFactsFixture'; import { bilateralSagittalSlabs, dceEightPhase, - dceSevenPhasePhilips, dixonDualEcho, dixonUnevenEchoes, doubledAcquisition, dwiMultiBValue, partialTemporalTags, - type IdcSeriesFixture, + type SliceGroup, } from './idcSeriesFixtures'; +import { sliceFacts } from './sliceFixture'; + +type SemanticPart = ReturnType[number]; -let nextUid = 0; +const zOf = (facts: InstanceFacts) => facts.projectedPosition as number; +const byPosition = (a: InstanceFacts, b: InstanceFacts) => zOf(a) - zOf(b); -// An axial slice at z carrying the given tags, read through the fact reader so -// the fixtures stay in the tag vocabulary the real data uses. -function slice(z: number, tags: Record = {}) { - nextUid += 1; - return readInstanceFacts([ - [Tags.SOPInstanceUID, `1.2.3.${nextUid}`], - [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], - [Tags.ImagePositionPatient, `0\\0\\${z}`], - ...Object.entries(tags), - ]); -} +const split = (members: InstanceFacts[]) => + splitOverlappingAcquisitions(members, (member) => member.projectedPosition); + +// An axial slice at z carrying the given tags. +const slice = (z: number, tags: Record = {}) => + sliceFacts({ z, tags }); // A stack of `count` slices starting at `start`, tagged with an acquisition. const stack = (acquisition: string, start: number, count: number, step = 2.5) => @@ -45,13 +33,10 @@ const stack = (acquisition: string, start: number, count: number, step = 2.5) => slice(start + i * step, { [Tags.AcquisitionNumber]: acquisition }) ); -const zOf = (facts: InstanceFacts) => facts.projectedPosition as number; -const byPosition = (a: InstanceFacts, b: InstanceFacts) => zOf(a) - zOf(b); - // Slices mirroring a real IDC series recorded in idcSeriesFixtures.ts. -const fixtureSlices = (fixture: IdcSeriesFixture) => - fixture - .groups!.flatMap((group) => group.zs.map((z) => slice(z, group.tags))) +const fixtureSlices = (groups: SliceGroup[]) => + groups + .flatMap((group) => group.zs.map((z) => slice(z, group.tags))) .sort(byPosition); const labels = (parts: SemanticPart[]) => @@ -63,41 +48,19 @@ const partLabelled = (parts: SemanticPart[], label: string | null) => { return found; }; -const partValue = (part: SemanticPart, rule: string) => { - const entry = part.parts.find(([name]) => name === rule); - if (!entry) throw new Error(`no part named ${rule}`); - return entry[1]; -}; - -const unsplitParts = SEMANTIC_AXES.map((axis) => [axis.rule, null]); - describe('splitOverlappingAcquisitions', () => { it('passes a single acquisition through as one unlabelled part', () => { const members = stack('1', 0, 5); - const parts = splitOverlappingAcquisitions(members); - - expect(parts).toEqual([ - { - parts: unsplitParts, - members, - label: null, - repeatedPositions: false, - unreadablePositions: false, - }, - ]); - }); - - it('names one key part per axis, in axis order, split or not', () => { - const parts = splitOverlappingAcquisitions(stack('1', 0, 3)); + const parts = split(members); - expect(parts[0].parts.map(([rule]) => rule)).toEqual([ - 'acquisition', - 'phase', - 'echo', - 'b-value', - ...DESCRIPTOR_AXES.map((axis) => axis.rule), - ]); + expect(parts).toHaveLength(1); + expect(parts[0]).toMatchObject({ + members, + label: null, + repeatedPositions: false, + unreadablePositions: false, + }); }); it('separates overlapping acquisitions merged into one series', () => { @@ -109,9 +72,7 @@ describe('splitOverlappingAcquisitions', () => { const acq2 = stack('2', -19.25, 6); const acq3 = stack('3', -18.5, 4); - const parts = splitOverlappingAcquisitions( - [...acq1, ...acq2, ...acq3].sort(byPosition) - ); + const parts = split([...acq1, ...acq2, ...acq3].sort(byPosition)); expect(labels(parts)).toEqual([ 'acquisition 1', @@ -121,13 +82,6 @@ describe('splitOverlappingAcquisitions', () => { expect(partLabelled(parts, 'acquisition 1').members).toEqual(acq1); expect(partLabelled(parts, 'acquisition 2').members).toEqual(acq2); expect(partLabelled(parts, 'acquisition 3').members).toEqual(acq3); - expect(partLabelled(parts, 'acquisition 2').parts).toEqual([ - ['acquisition', '2'], - ['phase', null], - ['echo', null], - ['b-value', null], - ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), - ]); expect(parts.every((part) => !part.repeatedPositions)).toBe(true); }); @@ -143,7 +97,7 @@ describe('splitOverlappingAcquisitions', () => { ...stack('1', -245.25, 56, 5), ].sort(byPosition); - const parts = splitOverlappingAcquisitions(merged); + const parts = split(merged); expect(parts).toHaveLength(1); expect(parts[0].members).toEqual(merged); @@ -159,25 +113,9 @@ describe('splitOverlappingAcquisitions', () => { stack(String(20 + i), i * 25, 10) ); - const parts = splitOverlappingAcquisitions(groups.flat().sort(byPosition)); - - expect(parts).toHaveLength(1); - }); - - it('tolerates quantized whole-body PET positions', () => { - // IDC series - // 1.3.6.1.4.1.14519.5.2.1.7009.2403.337074050757748643824459343650 - // ("WB_3D_NON-AC"): whole-body PET stepping by 3.27mm with the occasional - // 3.35mm step from printing precision. One acquisition, nothing to - // separate. - const members = [0, 3.27, 6.54, 9.89, 13.16, 16.43].map((z) => - slice(z, { [Tags.AcquisitionNumber]: '1' }) - ); - - const parts = splitOverlappingAcquisitions(members); + const parts = split(groups.flat().sort(byPosition)); expect(parts).toHaveLength(1); - expect(parts[0].repeatedPositions).toBe(false); }); it('leaves repeat scans of one plane whole and flags the repetition', () => { @@ -190,17 +128,15 @@ describe('splitOverlappingAcquisitions', () => { slice(-82.89, { [Tags.AcquisitionNumber]: String(i + 1) }) ); - const parts = splitOverlappingAcquisitions(members); + const parts = split(members); - expect(parts).toEqual([ - { - parts: unsplitParts, - members, - label: null, - repeatedPositions: true, - unreadablePositions: false, - }, - ]); + expect(parts).toHaveLength(1); + expect(parts[0]).toMatchObject({ + members, + label: null, + repeatedPositions: true, + unreadablePositions: false, + }); }); it('does not fan out a counter stamped per slice over one repeated position', () => { @@ -210,7 +146,7 @@ describe('splitOverlappingAcquisitions', () => { slice(z, { [Tags.AcquisitionNumber]: String(i + 1) }) ); - const parts = splitOverlappingAcquisitions(members); + const parts = split(members); expect(parts).toHaveLength(1); expect(parts[0].label).toBeNull(); @@ -222,7 +158,7 @@ describe('splitOverlappingAcquisitions', () => { byPosition ); - const parts = splitOverlappingAcquisitions(members); + const parts = split(members); expect(parts).toHaveLength(1); expect(parts[0].repeatedPositions).toBe(true); @@ -243,9 +179,7 @@ describe('splitOverlappingAcquisitions', () => { slice(5, { [tag]: '4' }), ]; - const parts = splitOverlappingAcquisitions( - [...scans, ...remainder].sort(byPosition) - ); + const parts = split([...scans, ...remainder].sort(byPosition)); expect(labels(parts)).toEqual([ `${rule} 1`, @@ -253,7 +187,6 @@ describe('splitOverlappingAcquisitions', () => { `${rule} mixed`, ]); expect(partLabelled(parts, `${rule} mixed`).members).toEqual(remainder); - expect(partValue(partLabelled(parts, `${rule} mixed`), rule)).toBeNull(); } ); @@ -266,7 +199,7 @@ describe('splitOverlappingAcquisitions', () => { }) ); - const parts = splitOverlappingAcquisitions([...scans, ...contrasts]); + const parts = split([...scans, ...contrasts]); expect(labels(parts)).toEqual([ 'acquisition 1', @@ -293,9 +226,7 @@ describe('splitOverlappingAcquisitions', () => { }) ); - const parts = splitOverlappingAcquisitions( - [...volume, ...monitoring].sort(byPosition) - ); + const parts = split([...volume, ...monitoring].sort(byPosition)); expect(labels(parts)).toEqual(['acquisition 1', 'acquisition 2']); expect(partLabelled(parts, 'acquisition 2').members).toHaveLength(20); @@ -307,36 +238,13 @@ describe('splitOverlappingAcquisitions', () => { byPosition ); - expect(labels(splitOverlappingAcquisitions(merged))).toEqual([ - 'acquisition 1', - 'acquisition 2', - ]); + expect(labels(split(merged))).toEqual(['acquisition 1', 'acquisition 2']); }); it('does not separate scans that abut without overlapping', () => { const merged = [...stack('1', 0, 4), ...stack('2', 10, 4)].sort(byPosition); - expect(splitOverlappingAcquisitions(merged)).toHaveLength(1); - }); - - it('reports repeated positions no axis separates', () => { - const members = [0, 2.5, 2.5, 5].map((z) => - slice(z, { [Tags.AcquisitionNumber]: '1' }) - ); - - const parts = splitOverlappingAcquisitions(members); - - expect(parts).toHaveLength(1); - expect(parts[0].repeatedPositions).toBe(true); - }); - - it('ignores slices with no acquisition number', () => { - const members = [0, 2.5, 5, 6.25, 8.75].map((z) => slice(z)); - - const parts = splitOverlappingAcquisitions(members); - - expect(parts).toHaveLength(1); - expect(parts[0].repeatedPositions).toBe(false); + expect(split(merged)).toHaveLength(1); }); it('holds members whose position cannot be read in a part of their own', () => { @@ -347,59 +255,36 @@ describe('splitOverlappingAcquisitions', () => { const first = stack('2', 0, 3); const second = stack('3', 1, 3); - const parts = splitOverlappingAcquisitions([blind, ...first, ...second]); + const parts = split([blind, ...first, ...second]); // The two overlapping acquisitions stay separated, and the member nothing - // spatial can be said about is diagnosed rather than merged into them. - expect(labels(parts)).toEqual([ - 'acquisition 2', - 'acquisition 3', - UNREADABLE_GEOMETRY_LABEL, - ]); - const unknown = partLabelled(parts, UNREADABLE_GEOMETRY_LABEL); + // spatial can be said about is held apart rather than merged into them. + expect(parts).toHaveLength(3); + const unknown = parts.find((part) => part.unreadablePositions)!; expect(unknown.members).toEqual([blind]); expect(partLabelled(parts, 'acquisition 2').members).toEqual(first); expect(partLabelled(parts, 'acquisition 3').members).toEqual(second); - expect(unknown.unreadablePositions).toBe(true); - expect(partValue(unknown, GEOMETRY_RULE)).toBe(UNREADABLE_GEOMETRY); - parts - .filter((part) => part !== unknown) - .forEach((part) => { - expect(part.unreadablePositions).toBe(false); - expect(part.parts.some(([rule]) => rule === GEOMETRY_RULE)).toBe(false); - }); + expect(parts.filter((part) => part.unreadablePositions)).toEqual([unknown]); }); - it('keeps members whose positions are all unreadable in one diagnosed part', () => { + it('keeps members whose positions are all unreadable in one part', () => { const blind = [ makeFacts('uid-a', { projectedPosition: null }), makeFacts('uid-b', { projectedPosition: null }), ]; - const parts = splitOverlappingAcquisitions(blind); + const parts = split(blind); expect(parts).toHaveLength(1); expect(parts[0].members).toEqual(blind); expect(parts[0].unreadablePositions).toBe(true); }); - it('keeps each part in the member order it was given', () => { - const acq1 = stack('1', -20, 5); - const acq2 = stack('2', -19.25, 6); - const merged = [...acq1, ...acq2].sort(byPosition); - - const parts = splitOverlappingAcquisitions(merged); - - parts.forEach((part) => { - expect(part.members).toEqual([...part.members].sort(byPosition)); - }); - }); - it('is invariant to member permutation in membership', () => { const acq1 = stack('1', -20, 5); const acq2 = stack('2', -19.25, 6); - const forward = splitOverlappingAcquisitions([...acq1, ...acq2]); - const backward = splitOverlappingAcquisitions([...acq2, ...acq1].reverse()); + const forward = split([...acq1, ...acq2]); + const backward = split([...acq2, ...acq1].reverse()); const membership = (parts: SemanticPart[]) => parts @@ -411,66 +296,34 @@ describe('splitOverlappingAcquisitions', () => { expect(membership(backward)).toEqual(membership(forward)); }); - - it('keeps the value spelling the fact reader normalized', () => { - const merged = [...stack('01', 0, 5), ...stack('+2', 0.75, 5)].sort( - byPosition - ); - - const parts = splitOverlappingAcquisitions(merged); - - expect(labels(parts)).toEqual(['acquisition 1', 'acquisition 2']); - }); }); describe('splitOverlappingAcquisitions temporal and echo axes', () => { it('separates DCE timepoints that re-scan one range', () => { - const parts = splitOverlappingAcquisitions(fixtureSlices(dceEightPhase)); + const parts = split(fixtureSlices(dceEightPhase)); expect(labels(parts)).toEqual( ['0', '1', '2', '3', '4', '5', '6', '7'].map((p) => `phase ${p}`) ); expect(partLabelled(parts, 'phase 3').members).toHaveLength(80); - expect(partValue(partLabelled(parts, 'phase 3'), 'phase')).toBe('3'); expect(parts.every((part) => !part.repeatedPositions)).toBe(true); }); - it('separates timepoints across vendors and 1-based numbering', () => { - const parts = splitOverlappingAcquisitions( - fixtureSlices(dceSevenPhasePhilips) - ); - - expect(parts).toHaveLength(7); - parts.forEach((part) => { - expect(part.members).toHaveLength(158); - expect(part.repeatedPositions).toBe(false); - }); - }); - it('separates Dixon echoes that nothing else distinguishes', () => { - const parts = splitOverlappingAcquisitions(fixtureSlices(dixonDualEcho)); + const parts = split(fixtureSlices(dixonDualEcho)); expect(labels(parts)).toEqual(['echo 1', 'echo 2']); - expect(partLabelled(parts, 'echo 1').parts).toEqual([ - ['acquisition', null], - ['phase', null], - ['echo', '1'], - ['b-value', null], - ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), - ]); }); it('separates echoes with unequal slice counts', () => { - const parts = splitOverlappingAcquisitions( - fixtureSlices(dixonUnevenEchoes) - ); + const parts = split(fixtureSlices(dixonUnevenEchoes)); expect(partLabelled(parts, 'echo 1').members).toHaveLength(13); expect(partLabelled(parts, 'echo 2').members).toHaveLength(12); }); it('separates repeated diffusion positions by b-value', () => { - const parts = splitOverlappingAcquisitions(fixtureSlices(dwiMultiBValue)); + const parts = split(fixtureSlices(dwiMultiBValue)); expect(labels(parts)).toEqual([ 'b-value 0', @@ -491,9 +344,7 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { ); const untagged = slice(2); - const parts = splitOverlappingAcquisitions( - [...b0, untagged, ...b800].sort(byPosition) - ); + const parts = split([...b0, untagged, ...b800].sort(byPosition)); expect(labels(parts)).toEqual([ 'b-value 0', @@ -501,9 +352,6 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { 'b-value unknown', ]); expect(partLabelled(parts, 'b-value unknown').members).toEqual([untagged]); - expect( - partValue(partLabelled(parts, 'b-value unknown'), 'b-value') - ).toBeNull(); }); it('still separates contrasts of a single plane', () => { @@ -513,38 +361,23 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { slice(0, { [Tags.AcquisitionNumber]: '1', [Tags.EchoNumbers]: echo }) ); - const parts = splitOverlappingAcquisitions(members); + const parts = split(members); expect(labels(parts)).toEqual(['echo 1', 'echo 2']); expect(parts.every((part) => !part.repeatedPositions)).toBe(true); }); - it('treats equivalent integer spellings as one tag value', () => { - const merged = [...stack('+1', 0, 5), ...stack('01', 0, 5)].sort( - byPosition - ); - - const parts = splitOverlappingAcquisitions(merged); - - expect(parts).toHaveLength(1); - expect(parts[0].repeatedPositions).toBe(true); - }); - it('does not split bilateral slabs whose stacks do not overlap', () => { // StackID (0020|9056) differs per slab, but the slabs form one sound // volume with a gap; this series is why StackID is not an axis. - const parts = splitOverlappingAcquisitions( - fixtureSlices(bilateralSagittalSlabs) - ); + const parts = split(fixtureSlices(bilateralSagittalSlabs)); expect(parts).toHaveLength(1); expect(parts[0].repeatedPositions).toBe(false); }); it('splits on acquisition when the temporal tag is partially present', () => { - const parts = splitOverlappingAcquisitions( - fixtureSlices(partialTemporalTags) - ); + const parts = split(fixtureSlices(partialTemporalTags)); expect(labels(parts)).toEqual( ['1', '2', '3', '4', '5', '6', '7'].map((a) => `acquisition ${a}`) @@ -553,23 +386,8 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { expect(parts.every((part) => !part.repeatedPositions)).toBe(true); }); - it('keeps sequential timepoints merged', () => { - const phase = (value: string, start: number, count: number) => - Array.from({ length: count }, (_, i) => - slice(start + i * 5, { [Tags.TemporalPositionIdentifier]: value }) - ); - - const parts = splitOverlappingAcquisitions( - [...phase('1', 0, 5), ...phase('2', 30, 5)].sort(byPosition) - ); - - expect(parts).toHaveLength(1); - }); - it('splits a doubled acquisition and still flags the repetition', () => { - const parts = splitOverlappingAcquisitions( - fixtureSlices(doubledAcquisition) - ); + const parts = split(fixtureSlices(doubledAcquisition)); expect(labels(parts)).toEqual(['acquisition 1', 'acquisition 2']); expect(partLabelled(parts, 'acquisition 1').members).toHaveLength(74); @@ -579,8 +397,7 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { }); it('recurses into each timepoint of a 4D multi-echo series', () => { - // Synthetic: no IDC case observed with two active levels. Pins the - // hierarchical key shape and label rendering. + // Synthetic: no IDC case observed with two active levels. const merged = ['1', '2'] .flatMap((phase) => ['1', '2'].flatMap((echo) => @@ -595,7 +412,7 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { ) .sort(byPosition); - const parts = splitOverlappingAcquisitions(merged); + const parts = split(merged); expect(labels(parts)).toEqual([ 'phase 1, echo 1', @@ -603,33 +420,8 @@ describe('splitOverlappingAcquisitions temporal and echo axes', () => { 'phase 2, echo 1', 'phase 2, echo 2', ]); - expect(partLabelled(parts, 'phase 2, echo 1').parts).toEqual([ - ['acquisition', null], - ['phase', '2'], - ['echo', '1'], - ['b-value', null], - ...DESCRIPTOR_AXES.map((axis) => [axis.rule, null]), - ]); parts.forEach((part) => { expect(part.members).toHaveLength(10); }); }); - - it('gives distinct values distinct key parts however they are spelled', () => { - // Normalized values remain distinct even when their punctuation differs. - const merged = [...stack('1.5', 0, 5), ...stack('1-5', 0, 5)].sort( - byPosition - ); - - const parts = splitOverlappingAcquisitions(merged); - - expect(labels(parts)).toEqual(['acquisition 1-5', 'acquisition 1.5']); - expect( - partValue(partLabelled(parts, 'acquisition 1-5'), 'acquisition') - ).toBe('1-5'); - }); }); - -function readInstanceFacts(tags: Iterable) { - return readStructuredFacts(datasetFromTags(tags)); -} diff --git a/packages/dicom/core/collections/assignCollectionIds.ts b/packages/dicom/core/collections/assignCollectionIds.ts index 19be2a98d..929de5bb8 100644 --- a/packages/dicom/core/collections/assignCollectionIds.ts +++ b/packages/dicom/core/collections/assignCollectionIds.ts @@ -1,28 +1,24 @@ -import type { - CollectionKey, - DicomCollection, - DicomCollectionPlan, -} from './planDicomCollections'; +import type { CollectionKey, DicomCollection } from './planDicomCollections'; export type CommittedCollection = { id: string; sopInstanceUids: string[]; }; -// encodeURIComponent escapes every separator the key values can carry, so the -// join characters below cannot appear inside an encoded component. -const escape = (value: string) => encodeURIComponent(value); - // A present value is prefixed, so it can never collide with the missing marker. const encodeValue = (value: string | null) => - value === null ? '~' : `.${escape(value)}`; + value === null ? '~' : `.${encodeURIComponent(value)}`; -/** Escaped encoding of a structured key, safe to use as a store ID. */ +/** + * Encoding of a structured key, safe to use as a store ID. encodeURIComponent + * escapes every separator a value can carry, so the join characters cannot + * appear inside a component. + */ export function encodeCollectionKey(key: CollectionKey) { return [ - escape(key.seriesKey), + encodeURIComponent(key.seriesKey), ...key.parts.map( - ([rule, value]) => `${escape(rule)}=${encodeValue(value)}` + ([rule, value]) => `${encodeURIComponent(rule)}=${encodeValue(value)}` ), ].join('|'); } @@ -52,10 +48,10 @@ const mint = (key: CollectionKey, taken: Set) => { * members; mints a fresh ID from the key otherwise. */ export function assignIds( - plan: DicomCollectionPlan, + planned: DicomCollection[], committedIds: CommittedCollection[] ) { - const plannedUids = plan.collections.map(uidsOf); + const plannedUids = planned.map(uidsOf); const committedUids = committedIds.map( (committed) => new Set(committed.sopInstanceUids) ); @@ -63,8 +59,8 @@ export function assignIds( // A committed ID moves only where its members are not split more evenly // elsewhere: the plurality holder must be strictly ahead of every rival. const claimable = committedIds.map((committed, committedIndex) => { - const overlaps = plannedUids.map((planned) => - overlapSize(planned, committedUids[committedIndex]) + const overlaps = plannedUids.map((uids) => + overlapSize(uids, committedUids[committedIndex]) ); const best = Math.max(0, ...overlaps); const holders = overlaps.filter((size) => size === best).length; @@ -87,12 +83,10 @@ export function assignIds( const taken = new Set(committedIds.map((committed) => committed.id)); - const collections = plan.collections.map((collection, index) => { + return planned.map((collection, index) => { const claim = claimFor(index); const id = claim ? claim.committed.id : mint(collection.key, taken); taken.add(id); return { ...collection, id }; }); - - return { collections }; } diff --git a/packages/dicom/core/collections/instanceFacts.ts b/packages/dicom/core/collections/instanceFacts.ts index 5715c2e43..837f0fb81 100644 --- a/packages/dicom/core/collections/instanceFacts.ts +++ b/packages/dicom/core/collections/instanceFacts.ts @@ -6,7 +6,7 @@ import type { DicomDataset } from '../metadata/dicomDataset'; import { getFrameTag } from '../metadata/functionalGroups'; import { trimDicomPadding } from '../utils'; -// readDicomTags hands back DICOM's own byte padding, so a value that is only +// Dataset text keeps DICOM's own byte padding, so a value that is only // padding is absent rather than an empty string. const textOf = (metadata: DicomDataset, tag: string) => { const value = trimDicomPadding(getFrameTag(metadata, tag) ?? ''); @@ -179,11 +179,6 @@ export function readInstanceDetails(metadata: DicomDataset) { return { facts, frameGeometry: frames }; } -/** Reads the planner's plain facts out of one instance's tag values. */ -export function readInstanceFacts(metadata: DicomDataset) { - return readInstanceDetails(metadata).facts; -} - // Carries a separator no UID can hold, so a fallback key never equals a real // series key. const NO_SERIES_UID = 'no-series'; diff --git a/packages/dicom/core/collections/instanceRegistry.ts b/packages/dicom/core/collections/instanceRegistry.ts index 3bb2eabfb..39023501c 100644 --- a/packages/dicom/core/collections/instanceRegistry.ts +++ b/packages/dicom/core/collections/instanceRegistry.ts @@ -7,11 +7,7 @@ import { type DicomCollection, type InstanceFacts, } from './planDicomCollections'; -import { - assignIds, - encodeCollectionKey, - type CommittedCollection, -} from './assignCollectionIds'; +import { assignIds, type CommittedCollection } from './assignCollectionIds'; import { seriesKeyOf } from './instanceFacts'; import { readDatasetDetails } from './datasetDetails'; import { groupBy } from './groupBy'; @@ -19,13 +15,12 @@ import type { Reconstruction } from './reconstructVolume'; /** * How a collection differs from what was last committed under its ID: - * `unchanged` has the same members, key and geometry, re-supplied by the batch. + * `unchanged` has the same members and geometry, so its volume stands. */ type CollectionChange = 'new' | 'unchanged' | 'changed'; type CollectionUpdateFields = { id: string; - seriesKey: string; collection: DicomCollection; /** Registered instances in the collection's order, aligned with collection.members. */ members: Instance[]; @@ -57,10 +52,11 @@ type Registered = { type Committed = { members: readonly InstanceKey[]; - // Reported when relabelled even if its members did not move. - key: string; orientation: readonly number[] | null; reconstruction: Reconstruction; + // Siblings can change either without moving a member, and that is reported. + label: string | null; + warnings: readonly string[]; }; type SeriesState = { @@ -75,26 +71,16 @@ export const emptyRegistry: RegistryState = new Map(); const emptySeries: SeriesState = { instances: new Map(), committed: new Map() }; -// One facts object per instance: the planner's members are matched back by identity. -const factsByInstance = new WeakMap(); - -const factsOf = (instance: Instance) => { - const cached = factsByInstance.get(instance); - if (cached) return cached; - const facts = { ...readDatasetDetails(instance.dataset).facts }; - factsByInstance.set(instance, facts); - return facts; -}; - const keyOf = (instance: Instance): InstanceKey => trimDicomPadding( getDatasetTag(instance.dataset, Tags.SOPInstanceUID) ?? '' ) || instance; +// A facts object of its own: the planner's members are matched back by identity. const registeredOf = (instance: Instance): Registered => ({ key: keyOf(instance), instance, - facts: factsOf(instance), + facts: { ...readDatasetDetails(instance.dataset).facts }, }); // A collection holding no SOP Instance UID cannot be claimed back by overlap, @@ -124,11 +110,9 @@ const reasonOf = (reconstruction: Reconstruction) => const sameReconstruction = (a: Reconstruction, b: Reconstruction) => a.kind === b.kind && reasonOf(a) === reasonOf(b) && - a.sliceSpacing === b.sliceSpacing && - sameList(a.slots, b.slots); + a.sliceSpacing === b.sliceSpacing; const unchanged = (before: Committed, after: Committed) => - before.key === after.key && sameList(before.members, after.members) && sameList(before.orientation, after.orientation) && sameReconstruction(before.reconstruction, after.reconstruction); @@ -141,6 +125,10 @@ const changeOf = ( return unchanged(before, after) ? 'unchanged' : 'changed'; }; +const sameDescription = (before: Committed | undefined, after: Committed) => + !before || + (before.label === after.label && sameList(before.warnings, after.warnings)); + const kindOf = (first: Instance) => getDatasetModality(first.dataset) === 'SEG' ? ('segmentation' as const) @@ -188,19 +176,20 @@ function planSeries( ? instance : (supplied.get(key) ?? instance); - const planned = assigned.collections.map(({ id, ...collection }) => { + const planned = assigned.map(({ id, ...collection }) => { const entries = collection.members.map((facts) => entryOf.get(facts)!); const committed: Committed = { members: entries.map((entry) => entry.key), - key: encodeCollectionKey(collection.key), orientation: collection.orientation, reconstruction: collection.reconstruction, + label: collection.label, + warnings: collection.warnings, }; const members = entries.map((entry) => entry.instance); - const change = changeOf(series.committed.get(id), committed); + const previous = series.committed.get(id); + const change = changeOf(previous, committed); const update: InstanceCollectionUpdate = { id, - seriesKey, collection, members, provenance: entries.map(provenanceOf), @@ -210,6 +199,7 @@ function planSeries( // A replan can move members or relabel a collection the batch brought nothing. const changed = change !== 'unchanged' || + !sameDescription(previous, committed) || committed.members.some((key) => supplied.has(key)); return { committed, update, changed }; }); @@ -257,7 +247,7 @@ export function registerInstances( updates: results.flatMap((result) => result.updates), /** Committed IDs the replan dissolved, whose members moved elsewhere. */ removed: results.flatMap((result) => result.removed), - /** Different geometry under a registered SOP Instance UID; the first copy is kept. */ + /** Different header facts under a registered SOP Instance UID; the first copy is kept. */ conflictingInstanceUids: results.flatMap( (result) => result.conflictingInstanceUids ), @@ -290,8 +280,3 @@ export function forgetCollection( else next.set(seriesKey, remaining); return next; } - -/** Whether this object, not merely an equal copy, is the registered instance. */ -export const isRegistered = (state: RegistryState, instance: Instance) => - state.get(seriesKeyOf(instance.dataset))?.instances.get(keyOf(instance)) - ?.instance === instance; diff --git a/packages/dicom/core/collections/multiframeGeometry.ts b/packages/dicom/core/collections/multiframeGeometry.ts index 30adbf375..59f20af58 100644 --- a/packages/dicom/core/collections/multiframeGeometry.ts +++ b/packages/dicom/core/collections/multiframeGeometry.ts @@ -4,7 +4,15 @@ import { reconstructVolume, type Reconstruction } from './reconstructVolume'; import { dot, orientationsAgree } from './orientation'; import { getDatasetTag } from '../metadata/datasetAccess'; import { trimDicomPadding } from '../utils'; -import { perFrameGroups, sequenceItems } from '../metadata/functionalGroups'; +import { + perFrameGroups, + sequenceItems, + SHARED_GROUPS, +} from '../metadata/functionalGroups'; + +const FRAME_CONTENT = '00209111'; +const STACK_ID = '00209056'; +const TEMPORAL_POSITION_INDEX = '00209128'; function storageDirection(frames: ReturnType[]) { const first = frames[0]; @@ -18,11 +26,11 @@ function storageDirection(frames: ReturnType[]) { } const singleSpatialStack = (groups: DicomDataset[]) => - ['00209056', '00209128'].every((tag) => { + [STACK_ID, TEMPORAL_POSITION_INDEX].every((tag) => { const values = groups .map((group) => trimDicomPadding( - getDatasetTag(sequenceItems(group, '00209111')[0], tag) ?? '' + getDatasetTag(sequenceItems(group, FRAME_CONTENT)[0], tag) ?? '' ) ) .filter(Boolean); @@ -37,7 +45,7 @@ const singleSpatialStack = (groups: DicomDataset[]) => */ export function multiframeGeometry(metadata: DicomDataset, count: number) { const groups = perFrameGroups(metadata); - const shared = sequenceItems(metadata, '52009229'); + const shared = sequenceItems(metadata, SHARED_GROUPS); if (count < 2 || (shared.length === 0 && groups.length === 0)) return null; const frames = Array.from({ length: count }, (_, index) => readGeometryFacts(metadata, index) @@ -61,12 +69,6 @@ export function multiframeGeometry(metadata: DicomDataset, count: number) { kind: 'irregular', reason: 'unreadable-geometry', sliceSpacing: reconstruction.sliceSpacing, - slots: [0], }; - return { - ...first, - direction, - sliceSpacingSource: 'ImagePositionPatient', - reconstruction: { ...validated, slots: [0] }, - }; + return { ...first, direction, reconstruction: validated }; } diff --git a/packages/dicom/core/collections/planDicomCollections.ts b/packages/dicom/core/collections/planDicomCollections.ts index a214b919f..c1a017122 100644 --- a/packages/dicom/core/collections/planDicomCollections.ts +++ b/packages/dicom/core/collections/planDicomCollections.ts @@ -2,7 +2,6 @@ import { orientationsAgree } from './orientation'; import { groupBy } from './groupBy'; import { instanceKey } from './instanceKey'; import { - SEMANTIC_AXES, splitOverlappingAcquisitions, type PositionOf, } from './splitOverlappingAcquisitions'; @@ -39,7 +38,7 @@ export type InstanceFacts = { position: number[] | null; projectedPosition: number | null; pixelSpacing: number[] | null; - /** Intra-instance frame geometry; slots still index source instances. */ + /** Geometry of the frames within one instance. */ frameReconstruction?: Reconstruction; // Ordering fallback. @@ -58,12 +57,11 @@ export type CollectionKey = { parts: Array<[string, string | null]>; }; -type MemberOrder = 'spatial' | 'instance-number' | 'input'; - export type DicomCollection = { key: CollectionKey; + // Ordered by position when every one reads, else by instance number when + // every one reads, else as given. members: InstanceFacts[]; - order: MemberOrder; // The axes the members were ordered and judged on. Allocation must build // on these too, or the warnings describe a volume other than the one shown. orientation: number[] | null; @@ -71,33 +69,27 @@ export type DicomCollection = { // Names the scan the collection was separated out as ('acquisition 2', // 'phase 3, echo 1'); null when nothing separated it from its series. label: string | null; - // Per-member notes about how the plan was reached. - diagnostics: string[]; // Conditions the user should hear about: the collection loads, but not as // the sound volume its series promised. warnings: string[]; }; -export type DicomCollectionPlan = { - collections: DicomCollection[]; -}; - type PlanInput = { seriesKey: string; instances: InstanceFacts[]; }; -export { ORIENTATION_TOLERANCE } from './orientation'; - // The hard facts, in the order they appear in a collection key. -export const HARD_FACT_RULES = [ +const HARD_FACT_RULES = [ 'rows', 'columns', 'samplesPerPixel', 'numberOfFrames', ] as const; -export const ORIENTATION_RULE = 'orientation'; +const ORIENTATION_RULE = 'orientation'; + +const UNREADABLE_POSITION_LABEL = 'position unknown'; export const REPEATED_POSITIONS_WARNING = 'holds repeated slice positions that no tag separates. Its slice spacing ' + @@ -148,13 +140,6 @@ const reconstructionWarnings = ( return RECONSTRUCTION_WARNINGS[reconstruction.reason]; }; -const ANONYMOUS = 'an instance with no SOP Instance UID'; - -const label = (instance: InstanceFacts) => - instance.sopInstanceUid === null - ? ANONYMOUS - : `instance ${instance.sopInstanceUid}`; - // Nulls sort last so a missing identity never becomes a bucket representative. const compareUid = (left: string | null, right: string | null) => { if (left === right) return 0; @@ -169,11 +154,6 @@ const compareBySopUid = (left: InstanceFacts, right: InstanceFacts) => const readableNumber = (value: number | null): value is number => value !== null && Number.isFinite(value); -const compareText = (left: string, right: string) => { - if (left === right) return 0; - return left < right ? -1 : 1; -}; - // Unreadable numbers sort last so they never win a tie-break. const compareNumber = (left: number | null, right: number | null) => { if (!readableNumber(left)) return readableNumber(right) ? 1 : 0; @@ -181,45 +161,12 @@ const compareNumber = (left: number | null, right: number | null) => { return left === right ? 0 : left - right; }; -// JSON collapses NaN and Infinity onto null; keep them apart so the signature -// below separates every pair of unequal instances. -const encodeFact = (_key: string, value: unknown) => - typeof value === 'number' && !Number.isFinite(value) ? String(value) : value; - -const contentSignature = (instance: InstanceFacts) => - JSON.stringify( - [ - instance.sopInstanceUid, - instance.seriesInstanceUid, - ...HARD_FACT_RULES.map((rule) => instance[rule]), - ...SEMANTIC_AXES.map((axis) => instance[axis.fact]), - instance.orientation, - instance.position, - instance.projectedPosition, - instance.pixelSpacing, - instance.frameReconstruction, - instance.instanceNumber, - ], - encodeFact - ); - -/** - * Total order over instances that share a SOP Instance UID comparison, which - * happens whenever two instances both lack one. - */ -const compareByContent = (left: InstanceFacts, right: InstanceFacts) => - compareText( - JSON.stringify(left.orientation), - JSON.stringify(right.orientation) - ) || - compareNumber(left.projectedPosition, right.projectedPosition) || - compareNumber(left.instanceNumber, right.instanceNumber) || - compareText(contentSignature(left), contentSignature(right)); - -// Sorting on the UID alone ties every anonymous instance, leaving the greedy -// orientation walk at the mercy of input order. +// Instances without a SOP Instance UID all tie on it, so their position and +// instance number keep the greedy orientation walk off input order. const compareWalkOrder = (left: InstanceFacts, right: InstanceFacts) => - compareBySopUid(left, right) || compareByContent(left, right); + compareBySopUid(left, right) || + compareNumber(left.projectedPosition, right.projectedPosition) || + compareNumber(left.instanceNumber, right.instanceNumber); const readableOrientation = (value: number[] | null): value is number[] => value !== null && @@ -272,41 +219,6 @@ const nonparallel = (axes: number[] | null, members: InstanceFacts[]) => const canonicalKey = (key: CollectionKey) => JSON.stringify([key.seriesKey, key.parts]); -/** Last occurrence of a SOP Instance UID wins, so the newest batch survives. */ -const dedupe = (instances: InstanceFacts[]) => { - const lastIndex = new Map(); - instances.forEach((instance, index) => { - if (instance.sopInstanceUid !== null) - lastIndex.set(instance.sopInstanceUid, index); - }); - - const kept = instances.filter( - (instance, index) => - instance.sopInstanceUid === null || - lastIndex.get(instance.sopInstanceUid) === index - ); - - const droppedCounts = new Map(); - instances.forEach((instance, index) => { - const uid = instance.sopInstanceUid; - if (uid === null || lastIndex.get(uid) === index) return; - droppedCounts.set(uid, (droppedCounts.get(uid) ?? 0) + 1); - }); - - const diagnostics = new Map(); - kept.forEach((instance) => { - const uid = instance.sopInstanceUid; - const dropped = uid === null ? 0 : (droppedCounts.get(uid) ?? 0); - if (dropped > 0) - diagnostics.set( - instance, - `dropped ${dropped} earlier copy of instance ${uid}` - ); - }); - - return { kept, diagnostics }; -}; - const hardFactSignature = (instance: InstanceFacts) => JSON.stringify(HARD_FACT_RULES.map((rule) => instance[rule])); @@ -332,9 +244,9 @@ const hardFactLabeler = (all: InstanceFacts[]) => { }; /** - * Greedy bucketing walked in SOP Instance UID then content order, so the - * representative whose cosines become the key, and the membership the greedy - * walk produces, do not depend on input order. + * Greedy bucketing walked in SOP Instance UID order, so the representative + * whose cosines become the key, and the membership the greedy walk produces, + * do not depend on input order. */ const bucketByOrientation = (instances: InstanceFacts[]) => { const references: number[][] = []; @@ -393,8 +305,7 @@ const bucketByOrientation = (instances: InstanceFacts[]) => { // A repeated position breaks on the instance number, keeping the scanner's // own sequence for the tied members. Position stays primary: the allocator // places slot i at origin + i * spacing along the normal, so any order that -// is not monotone in position mirrors or scrambles the volume. Anonymous -// members that still tie order by content rather than by input position. +// is not monotone in position mirrors or scrambles the volume. const comparePosition = (positionOf: PositionOf) => (left: InstanceFacts, right: InstanceFacts) => (positionOf(left) as number) - (positionOf(right) as number) || @@ -405,104 +316,40 @@ const compareInstanceNumber = (left: InstanceFacts, right: InstanceFacts) => (left.instanceNumber as number) - (right.instanceNumber as number) || compareWalkOrder(left, right); -/** Never inherits input order silently: the order actually used is recorded. */ const orderMembers = (members: InstanceFacts[], positionOf: PositionOf) => { - const numbered = members.every((m) => readableNumber(m.instanceNumber)); - if (members.every((m) => readableNumber(positionOf(m)))) - return { - members: [...members].sort(comparePosition(positionOf)), - order: 'spatial' as MemberOrder, - diagnostics: [] as string[], - }; - - const positionless = (ordered: InstanceFacts[]) => - ordered - .filter((m) => !readableNumber(positionOf(m))) - .map((m) => `${label(m)} has no readable position`); - - if (numbered) { - const ordered = [...members].sort(compareInstanceNumber); - return { - members: ordered, - order: 'instance-number' as MemberOrder, - diagnostics: positionless(ordered), - }; - } - - return { - members: [...members], - order: 'input' as MemberOrder, - diagnostics: [ - ...positionless(members), - ...members - .filter((m) => !readableNumber(m.instanceNumber)) - .map((m) => `${label(m)} has no readable instance number`), - ], - }; -}; - -/** Occurrences per instance, so an input holding one object twice needs two. */ -const tally = (instances: InstanceFacts[]) => { - const counts = new Map(); - instances.forEach((instance) => - counts.set(instance, (counts.get(instance) ?? 0) + 1) - ); - return counts; + return [...members].sort(comparePosition(positionOf)); + if (members.every((m) => readableNumber(m.instanceNumber))) + return [...members].sort(compareInstanceNumber); + return [...members]; }; -/** - * Throws when the collections do not hold every instance as many times as the - * input does, when they hold one the input never gave, or when two collections - * share a key. - */ -export function validateCollections( - instances: InstanceFacts[], - collections: DicomCollection[] -) { - const expected = tally(instances); - const placed = tally(collections.flatMap((collection) => collection.members)); - - expected.forEach((count, instance) => { - const found = placed.get(instance) ?? 0; - if (found === count) return; - if (found === 0) - throw new Error(`${label(instance)} landed in no collection`); - throw new Error( - `${label(instance)} landed in ${found} collections, expected ${count}` - ); - }); - - placed.forEach((_count, instance) => { - if (!expected.has(instance)) - throw new Error( - `${label(instance)} landed in a collection without being an input` - ); - }); - - const seen = new Set(); - collections.forEach((collection) => { - const encoded = canonicalKey(collection.key); - if (seen.has(encoded)) - throw new Error(`two collections share the key ${encoded}`); - seen.add(encoded); - }); -} +// An unreadable position is named only beside a volume it was kept out of, +// and warned about there or where it leaves an order and spacing to guess. +const unreadablePositionNotes = ( + unreadable: boolean, + placed: boolean, + stacked: boolean +) => ({ + label: unreadable && placed ? UNREADABLE_POSITION_LABEL : null, + warnings: + unreadable && (placed || stacked) ? [UNREADABLE_POSITION_WARNING] : [], +}); export function planDicomCollections(input: PlanInput) { - const { kept, diagnostics: dedupeDiagnostics } = dedupe(input.instances); - const labelHardFacts = hardFactLabeler(kept); + const { instances } = input; + const labelHardFacts = hardFactLabeler(instances); const multiframe = (instance: InstanceFacts) => Number(instance.numberOfFrames) > 1; const groups = [ ...groupBy( - kept.filter((instance) => !multiframe(instance)), + instances.filter((instance) => !multiframe(instance)), hardFactSignature ).values(), - ...kept.filter(multiframe).map((instance) => [instance]), + ...instances.filter(multiframe).map((instance) => [instance]), ]; - const planned = groups + const parts = groups .flatMap((group) => bucketByOrientation(group).map((bucket) => ({ group, @@ -518,13 +365,14 @@ export function planDicomCollections(input: PlanInput) { positionOf, part, })) - ) + ); + + const placed = parts.some(({ part }) => !part.unreadablePositions); + + const collections = parts .map(({ group, bucket, positionOf, part }) => { - const ordered = orderMembers(part.members, positionOf); - const reconstruction = reconstructInstances( - ordered.members, - bucket.normal - ); + const members = orderMembers(part.members, positionOf); + const reconstruction = reconstructInstances(members, bucket.normal); const key: CollectionKey = { seriesKey: input.seriesKey, parts: [ @@ -536,38 +384,28 @@ export function planDicomCollections(input: PlanInput) { : []), ], }; + const unreadable = unreadablePositionNotes( + part.unreadablePositions, + placed, + members.length > 1 + ); return { key, - members: ordered.members, - order: ordered.order, + members, orientation: bucket.orientation, reconstruction, label: - [labelHardFacts(group[0]), part.label].filter(Boolean).join(', ') || - null, - diagnostics: [ - ...ordered.members.flatMap((member) => { - const dropped = dedupeDiagnostics.get(member); - return dropped ? [dropped] : []; - }), - ...(bucket.value === null - ? ordered.members.map( - (member) => `${label(member)} has no readable orientation` - ) - : []), - ...ordered.diagnostics, - ], + [labelHardFacts(group[0]), part.label, unreadable.label] + .filter(Boolean) + .join(', ') || null, warnings: [ ...(part.repeatedPositions ? [REPEATED_POSITIONS_WARNING] : []), - ...(part.unreadablePositions && !multiframe(group[0]) - ? [UNREADABLE_POSITION_WARNING] - : []), + ...(multiframe(group[0]) ? [] : unreadable.warnings), ...reconstructionWarnings( reconstruction, - ordered.members.length === 1 && - !!ordered.members[0].frameReconstruction + members.length === 1 && !!members[0].frameReconstruction ), - ...(nonparallel(bucket.orientation, ordered.members) + ...(nonparallel(bucket.orientation, members) ? [NONPARALLEL_SLICES_WARNING] : []), ], @@ -577,19 +415,5 @@ export function planDicomCollections(input: PlanInput) { canonicalKey(left.key) < canonicalKey(right.key) ? -1 : 1 ); - // A series that plans to one instance is a whole volume: nothing was held - // out of a sibling, and one slice has no order or spacing to get wrong. - const lone = planned.length === 1 && planned[0].members.length === 1; - const collections = lone - ? planned.map((collection) => ({ - ...collection, - warnings: collection.warnings.filter( - (warning) => warning !== UNREADABLE_POSITION_WARNING - ), - })) - : planned; - - validateCollections(kept, collections); - - return { collections }; + return collections; } diff --git a/packages/dicom/core/collections/reconstructVolume.ts b/packages/dicom/core/collections/reconstructVolume.ts index 2599b9a3c..820522ce9 100644 --- a/packages/dicom/core/collections/reconstructVolume.ts +++ b/packages/dicom/core/collections/reconstructVolume.ts @@ -18,21 +18,20 @@ export type IrregularReason = * What the members can be reconstructed as. * * `regular` means every consecutive pair of slice planes is the same distance - * apart and the members share one in-plane grid, so member i belongs at slot - * `slots[i]` of a volume sampled at `sliceSpacing`. `irregular` means they do - * not: the members still load, placed one slot apart at the step the stack - * does take, but no lattice describes where they actually are. + * apart and the members share one in-plane grid, so member i is slice i of a + * volume sampled at `sliceSpacing`. `irregular` means they do not: the members + * still load, placed one slice apart at the step the stack does take, but no + * lattice describes where they actually are. * * A slice spacing of null means there is nothing to derive one from, which one * member alone always is. */ export type Reconstruction = - | { kind: 'regular'; sliceSpacing: number | null; slots: number[] } + | { kind: 'regular'; sliceSpacing: number | null } | { kind: 'irregular'; reason: IrregularReason; sliceSpacing: number | null; - slots: number[]; }; /** @@ -44,6 +43,7 @@ export type Reconstruction = * missed slice is orders of magnitude larger. */ const SLICE_SPACING_TOLERANCE_MM = 0.1; +const SLICE_SPACING_TOLERANCE_CAP = 0.1; const SLICE_SPACING_RELATIVE_TOLERANCE = 0.01; /** How far a slice may sit from the in-plane origin of the first, in mm. */ @@ -54,7 +54,10 @@ const PIXEL_SPACING_TOLERANCE_MM = 1e-4; const spacingTolerance = (gap: number) => Math.max( - Math.min(SLICE_SPACING_TOLERANCE_MM, Math.abs(gap) * 0.1), + Math.min( + SLICE_SPACING_TOLERANCE_MM, + Math.abs(gap) * SLICE_SPACING_TOLERANCE_CAP + ), Math.abs(gap) * SLICE_SPACING_RELATIVE_TOLERANCE ); @@ -113,14 +116,8 @@ const mixedPixelSpacing = (members: ReconstructionMember[]) => { const irregular = ( reason: IrregularReason, - sliceSpacing: number | null, - count: number -): Reconstruction => ({ - kind: 'irregular', - reason, - sliceSpacing, - slots: Array.from({ length: count }, (_, index) => index), -}); + sliceSpacing: number | null +): Reconstruction => ({ kind: 'irregular', reason, sliceSpacing }); const inPlaneShifted = ( members: ReconstructionMember[], @@ -152,27 +149,29 @@ const geometryFault = ( /** The lattice the slice planes sit on, once they are known to be readable. */ const lattice = (along: number[]): Reconstruction => { - if (along.length < 2) - return { kind: 'regular', sliceSpacing: null, slots: [0] }; + if (along.length < 2) return { kind: 'regular', sliceSpacing: null }; const gaps = along.slice(1).map((position, index) => position - along[index]); const step = median(gaps); const count = along.length; + const fallback = step > 0 ? step : null; - if (gaps.some((gap) => gap <= 0)) - return irregular('repeated-position', step > 0 ? step : null, count); + // Frames are judged in stored order, so a step backwards is not a repeat. + if (new Set(along).size < count) + return irregular('repeated-position', fallback); if (gaps.some((gap) => Math.abs(gap - step) > spacingTolerance(step))) - return irregular('uneven-slice-spacing', step, count); + return irregular('uneven-slice-spacing', fallback); // Every gap matches, so the endpoints fit the members better than any single // printed gap does. const sliceSpacing = (along[count - 1] - along[0]) / gaps.length; - const slots = along.map((position) => - Math.round((position - along[0]) / sliceSpacing) + const drifts = along.some( + (position, index) => + Math.round((position - along[0]) / sliceSpacing) !== index ); - return slots.some((slot, index) => slot !== index) - ? irregular('uneven-slice-spacing', step, count) - : { kind: 'regular', sliceSpacing, slots }; + return drifts + ? irregular('uneven-slice-spacing', step) + : { kind: 'regular', sliceSpacing }; }; /** @@ -191,11 +190,7 @@ export function reconstructVolume( members.length < 2 && !members.some((member) => Number(member.numberOfFrames) > 1) ) - return { - kind: 'regular', - sliceSpacing: null, - slots: members.map(() => 0), - }; + return { kind: 'regular', sliceSpacing: null }; const axis = normal ?? sliceNormalOf(members[0].orientation); const along = members.map((member) => projectOnNormal(axis, member.position)); @@ -203,18 +198,15 @@ export function reconstructVolume( const fault = geometryFault(members, axis, along); return fault === null ? lattice(along as number[]) - : irregular(fault, positionStep(members), members.length); + : irregular(fault, positionStep(members)); } -/** Slots index source instances even when one instance holds many frames. */ +/** One instance holding many frames is judged by its own frame geometry. */ export function reconstructInstances( members: ReconstructionMember[], - normal?: number[] | null, - supplied?: Reconstruction -): Reconstruction { + normal?: number[] | null +) { const framePlan = members.length === 1 ? members[0].frameReconstruction : undefined; - return framePlan - ? { ...framePlan, slots: [0] } - : (supplied ?? reconstructVolume(members, normal)); + return framePlan ?? reconstructVolume(members, normal); } diff --git a/packages/dicom/core/collections/splitOverlappingAcquisitions.ts b/packages/dicom/core/collections/splitOverlappingAcquisitions.ts index 63fa4a143..71b1485a4 100644 --- a/packages/dicom/core/collections/splitOverlappingAcquisitions.ts +++ b/packages/dicom/core/collections/splitOverlappingAcquisitions.ts @@ -1,13 +1,6 @@ import type { InstanceFacts } from './planDicomCollections'; import { groupBy } from './groupBy'; -export const DESCRIPTOR_AXES = [ - { rule: 'sequence', fact: 'sequenceName', counter: true }, - { rule: 'thickness', fact: 'sliceThickness', counter: true }, - { rule: 'series', fact: 'seriesNumber', counter: true }, - { rule: 'date', fact: 'seriesDate', counter: true }, -] as const; - /** * Facts tried, in order, as the identity of one scan within a series. An axis * that does not split hands the members to the next; an axis that does split @@ -22,25 +15,25 @@ export const DESCRIPTOR_AXES = [ * groups too, except when all images share one plane: separating those cannot * remove a slice from a spatial stack. */ -export const SEMANTIC_AXES = [ - { rule: 'acquisition', fact: 'acquisitionNumber', counter: true }, - { rule: 'phase', fact: 'temporalPositionIdentifier', counter: true }, - { rule: 'echo', fact: 'echoNumbers', counter: false }, - { rule: 'b-value', fact: 'diffusionBValue', counter: false }, - ...DESCRIPTOR_AXES, +const SEMANTIC_AXES = [ + { rule: 'acquisition', fact: 'acquisitionNumber', kind: 'counter' }, + { rule: 'phase', fact: 'temporalPositionIdentifier', kind: 'counter' }, + { rule: 'echo', fact: 'echoNumbers', kind: 'contrast' }, + { rule: 'b-value', fact: 'diffusionBValue', kind: 'contrast' }, + { rule: 'sequence', fact: 'sequenceName', kind: 'descriptor' }, + { rule: 'thickness', fact: 'sliceThickness', kind: 'descriptor' }, + { rule: 'series', fact: 'seriesNumber', kind: 'descriptor' }, + { rule: 'date', fact: 'seriesDate', kind: 'descriptor' }, ] as const; type SemanticAxis = (typeof SEMANTIC_AXES)[number]; -const isDescriptor = (axis: SemanticAxis) => - DESCRIPTOR_AXES.some((descriptor) => descriptor.fact === axis.fact); - -export type SemanticPart = { +type SemanticPart = { // One entry per axis, in SEMANTIC_AXES order: the value the part was split // out on, or null where the axis did not partition its members. parts: Array<[string, string | null]>; members: InstanceFacts[]; - // 'acquisition 2, echo 1'; null for members no axis separated. + // 'acquisition 2, echo 1'; null for members nothing separated. label: string | null; // Two members share a slice position and no axis separates them. repeatedPositions: boolean; @@ -51,18 +44,15 @@ export type SemanticPart = { // The key part that keeps the members of unreadable geometry apart from the // judged parts of the same series. -export const GEOMETRY_RULE = 'geometry'; -export const UNREADABLE_GEOMETRY = 'unreadable'; -export const UNREADABLE_GEOMETRY_LABEL = 'position unknown'; +const GEOMETRY_RULE = 'geometry'; +const UNREADABLE_GEOMETRY = 'unreadable'; /** - * Where a member sits along the slice axis. The planner passes the projection - * on its bucket's common normal; the member's own is the default. + * Where a member sits along the slice axis: the planner passes the projection + * on its bucket's common normal. */ export type PositionOf = (member: InstanceFacts) => number | null; -const ownPosition: PositionOf = (member) => member.projectedPosition; - const countDistinctPositions = ( members: InstanceFacts[], positionOf: PositionOf @@ -105,7 +95,7 @@ const groupByAxis = ( axis: SemanticAxis, singlePlane: boolean ) => { - const independentImages = singlePlane && isDescriptor(axis); + const independentImages = singlePlane && axis.kind === 'descriptor'; const tagged = new Map(); members.forEach((member) => { const value = member[axis.fact]; @@ -119,7 +109,8 @@ const groupByAxis = ( // a slice from a spatial stack. const eligible = new Map( [...tagged].filter( - ([, group]) => !axis.counter || independentImages || group.length > 1 + ([, group]) => + axis.kind === 'contrast' || independentImages || group.length > 1 ) ); const remainder = members.filter((member) => { @@ -164,29 +155,19 @@ const unsplit = ( }, ]; -/** Members no axis can judge, held apart under a key part of their own. */ -const unreadableGeometry = ( - members: InstanceFacts[], - axes: SemanticAxis[] -): SemanticPart => ({ - parts: [ - ...axes.map((axis): [string, null] => [axis.rule, null]), - [GEOMETRY_RULE, UNREADABLE_GEOMETRY], - ], - members, - label: UNREADABLE_GEOMETRY_LABEL, - repeatedPositions: false, - unreadablePositions: true, -}); - const labelFor = (axis: SemanticAxis, members: InstanceFacts[]) => { const values = new Set(members.map((member) => member[axis.fact])); const value = values.size === 1 ? [...values][0] : 'mixed'; return `${axis.rule} ${value ?? 'unknown'}`; }; -const splitUnreadable = (members: InstanceFacts[], axes: SemanticAxis[]) => { - const descriptors = DESCRIPTOR_AXES.filter((axis) => axes.includes(axis)); +// Members no axis can judge, held apart by descriptor under a key part of +// their own. +const splitUnreadable = ( + members: InstanceFacts[], + axes: SemanticAxis[] +): SemanticPart[] => { + const descriptors = axes.filter((axis) => axis.kind === 'descriptor'); const groups = [ ...groupBy(members, (member) => JSON.stringify(descriptors.map((axis) => member[axis.fact])) @@ -195,20 +176,19 @@ const splitUnreadable = (members: InstanceFacts[], axes: SemanticAxis[]) => { const differing = descriptors.filter( (axis) => new Set(members.map((member) => member[axis.fact])).size > 1 ); - return groups.map((group) => { - const part = unreadableGeometry(group, axes); - return { - ...part, - parts: part.parts.map(([rule, value]): [string, string | null] => { - const descriptor = descriptors.find((axis) => axis.rule === rule); - return [rule, descriptor ? group[0][descriptor.fact] : value]; - }), - label: [ - ...differing.map((axis) => labelFor(axis, group)), - part.label, - ].join(', '), - }; - }); + return groups.map((group) => ({ + parts: [ + ...axes.map((axis): [string, string | null] => [ + axis.rule, + axis.kind === 'descriptor' ? group[0][axis.fact] : null, + ]), + [GEOMETRY_RULE, UNREADABLE_GEOMETRY], + ], + members: group, + label: differing.map((axis) => labelFor(axis, group)).join(', ') || null, + repeatedPositions: false, + unreadablePositions: true, + })); }; function splitByAxes( @@ -221,9 +201,7 @@ function splitByAxes( const singlePlane = countDistinctPositions(members, positionOf) === 1; const found = firstSplittingAxis( members, - singlePlane - ? axes.filter((axis) => !axis.counter || isDescriptor(axis)) - : axes, + singlePlane ? axes.filter((axis) => axis.kind !== 'counter') : axes, positionOf, singlePlane ); @@ -277,7 +255,7 @@ function splitByAxes( */ export function splitOverlappingAcquisitions( members: InstanceFacts[], - positionOf: PositionOf = ownPosition + positionOf: PositionOf ): SemanticPart[] { const axes = [...SEMANTIC_AXES]; const readable = (member: InstanceFacts) => diff --git a/packages/dicom/core/header/__tests__/byteDeque.spec.ts b/packages/dicom/core/header/__tests__/byteDeque.spec.ts index c32e8a708..fda59164d 100644 --- a/packages/dicom/core/header/__tests__/byteDeque.spec.ts +++ b/packages/dicom/core/header/__tests__/byteDeque.spec.ts @@ -14,7 +14,7 @@ describe('ByteDeque', () => { dq.pushStart(new Uint8Array([1, 2, 3])); expect(dq.size).to.equal(9); - const data = dq.popAll(); + const data = dq.popStart(dq.size); expect(data).to.eql(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])); }); @@ -31,22 +31,6 @@ describe('ByteDeque', () => { expect(data).to.eql(new Uint8Array([8, 9])); }); - it('popEnd() should work', () => { - const dq = new ByteDeque(); - - dq.pushEnd(new Uint8Array([1, 2, 3, 4, 5])); - expect(dq.size).to.equal(5); - - dq.pushEnd(new Uint8Array([6, 7, 8, 9])); - expect(dq.size).to.equal(9); - - let data = dq.popEnd(7); - expect(data).to.eql(new Uint8Array([3, 4, 5, 6, 7, 8, 9])); - - data = dq.popEnd(2); - expect(data).to.eql(new Uint8Array([1, 2])); - }); - it('popStart() consumes the remainder', () => { const dq = new ByteDeque(); @@ -56,24 +40,4 @@ describe('ByteDeque', () => { const data = dq.popStart(10); expect(data).to.eql(new Uint8Array([1, 2, 3, 4, 5, 6])); }); - - it('popEnd() consumes the remainder', () => { - const dq = new ByteDeque(); - - dq.pushEnd(new Uint8Array([1, 2, 3])); - dq.pushEnd(new Uint8Array([4, 5, 6])); - - const data = dq.popEnd(10); - expect(data).to.eql(new Uint8Array([1, 2, 3, 4, 5, 6])); - }); - - it('clear() clears the deque', () => { - const dq = new ByteDeque(); - dq.pushStart(new Uint8Array([1, 2, 3, 4, 5])); - expect(dq.isEmpty()).to.be.false; - - dq.clear(); - expect(dq.size).to.equal(0); - expect(dq.isEmpty()).to.be.true; - }); }); diff --git a/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts b/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts index f8c4c6ca8..d7f6d091a 100644 --- a/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts +++ b/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts @@ -3,10 +3,15 @@ import { findElement, readDicomDataset } from '../../metadata/dicomDataset'; import { getDatasetTag } from '../../metadata/datasetAccess'; import { sequenceItems } from '../../metadata/functionalGroups'; import { concatBytes } from '../../utils'; -import { readHeader, syntheticSlice } from '@/tests/dicomSourceFixtures'; +import { + pixelDataStart, + readHeader, + syntheticSlice, +} from '@/tests/dicomSourceFixtures'; import { rawElement, sequenceItem, + toImplicitVr, undefinedLengthItem, undefinedLengthSequence, } from '@/tests/specs/syntheticDicom'; @@ -75,6 +80,50 @@ describe('streamed header encodings', () => { } ); + it.each([ + ['Explicit', false, 12], + ['Implicit', true, 8], + ])( + 'does not take the Pixel Data of a defined-length icon sequence for the image (%s VR)', + async (_name, implicitVr, headLength) => { + const icon = rawElement(0x7fe0, 0x0010, 'OW', new Uint8Array(64)); + const bytes = syntheticSlice({ + implicitVr, + rows: 16, + cols: 16, + extraElements: [rawElement(0x0088, 0x0200, 'SQ', sequenceItem(icon))], + }); + const pixelBytes = 16 * 16 * 2; + const instance = await readHeader(bytes, 7); + expect(instance.pixelData).toEqual({ + offset: bytes.length - pixelBytes - headLength, + valueOffset: bytes.length - pixelBytes, + length: pixelBytes, + }); + expect( + findElement(sequenceItems(instance.dataset, '00880200')[0], '7FE00010') + ).toBeDefined(); + } + ); + + it('reads past a defined-length sequence whose item is Implicit VR in an Explicit VR file', async () => { + const item = toImplicitVr( + concatBytes([ + rawElement(0x0008, 0x1150, 'UI', encode('1.2.840.10008.5.1.4.1.1.2\0')), + rawElement(0x0008, 0x1155, 'UI', encode('1.2.3\0')), + ]) + ); + const bytes = syntheticSlice({ + extraElements: [ + rawElement(0x0008, 0x1140, 'SQ', sequenceItem(item)), + rawElement(0x4008, 0x0103, 'LO', encode('AFTER ')), + ], + }); + const instance = await readHeader(bytes, 7); + expect(instance.pixelData?.offset).toBe(pixelDataStart(bytes)); + expect(getDatasetTag(instance.dataset, '40080103')).toBe('AFTER '); + }); + it('reads undefined-length Big Endian items and their following attributes', async () => { const sequence = bigEndianElement( rawElement(0x0008, 0x1140, 'SQ', new Uint8Array()), diff --git a/packages/dicom/core/header/byteDeque.ts b/packages/dicom/core/header/byteDeque.ts index 2515d3deb..ab962bff5 100644 --- a/packages/dicom/core/header/byteDeque.ts +++ b/packages/dicom/core/header/byteDeque.ts @@ -2,110 +2,31 @@ * A byte array deque. */ export default class ByteDeque { - private arrays: Uint8Array[]; + private arrays: Uint8Array[] = []; private _size = 0; - constructor() { - this.arrays = []; - } - get size() { return this._size; } - isEmpty() { - return this.size === 0; - } - - clear() { - this.arrays.length = 0; - this._size = 0; - } - /** * Push a new Uint8Array to the end. - * @param {Uint8Array} bytes */ pushEnd(bytes: Uint8Array) { this.arrays.push(bytes); this._size += bytes.length; } - /** - * Push the contents of a ByteDeque to the start. - * @param {ByteDeque} bytes - */ - pushStart(bytes: ByteDeque): void; - /** * Push a new Uint8Array to the start. - * @param {Uint8Array} bytes */ - pushStart(bytes: Uint8Array): void; - - pushStart(bytes: Uint8Array | ByteDeque) { - if (bytes instanceof ByteDeque) { - this.arrays.unshift(...bytes.arrays); - this._size += bytes.size; - bytes.clear(); - } else { - this.arrays.unshift(bytes); - this._size += bytes.length; - } - } - - /** - * Pop bytes off the end. - * @param {number} count - */ - popEnd(count: number): Uint8Array { - return this.consumeEnd(count, false) as Uint8Array; - } - - /** - * Erase bytes off the end. - * - * This is more efficient than ignoring the return value of popEnd - * due to not allocating memory for the return result. - * @param {number} count - */ - eraseEnd(count: number): void { - this.consumeEnd(count, true); - } - - private consumeEnd(count: number, discard = false) { - let processed = 0; - const bufferSize = Math.min(count, this.size); - const popped = discard ? null : new Uint8Array(bufferSize); - let writeOffset = bufferSize; - - while (processed < count && this.arrays.length) { - const bytes = this.arrays.pop()!; - const remaining = count - processed; - // chomp bytes[offset:] - const offset = remaining >= bytes.length ? 0 : bytes.length - remaining; - const takeEntireArray = offset === 0; - - if (popped) { - const toSet = takeEntireArray ? bytes : bytes.subarray(offset); - writeOffset -= toSet.length; - popped.set(toSet, writeOffset); - } - - if (!takeEntireArray) { - // put back remainder - this.arrays.push(bytes.subarray(0, offset)); - } - - processed += bytes.length - offset; - } - - return popped ?? undefined; + pushStart(bytes: Uint8Array) { + this.arrays.unshift(bytes); + this._size += bytes.length; } /** * Pop bytes off the start. - * @param {number} count */ popStart(count: number): Uint8Array { return this.consumeStart(count, false) as Uint8Array; @@ -116,7 +37,6 @@ export default class ByteDeque { * * This is more efficient than ignoring the return value of popStart * due to not allocating memory for the return result. - * @param {number} count */ eraseStart(count: number): void { this.consumeStart(count, true); @@ -152,12 +72,4 @@ export default class ByteDeque { this._size = Math.max(0, this._size - count); return popped ?? undefined; } - - popAll(discard = false) { - if (discard) { - this.arrays.length = 0; - return undefined; - } - return this.popStart(this.size); - } } diff --git a/packages/dicom/core/header/dicomParser.ts b/packages/dicom/core/header/dicomParser.ts index c1b6e3f4d..f54127034 100644 --- a/packages/dicom/core/header/dicomParser.ts +++ b/packages/dicom/core/header/dicomParser.ts @@ -1,7 +1,11 @@ import StreamingByteReader from './streamingByteReader'; import { toAscii, asCoroutine } from '../utils'; import { + DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN, + EXPLICIT_VR_BIG_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, PART_10_HEADER_LENGTH, + UNDEFINED_LENGTH, sniffDicomLayout, type DicomLayout, } from '../metadata/dicomLayout'; @@ -14,36 +18,22 @@ export type DataElement = { element: number; vr: string; length: number; - data: Array | Uint8Array | undefined; + /** Absent for sequences and encapsulated values, which are only stepped over. */ + data: Uint8Array | undefined; }; type DataElementCallback = (el: DataElement) => void; type ParseOptions = { - peek?: boolean; littleEndian?: boolean; explicitVr?: boolean; - endPosition?: number; onDataElement?: DataElementCallback; }; -const assertReadBounds = ( - reader: StreamingByteReader, - end: number | undefined, - length: number -) => { - if (end !== undefined && reader.position + length > end) - throw new Error('Data element exceeds its enclosing sequence or item'); -}; - // This is based on the DICOM standard as of 2023. All links may point to whatever is the current at the time of visiting. -const UndefinedLength = 0xffffffff; const isEncapsulatedValue = (vr: string, length: number) => - length === UndefinedLength && (vr === 'OB' || vr === 'OW'); -const ImplicitTransferSyntaxUID = '1.2.840.10008.1.2'; -export const ExplicitVRBigEndianUID = '1.2.840.10008.1.2.2'; -const DeflatedExplicitVRLittleEndianUID = '1.2.840.10008.1.2.1.99'; + length === UNDEFINED_LENGTH && (vr === 'OB' || vr === 'OW'); const Tags = { TransferSyntaxUID: [0x0002, 0x0010] as Tag, @@ -58,12 +48,6 @@ const ExplicitVrLegacyDataElementFormat = new Set(["AE", "AS", "AT", "CS", "DA", // prettier-ignore const ExplicitVrCannotHaveUndefinedLength = new Set(["SV", "UC", "UR", "UV", "UT"]); -const DEBUG = false; - -function debug(...args: any[]) { - if (DEBUG) console.log(...args); -} - function equalsToTag(tag: Tag) { return (group: number, element: number) => group === tag[0] && element === tag[1]; @@ -82,9 +66,6 @@ function* readElementTag( * Peeks the data element group num and element num * * Assumes the reader is pointing to the start of a Data Element. - * @param {*} reader - * @param {*} opts - * @returns */ function* peekElementTag( reader: StreamingByteReader, @@ -110,45 +91,36 @@ function* peekElementTag( * * Assumes the reader is pointing to the first byte of an element's value. * - * Does not return data for undefined lengths, but the reader pointer is advanced. - * @returns + * Returns no data for sequences and encapsulated values, but the reader pointer is advanced. */ function* readElementValue( reader: StreamingByteReader, vr: string, length: number, - { explicitVr = false, littleEndian = false, endPosition }: ParseOptions = {} + { explicitVr = false, littleEndian = false }: ParseOptions = {} ): Generator { - assertReadBounds( - reader, - endPosition, - length === UndefinedLength ? 0 : length - ); // See examples: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html // PS3.5 6.2.2: an undefined-length UN holds sequence items encoded // in Implicit VR Little Endian, regardless of the enclosing syntax. - if (vr === 'UN' && length === UndefinedLength) { - return yield* readSequenceValue(reader, length, { + if (vr === 'UN' && length === UNDEFINED_LENGTH) { + yield* skipSequenceValue(reader, length, { explicitVr: false, littleEndian: true, - endPosition, }); + return undefined; } if (vr === 'SQ') { - return yield* readSequenceValue(reader, length, { - explicitVr, - littleEndian, - endPosition, - }); + yield* skipSequenceValue(reader, length, { explicitVr, littleEndian }); + return undefined; } if (isEncapsulatedValue(vr, length)) { - yield* readFragments(reader, { littleEndian, endPosition }); + yield* readFragments(reader, { littleEndian }); return undefined; } - if (length === UndefinedLength) + if (length === UNDEFINED_LENGTH) throw new Error('cannot read a value of undefined length'); return yield* reader.read(length); } @@ -156,13 +128,11 @@ function* readElementValue( /** Fragment lengths bound opaque pixels, which can contain delimiter bytes. */ function* readFragments(reader: StreamingByteReader, opts: ParseOptions) { for (;;) { - assertReadBounds(reader, opts.endPosition, 8); const [group, element] = yield* readElementTag(reader, opts); const length = yield* reader.readUint32(opts); if (group === 0xfffe && element === 0xe0dd && length === 0) return; - if (!equalsToTag(Tags.Item)(group, element) || length === UndefinedLength) + if (!equalsToTag(Tags.Item)(group, element) || length === UNDEFINED_LENGTH) throw new Error('Expected a defined-length encapsulated fragment'); - assertReadBounds(reader, opts.endPosition, length); yield* reader.seek(length); } } @@ -172,18 +142,14 @@ function* readFragments(reader: StreamingByteReader, opts: ParseOptions) { * * Does not parse the value according to VR or transfer syntax. * - * Does not return the element value if the length is undefined. - * * Assumes the reader is pointing to the start of a Data Element. * https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.1 - * @param {*} reader */ function* readDataElement( reader: StreamingByteReader, opts: ParseOptions = {} ) { - const { littleEndian = false, explicitVr = false, endPosition } = opts; - assertReadBounds(reader, endPosition, 8); + const { littleEndian = false, explicitVr = false } = opts; // read tag const [group, element] = yield* readElementTag(reader, { littleEndian }); let length = 0; @@ -202,43 +168,27 @@ function* readDataElement( } if ( - length === UndefinedLength && + length === UNDEFINED_LENGTH && ExplicitVrCannotHaveUndefinedLength.has(vr) ) { console.warn(`Invalid DICOM. VR ${vr} may not have undefined length`); } - debug( - 'readDataElement explicitVr', - group.toString(16), - element.toString(16), - 'length', - length - ); data = yield* readElementValue(reader, vr, length, { littleEndian, explicitVr, - endPosition, }); } else { length = yield* reader.readUint32({ littleEndian }); - debug( - 'readDataElement implicitVr', - group.toString(16), - element.toString(16), - 'length', - length - ); // For implicit VR with undefined length, assume it's a sequence - if (length === UndefinedLength) { + if (length === UNDEFINED_LENGTH) { vr = 'SQ'; } data = yield* readElementValue(reader, vr, length, { littleEndian, explicitVr, - endPosition, }); } @@ -258,7 +208,6 @@ function* readDataElementsUntil( opts: ParseOptions ) { while (true) { - assertReadBounds(reader, opts.endPosition, 4); const [group, element] = yield* peekElementTag(reader, opts); if (untilFn(group, element)) { return; @@ -268,105 +217,56 @@ function* readDataElementsUntil( } } -/** - * Stops the reader when the byte length is exhausted from the reader position. - * - * Assumes the reader is pointing to the start of a Data Element. - */ -function* readFiniteDataElements( - reader: StreamingByteReader, - byteLength: number, - opts: ParseOptions -) { - const endPosition = reader.position + byteLength; - assertReadBounds(reader, opts.endPosition, byteLength); - while (reader.position < endPosition) { - const el = yield* readDataElement(reader, { ...opts, endPosition }); - opts.onDataElement?.(el); - } -} - -function* readSequenceItem(reader: StreamingByteReader, opts: ParseOptions) { +function* skipSequenceItem(reader: StreamingByteReader, opts: ParseOptions) { const itemByteLength = yield* reader.readUint32(opts); - const itemDataset: DataElement[] = []; - const itemOptions = { - ...opts, - onDataElement: (el: DataElement) => itemDataset.push(el), - }; - if (itemByteLength !== UndefinedLength) { - yield* readFiniteDataElements(reader, itemByteLength, itemOptions); - } else { - yield* readDataElementsUntil( - reader, - equalsToTag(Tags.ItemDelimiter), - itemOptions - ); - assertReadBounds(reader, opts.endPosition, 8); - yield* reader.seek(8); + if (itemByteLength !== UNDEFINED_LENGTH) { + yield* reader.seek(itemByteLength); + return; } - return itemDataset; -} - -function* finishSequence(reader: StreamingByteReader, end?: number) { - yield* reader.seek(4); - // The declared boundary wins over a premature delimiter in a finite SQ. - if (end !== undefined) yield* reader.seek(end - reader.position); + yield* readDataElementsUntil(reader, equalsToTag(Tags.ItemDelimiter), { + ...opts, + onDataElement: undefined, + }); + yield* reader.seek(8); } /** + * Steps over a sequence value. A defined length says where the value or item + * ends, so only undefined lengths are walked, to find their delimiters. + * * The reader must be pointing to the start of the sequence's data, namely the first item or the sequence delimitation item. * * See: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.html * and: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html */ -function* readSequenceValue( +function* skipSequenceValue( reader: StreamingByteReader, byteLength: number, opts: ParseOptions ) { - const items: DataElement[][] = []; - const endPosition = - byteLength === UndefinedLength ? undefined : reader.position + byteLength; - const itemOptions = { - ...opts, - endPosition: endPosition ?? opts.endPosition, - }; - while (endPosition === undefined || reader.position < endPosition) { - assertReadBounds(reader, itemOptions.endPosition, 8); + if (byteLength !== UNDEFINED_LENGTH) { + yield* reader.seek(byteLength); + return; + } + for (;;) { const [group, element] = yield* readElementTag(reader, opts); - - // Item tag - // https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html#table_7.5-3 if (equalsToTag(Tags.Item)(group, element)) { - items.push(yield* readSequenceItem(reader, itemOptions)); - continue; - } - - // Sequence Delimitation Item tag - // "Otherwise, the Value Field has an Undefined Length and a Sequence Delimitation Item marks the end of the Value Field." - // https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.2 - if (group === 0xfffe && element === 0xe0dd) { - yield* finishSequence(reader, endPosition); - return items; + yield* skipSequenceItem(reader, opts); + } else if (group === 0xfffe && element === 0xe0dd) { + yield* reader.seek(4); + return; + } else { + throw new Error( + `Expected a sequence item, found (${group.toString( + 16 + )},${element.toString(16)})` + ); } - - throw new Error( - `readSequenceValue: encountered unknown element: (${group.toString( - 16 - )},${element.toString(16)})` - ); } - return items; } // Per Part 10: "File Meta Information shall be encoded using the Explicit VR Little Endian Transfer Syntax" -// Transfer syntaxes are negotiated between DICOM nodes. Additionally, the File Meta Info block contains the transfer syntax used to encode the Data Set. -// Assumption: we are using Explicit VR Little Endian. The default (Implicit VR Little Endian) is not widely used. -// Assumption: File Meta Elements follow the VRs listed here: https://dicom.nema.org/medical/dicom/current/output/chtml/part06/chapter_7.html -// Resources: -// data element layout: https://www.leadtools.com/help/sdk/v20/dicom/api/overview-data-element-structure.html -// transfer syntax info: https://pacsbootcamp.com/transfer-syntax -function* readFieldMetaInfo( +function* readFileMetaInfo( reader: StreamingByteReader, opts?: { onDataElement?: DataElementCallback } ) { @@ -397,7 +297,7 @@ function* readFieldMetaInfo( // Compressed bytes can resemble meta elements. The complete reader will // locate the end of group 2 and inflate the dataset before walking it. - if (transferSyntaxUid === DeflatedExplicitVRLittleEndianUID) + if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) return { transferSyntaxUid }; // read until end of file meta info group block, which is the first non 0x0002 grouped element. @@ -419,6 +319,8 @@ type ReadDicomOptions = { onDataElement?: DataElementCallback; /** Called once the opening bytes say how the file is laid out. */ onLayout?(layout: DicomLayout): void; + /** Called once the file meta information or the layout names the syntax. */ + onTransferSyntax?(transferSyntaxUid: string): void; }; function* readDicomUntilPixelData(opts?: ReadDicomOptions) { @@ -432,27 +334,24 @@ function* readDicomUntilPixelData(opts?: ReadDicomOptions) { if (layout.preamble) yield* reader.seek(PART_10_HEADER_LENGTH); const transferSyntaxUid = layout.fileMeta - ? (yield* readFieldMetaInfo(reader, { + ? (yield* readFileMetaInfo(reader, { onDataElement: opts?.onDataElement, })).transferSyntaxUid : layout.transferSyntaxUid; + opts?.onTransferSyntax?.(transferSyntaxUid); // A negative boundary asks the metadata loader to retain the complete file. - if (transferSyntaxUid === DeflatedExplicitVRLittleEndianUID) - return { position: -1, transferSyntaxUid }; - const explicitVr = transferSyntaxUid !== ImplicitTransferSyntaxUID; - const littleEndian = transferSyntaxUid !== ExplicitVRBigEndianUID; + if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) + return { position: -1 }; + const explicitVr = transferSyntaxUid !== IMPLICIT_VR_LITTLE_ENDIAN; + const littleEndian = transferSyntaxUid !== EXPLICIT_VR_BIG_ENDIAN; yield* readDataElementsUntil( reader, - // (7fe0,0010): Pixel Data (group, element) => opts?.stopAtElement?.(group, element) ?? false, { explicitVr, littleEndian, onDataElement: opts?.onDataElement } ); - return { - position: reader.position, - transferSyntaxUid, - }; + return { position: reader.position }; } export const createDicomParser = (callbacks?: ReadDicomOptions) => { diff --git a/packages/dicom/core/header/readDicomHeader.ts b/packages/dicom/core/header/readDicomHeader.ts index 26ab3175a..878a8aa5b 100644 --- a/packages/dicom/core/header/readDicomHeader.ts +++ b/packages/dicom/core/header/readDicomHeader.ts @@ -1,6 +1,8 @@ -import { createDicomParser, ExplicitVRBigEndianUID } from './dicomParser'; +import { createDicomParser } from './dicomParser'; import { + EXPLICIT_VR_BIG_ENDIAN, IMPLICIT_VR_LITTLE_ENDIAN, + UNDEFINED_LENGTH, type DicomLayout, } from '../metadata/dicomLayout'; import { concatBytes, toAscii } from '../utils'; @@ -21,7 +23,6 @@ const MODALITY = [0x0008, 0x0060] as const; const PIXEL_DATA = [0x7fe0, 0x0010] as const; /** Tag, VR, reserved bytes and a 32 bit length: the longest element head. */ const PIXEL_DATA_HEAD_LENGTH = 12; -const UNDEFINED_LENGTH = 0xffffffff; const LONG_FORM_VRS = new Set(['OB', 'OD', 'OF', 'OL', 'OV', 'OW', 'UN']); const isTag = ( @@ -41,6 +42,7 @@ function headerParser(policy: ImageImportPolicy) { const found = { modality: undefined as string | undefined, layout: null as DicomLayout | null, + transferSyntaxUid: null as string | null, atPixelData: false, }; const parse = createDicomParser({ @@ -54,6 +56,9 @@ function headerParser(policy: ImageImportPolicy) { onLayout: (layout) => { found.layout = layout; }, + onTransferSyntax: (transferSyntaxUid) => { + found.transferSyntaxUid = transferSyntaxUid; + }, onDataElement: (el) => { if ( isTag(MODALITY, el.group, el.element) && @@ -78,11 +83,11 @@ async function readUntilStop( ) { const received: Uint8Array[] = []; let total = 0; - let stop: { position: number; transferSyntaxUid: string } | null = null; + let stop: { position: number } | null = null; const result = () => ({ received, + total, end: stop && stop.position >= 0 ? stop.position : undefined, - transferSyntaxUid: stop?.transferSyntaxUid ?? null, }); const reader = stream.getReader(); try { @@ -110,7 +115,7 @@ function pixelDataElement( ): PixelDataElement | null { if (head.length < 8) return null; const view = new DataView(head.buffer, head.byteOffset, head.byteLength); - const littleEndian = transferSyntaxUid !== ExplicitVRBigEndianUID; + const littleEndian = transferSyntaxUid !== EXPLICIT_VR_BIG_ENDIAN; const element = (length: number, headLength: number) => ({ offset, valueOffset: offset + headLength, @@ -137,18 +142,18 @@ export async function readDicomHeader( policy: ImageImportPolicy = 'complete-header' ) { const { parse, found } = headerParser(policy); - const { received, end, transferSyntaxUid } = await readUntilStop( - stream, - parse, - () => (found.atPixelData ? PIXEL_DATA_HEAD_LENGTH : 0) + const { received, total, end } = await readUntilStop(stream, parse, () => + found.atPixelData ? PIXEL_DATA_HEAD_LENGTH : 0 + ); + const { transferSyntaxUid } = found; + const bytes = concatBytes( + received, + Math.min(total, (end ?? total) + PIXEL_DATA_HEAD_LENGTH) ); - const header = concatBytes(received, end); const head = - found.atPixelData && end !== undefined - ? concatBytes(received).subarray(end, end + PIXEL_DATA_HEAD_LENGTH) - : null; + found.atPixelData && end !== undefined ? bytes.subarray(end) : null; return { - header, + header: bytes.subarray(0, end), layout: found.layout, transferSyntaxUid, pixelData: diff --git a/packages/dicom/core/header/streamingByteReader.ts b/packages/dicom/core/header/streamingByteReader.ts index 41d606ad0..1258361c9 100644 --- a/packages/dicom/core/header/streamingByteReader.ts +++ b/packages/dicom/core/header/streamingByteReader.ts @@ -18,12 +18,7 @@ export default class StreamingByteReader { return this.pos; } - /** - * Seeks along the byte stream. - * - * No negative values. - * @param offset - */ + /** Seeks along the byte stream. No negative values. */ *seek(offset: number) { if (offset < 0) { throw new Error('Offset must not be negative'); @@ -37,12 +32,7 @@ export default class StreamingByteReader { this.pos += offset; } - /** - * Reads a number of bytes. - * @param length - * @param param1 - * @returns - */ + /** Reads a number of bytes. */ *read( length: number, { peek = false } = {} @@ -67,56 +57,28 @@ export default class StreamingByteReader { return data; } - /** - * Reads an ASCII string. - * @param length - * @param param1 - * @returns - */ + /** Reads an ASCII string. */ *readAscii(length: number, { ignoreNulls = false, peek = false } = {}) { const bytes = yield* this.read(length, { peek }); return toAscii(bytes, { ignoreNulls }); } - /** - * - * @param {'getUint8' | 'getInt8' | ...} method - * @param length must be the length associated with the method - */ - private *readDataView( - method: T extends `get${infer R}` ? `get${R}` : never, + /** `length` must be the length associated with the method. */ + private *readDataView( + method: 'getUint16' | 'getUint32', length: number, { littleEndian = false, peek = false } = {} ) { const bytes = yield* this.read(length, { peek }); const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - if (method === 'getUint8' || method === 'getInt8') { - return dv[method](0) as number; - } - return dv[method](0, littleEndian) as number; - } - - *readUint8() { - return yield* this.readDataView('getUint8', 1); - } - - *readInt8() { - return yield* this.readDataView('getInt8', 1); + return dv[method](0, littleEndian); } *readUint16(opts = {}) { return yield* this.readDataView('getUint16', 2, opts); } - *readInt16(opts = {}) { - return yield* this.readDataView('getInt16', 2, opts); - } - *readUint32(opts = {}) { return yield* this.readDataView('getUint32', 4, opts); } - - *readInt32(opts = {}) { - return yield* this.readDataView('getInt32', 4, opts); - } } diff --git a/packages/dicom/core/index.ts b/packages/dicom/core/index.ts index d2cf2c438..0668a5769 100644 --- a/packages/dicom/core/index.ts +++ b/packages/dicom/core/index.ts @@ -21,7 +21,6 @@ export { // Datasets export { readDicomDataset, - isPrivateElement, type DicomDataset, type DicomElement, } from './metadata/dicomDataset'; @@ -46,11 +45,7 @@ export { export { seriesKeyOf } from './collections/instanceFacts'; // Volumes -export { - allocateVolume, - type Volume, - type AllocateVolumeOptions, -} from './volume/allocateVolume'; +export { allocateVolume, type Volume } from './volume/allocateVolume'; export { loadVolume, middleSlot, diff --git a/packages/dicom/core/instance/__tests__/readInstance.spec.ts b/packages/dicom/core/instance/__tests__/readInstance.spec.ts deleted file mode 100644 index bd17c3af4..000000000 --- a/packages/dicom/core/instance/__tests__/readInstance.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { readInstance } from '../readInstance'; -import { getDatasetTag } from '../../metadata/datasetAccess'; -import { - pixelDataStart, - syntheticSlice, - withoutPixelData, -} from '@/tests/dicomSourceFixtures'; -import { rawElement } from '@/tests/specs/syntheticDicom'; -import { trackedSource } from '@/tests/byteSourceFixtures'; - -const PATIENT_NAME = '00100010'; -const CHUNK = 256; - -const largeSlice = (modality = 'MR') => - syntheticSlice({ - rows: 64, - cols: 64, - modality, - patientName: 'DOE^JANE', - extraElements: [ - rawElement(0x0029, 0x0010, 'LO', new TextEncoder().encode('VENDOR')), - ], - }); - -const signal = () => new AbortController().signal; - -describe('readInstance', () => { - it('reads the public header and where Pixel Data starts', async () => { - const bytes = largeSlice(); - const { source } = trackedSource(bytes, CHUNK); - - const instance = await readInstance(source, signal()); - - expect(instance.source).toBe(source); - expect(getDatasetTag(instance.dataset, PATIENT_NAME)).toBe('DOE^JANE'); - expect( - instance.dataset.elements.some((element) => element.group === 0x0029) - ).toBe(false); - const start = pixelDataStart(bytes); - expect(instance.pixelData).toEqual({ - offset: start, - valueOffset: start + 12, - length: bytes.length - start - 12, - }); - expect(instance.transferSyntaxUid).toBe('1.2.840.10008.1.2.1'); - expect(instance.layout).toMatchObject({ preamble: true, fileMeta: true }); - expect(instance.ultrasoundRegions).toBeNull(); - expect(Object.isFrozen(instance)).toBe(true); - }); - - it('stops pulling bytes at the header and cancels the stream', async () => { - const bytes = largeSlice(); - const { source, stats } = trackedSource(bytes, CHUNK); - - await readInstance(source, signal()); - - expect(stats.cancelled).toBe(1); - expect(stats.delivered).toBeLessThanOrEqual( - pixelDataStart(bytes) + 2 * CHUNK - ); - expect(stats.delivered).toBeLessThan(bytes.length / 2); - }); - - it('reads an object without Pixel Data to its last byte', async () => { - const bytes = withoutPixelData(largeSlice()); - const { source, stats } = trackedSource(bytes, CHUNK); - - const instance = await readInstance(source, signal()); - - expect(instance.pixelData).toBeNull(); - expect(getDatasetTag(instance.dataset, PATIENT_NAME)).toBe('DOE^JANE'); - expect(stats.delivered).toBe(bytes.length); - }); - - it('returns after the Modality tag of an RT object only when asked to', async () => { - const bytes = largeSlice('RTDOSE'); - const skipped = trackedSource(bytes, CHUNK); - const complete = trackedSource(bytes, CHUNK); - - const shortcut = await readInstance(skipped.source, signal(), { - imageImportPolicy: 'skip-radiotherapy', - }); - const full = await readInstance(complete.source, signal()); - - expect(shortcut.pixelData).toBeNull(); - expect(getDatasetTag(shortcut.dataset, PATIENT_NAME)).toBeUndefined(); - expect(full.pixelData?.offset).toBe(pixelDataStart(bytes)); - expect(skipped.stats.delivered).toBeLessThan(complete.stats.delivered); - }); - - it('reads nothing once its signal has aborted', async () => { - const { source, stats } = trackedSource(largeSlice(), CHUNK); - const controller = new AbortController(); - controller.abort(new DOMException('stop', 'AbortError')); - - await expect(readInstance(source, controller.signal)).rejects.toMatchObject( - { name: 'AbortError' } - ); - expect(stats.reads).toBe(0); - }); -}); diff --git a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts index 593f0cc74..1bbcfe420 100644 --- a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts +++ b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts @@ -29,6 +29,18 @@ import { const REGION = { physicalDeltaX: 0.0625, physicalDeltaY: 0.125 }; const never = () => new AbortController().signal; +const CHUNK = 256; + +const largeSlice = () => + syntheticSlice({ + rows: 64, + cols: 64, + modality: 'MR', + patientName: 'DOE^JANE', + extraElements: [ + rawElement(0x0029, 0x0010, 'LO', new TextEncoder().encode('VENDOR')), + ], + }); describe('readInstance over byte sources', () => { it.each([ @@ -69,6 +81,48 @@ describe('readInstance over byte sources', () => { } ); + it('reads the header and where Pixel Data starts', async () => { + const bytes = largeSlice(); + const { source } = trackedSource(bytes, CHUNK); + + const instance = await readInstance(source, never()); + + expect(instance.source).toBe(source); + expect(getDatasetTag(instance.dataset, '00100010')).toBe('DOE^JANE'); + const start = pixelDataStart(bytes); + expect(instance.pixelData).toEqual({ + offset: start, + valueOffset: start + 12, + length: bytes.length - start - 12, + }); + expect(instance.transferSyntaxUid).toBe(EXPLICIT_VR_LITTLE_ENDIAN); + expect(Object.isFrozen(instance)).toBe(true); + }); + + it('stops pulling bytes at the header and cancels the stream', async () => { + const bytes = largeSlice(); + const { source, stats } = trackedSource(bytes, CHUNK); + + await readInstance(source, never()); + + expect(stats.cancelled).toBe(1); + expect(stats.delivered).toBeLessThanOrEqual( + pixelDataStart(bytes) + 2 * CHUNK + ); + expect(stats.delivered).toBeLessThan(bytes.length / 2); + }); + + it('reads nothing once its signal has aborted', async () => { + const { source, stats } = trackedSource(largeSlice(), CHUNK); + const controller = new AbortController(); + controller.abort(new DOMException('stop', 'AbortError')); + + await expect(readInstance(source, controller.signal)).rejects.toMatchObject( + { name: 'AbortError' } + ); + expect(stats.reads).toBe(0); + }); + it('reads a Part 10 file with its layout', async () => { const bytes = syntheticSlice({ patientName: 'DOE^JOHN', modality: 'CT' }); @@ -170,22 +224,30 @@ describe('readInstance over byte sources', () => { it('reads every tag of an object that has no Pixel Data', async () => { const bytes = withoutPixelData(syntheticSlice({ modality: 'SR' })); - const { dataset } = await readHeader(bytes); + const { dataset, transferSyntaxUid, pixelData } = await readHeader(bytes); expect(dataset).toEqual(readDicomDataset(bytes)); expect(dataset.elements.length).toBeGreaterThan(1); + expect(pixelData).toBeNull(); + expect(transferSyntaxUid).toBe(EXPLICIT_VR_LITTLE_ENDIAN); }); - it('reads a radiotherapy object without Pixel Data no further than its modality', async () => { - const bytes = withoutPixelData(syntheticSlice({ modality: 'RTSTRUCT' })); - const { source, stats } = trackedSource(bytes, 32); + it('reads a radiotherapy object no further than its modality, only when asked to', async () => { + const bytes = syntheticSlice({ modality: 'RTDOSE', patientName: 'DOE' }); + const skipped = trackedSource(bytes, 32); - const { dataset } = await readInstance(source, never(), { + const shortcut = await readInstance(skipped.source, never(), { imageImportPolicy: 'skip-radiotherapy', }); + const full = await readHeader(bytes, 32); - expect(getDatasetTag(dataset, Tags.Modality)?.trim()).toBe('RTSTRUCT'); - expect(stats.delivered).toBeLessThan(bytes.length); + expect(getDatasetTag(shortcut.dataset, Tags.Modality)?.trim()).toBe( + 'RTDOSE' + ); + expect(getDatasetTag(shortcut.dataset, '00100010')).toBeUndefined(); + expect(shortcut.pixelData).toBeNull(); + expect(skipped.stats.delivered).toBeLessThan(pixelDataStart(bytes)); + expect(full.pixelData?.offset).toBe(pixelDataStart(bytes)); }); it('rejects a byte source that is not DICOM', async () => { diff --git a/packages/dicom/core/instance/readInstance.ts b/packages/dicom/core/instance/readInstance.ts index 5dfd64bad..e4de5d98b 100644 --- a/packages/dicom/core/instance/readInstance.ts +++ b/packages/dicom/core/instance/readInstance.ts @@ -1,9 +1,5 @@ import type { ByteSource } from '../source/byteSource'; -import { - readDicomDataset, - withoutPrivateElements, - type DicomDataset, -} from '../metadata/dicomDataset'; +import { readPublicDataset, type DicomDataset } from '../metadata/dicomDataset'; import type { DicomLayout } from '../metadata/dicomLayout'; import { getDatasetModality } from '../metadata/datasetAccess'; import { @@ -50,9 +46,8 @@ export async function readInstance( const { header, layout, transferSyntaxUid, pixelData } = await readDicomHeader(source.read(signal), options.imageImportPolicy); signal.throwIfAborted(); - const parsed = await (options.readDataset ?? readDicomDataset)(header); + const dataset = await (options.readDataset ?? readPublicDataset)(header); signal.throwIfAborted(); - const dataset = withoutPrivateElements(parsed); return Object.freeze({ source, dataset, diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts index 7df810002..2c0990b41 100644 --- a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -5,7 +5,7 @@ import { createDicomParser } from '../../header/dicomParser'; import { deflateRawSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; import { parseDicomElements } from '../dcmjsParser'; -import { PART_10_HEADER_LENGTH, PREAMBLE_LENGTH } from '../dicomLayout'; +import { PART_10_HEADER_LENGTH } from '../dicomLayout'; import { concatBytes } from '../../utils'; import { buildSlice } from '@/tests/specs/dicomElementFixtures'; import { pixelDataStart, readHeader } from '@/tests/dicomSourceFixtures'; @@ -19,6 +19,7 @@ import { undefinedLengthSequence, } from '@/tests/specs/syntheticDicom'; +const PREAMBLE_LENGTH = 128; // (0002,0000) UL occupies twelve bytes, including its value. const GROUP_LENGTH_ELEMENT_LENGTH = 12; const withoutGroupLength = (file: Uint8Array) => @@ -193,9 +194,11 @@ describe('lenient headers with standards-defined values', () => { const dataset = readDicomDataset(bytes); expect(findElement(dataset, '00400275')?.values.kind).toBe('unread'); expect(getDatasetTag(dataset, '00431030')).toBe('AFTER '); - await expect(readHeader(bytes, 7)).rejects.toThrow( - 'enclosing sequence or item' + const instance = await readHeader(bytes, 7); + expect(findElement(instance.dataset, '00400275')?.values.kind).toBe( + 'unread' ); + expect(instance.pixelData?.offset).toBe(pixelDataStart(bytes)); }); it('decodes a known defined-length UN using the dataset character set', () => { @@ -294,7 +297,6 @@ it.each([sequenceItem, undefinedLengthItem])( ]); const dataset = readDicomDataset(bytes); const sequence = findElement(dataset, '00431029')!.values; - expect(findElement(dataset, '00431029')!.bytes).toBeUndefined(); if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); expect(getDatasetTag(sequence.items[0], '00100010')).toBe('DOE^JANE'); const instance = await readHeader(bytes, 7); diff --git a/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts b/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts new file mode 100644 index 000000000..971efa1f7 --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest'; +import { getDatasetTag } from '../datasetAccess'; +import { readDicomDataset } from '../dicomDataset'; +import { Tags } from '../dicomTags'; +import { + buildSlice, + CHINESE_NAME_BYTES, + CHINESE_NAME_PADDED, + GB18030_NAME_BYTES, + GB18030_NAME_PADDED, + JAPANESE_NAME, + JAPANESE_NAME_BYTES, + KATAKANA_NAME, + KATAKANA_NAME_BYTES, + KOREAN_NAME, + KOREAN_NAME_BYTES, + LATIN1_NAME_BYTES, + LATIN1_NAME_PADDED, + MIXED_JIS_NAME, + MIXED_JIS_NAME_BYTES, +} from '@/tests/specs/dicomElementFixtures'; +import { rawElement } from '@/tests/specs/syntheticDicom'; + +const CURRENT_PATIENT_LOCATION = '0038|0300'; +const STUDY_COMMENTS = '0032|4000'; +const JIS = 'ISO 2022 IR 13\\ISO 2022 IR 87'; + +const encodeUtf8 = (text: string) => new TextEncoder().encode(text); + +const read = (...options: Parameters) => { + const dataset = readDicomDataset(buildSlice(...options)); + return (tag: string) => getDatasetTag(dataset, tag); +}; + +// (0038,0300) is LO, whose value multiplicity is 1-n. +const patientLocation = (value: Uint8Array) => + rawElement(0x0038, 0x0300, 'LO', value); + +describe('DICOM text in a declared character set', () => { + it.each([ + ['ISO 2022 IR 6\\ISO 2022 IR 87', JAPANESE_NAME_BYTES, JAPANESE_NAME], + ['ISO 2022 IR 6\\ISO 2022 IR 149', KOREAN_NAME_BYTES, KOREAN_NAME], + ['ISO 2022 IR 6\\ISO 2022 IR 58', CHINESE_NAME_BYTES, CHINESE_NAME_PADDED], + ['GB18030', GB18030_NAME_BYTES, GB18030_NAME_PADDED], + ['ISO_IR 100', LATIN1_NAME_BYTES, LATIN1_NAME_PADDED], + [JIS, KATAKANA_NAME_BYTES, KATAKANA_NAME], + [JIS, MIXED_JIS_NAME_BYTES, MIXED_JIS_NAME], + ])( + 'decodes a patient name written in %s', + (specificCharacterSet, patientNameBytes, name) => { + expect( + read({ specificCharacterSet, patientNameBytes })(Tags.PatientName) + ).toBe(name); + } + ); + + // A backslash inside an LT is a character, not a value delimiter. + it('renders 0x5c as a yen sign inside an LT when JIS X 0201 is declared', () => { + const tag = read({ + specificCharacterSet: JIS, + extraElements: [ + rawElement(0x0032, 0x4000, 'LT', encodeUtf8('C:\\DICOM')), + ], + }); + + expect(tag(STUDY_COMMENTS)).toBe('C:\u00a5DICOM'); + }); + + it('keeps a numeric VR out of the character set conversion', () => { + const tag = read({ + specificCharacterSet: JIS, + patientNameBytes: MIXED_JIS_NAME_BYTES, + imageOrientationPatient: [1, 0, 0, 0, -1, 0], + imagePositionPatient: [1.5, -2, 3], + pixelSpacing: [0.5, 0.75], + }); + + expect(tag(Tags.PatientName)).toBe(MIXED_JIS_NAME); + expect(tag(Tags.ImageOrientationPatient)).toBe('1\\0\\0\\0\\-1\\0'); + expect(tag(Tags.ImagePositionPatient)).toBe('1.5\\-2\\3'); + expect(tag(Tags.PixelSpacing)).toBe('0.5\\0.75'); + }); + + it('decodes each value of a multi valued LO on its own', () => { + const latin1 = read({ + specificCharacterSet: 'ISO_IR 100', + extraElements: [ + patientLocation( + Uint8Array.of( + ...[0x42, 0xe4, 0x63, 0x6b, 0x65, 0x72, 0x5c], + ...[0x4a, 0xf6, 0x72, 0x67, 0x20] + ) + ), + ], + }); + const utf8 = read({ + specificCharacterSet: 'ISO_IR 192', + extraElements: [patientLocation(encodeUtf8('\u738b\\\u5c0f\u660e'))], + }); + + expect(latin1(CURRENT_PATIENT_LOCATION)).toBe('B\u00e4cker\\J\u00f6rg '); + expect(utf8(CURRENT_PATIENT_LOCATION)).toBe('\u738b\\\u5c0f\u660e'); + }); +}); diff --git a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts index b14d8f0da..58aa35da8 100644 --- a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts @@ -21,8 +21,6 @@ const IMAGE_POSITION_PATIENT = '00200032'; const SPECIFIC_CHARACTER_SET = '00080005'; const ICC_PROFILE = '00282000'; const FRAME_DIMENSION_POINTER = '0028000A'; -const SIEMENS_CSA_DATA = '00291010'; -const GE_PRIVATE_TAG = '00091001'; const ULTRASOUND_REGIONS = '00186011'; const PHYSICAL_DELTA_X = '0018602C'; const REQUEST_ATTRIBUTES = '00400275'; @@ -253,26 +251,6 @@ describe('readDicomDataset', () => { expect(values.reason.length).toBeGreaterThan(0); }); - it('keeps a private element and the bytes of its value', () => { - const dataset = readDicomDataset( - buildSlice({ extraElements: MIXED_VR_ELEMENTS }) - ); - - expect(findElement(dataset, SIEMENS_CSA_DATA)?.bytes).toEqual( - new Uint8Array(6).fill(0x41) - ); - expect(findElement(dataset, GE_PRIVATE_TAG)?.bytes).toEqual( - ascii('GEPRIV ') - ); - expect(findElement(dataset, GE_PRIVATE_TAG)?.vr).toBe('SH'); - }); - - it('leaves a public element of a known VR without a byte copy', () => { - const dataset = readDicomDataset(buildSlice()); - - expect(findElement(dataset, PATIENT_NAME)?.bytes).toBeUndefined(); - }); - it('reads a buffer VR as bytes and an AT as referenced tags', () => { const dataset = readDicomDataset( buildSlice({ extraElements: MIXED_VR_ELEMENTS }) diff --git a/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts b/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts index c95b26c15..de9043128 100644 --- a/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts +++ b/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts @@ -3,11 +3,9 @@ import { readDicomDataset } from '../dicomDataset'; import { concatBytes } from '../../utils'; import { syntheticSlice } from '@/tests/dicomSourceFixtures'; import { rawElement, sequenceItem } from '@/tests/specs/syntheticDicom'; -import { - readUltrasoundRegions, - unitToMm, - US_UNIT_CENTIMETERS, -} from '../ultrasoundRegion'; +import { readUltrasoundRegions, unitToMm } from '../ultrasoundRegion'; + +const US_UNIT_CENTIMETERS = 3; const u16LE = (value: number) => { const bytes = new Uint8Array(2); diff --git a/packages/dicom/core/metadata/dcmjsParser.ts b/packages/dicom/core/metadata/dcmjsParser.ts index d5358b6ba..5846cbe63 100644 --- a/packages/dicom/core/metadata/dcmjsParser.ts +++ b/packages/dicom/core/metadata/dcmjsParser.ts @@ -1,8 +1,11 @@ import dcmjs, { DicomElement, DicomReadStream } from 'dcmjs'; import { + DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN, + EXPLICIT_VR_BIG_ENDIAN, EXPLICIT_VR_LITTLE_ENDIAN, IMPLICIT_VR_LITTLE_ENDIAN, PART_10_HEADER_LENGTH, + UNDEFINED_LENGTH, sniffDicomLayout, } from './dicomLayout'; @@ -18,10 +21,7 @@ const FILE_META_GROUP = 0x0002; const FILE_META_GROUP_LENGTH = '00020000'; const TRANSFER_SYNTAX_UID = '00020010'; const PIXEL_DATA = '7FE00010'; -const EXPLICIT_VR_BIG_ENDIAN = '1.2.840.10008.1.2.2'; -const DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1.99'; const RESERVED_LENGTH = 2; -const UNDEFINED_LENGTH = 0xffffffff; /** VRs whose explicit form carries two reserved bytes and a 32 bit length. */ const LENGTH_32_VRS = new Set([ diff --git a/packages/dicom/core/metadata/dicomCharacterSet.ts b/packages/dicom/core/metadata/dicomCharacterSet.ts index d5a6ae45d..e4ecf5375 100644 --- a/packages/dicom/core/metadata/dicomCharacterSet.ts +++ b/packages/dicom/core/metadata/dicomCharacterSet.ts @@ -14,9 +14,6 @@ const DELIMITER_BYTES = new Set([0x0a, 0x0c, 0x0d, 0x3d, 0x5c, 0x5e]); */ export const CHARSET_VRS = new Set(['SH', 'LO', 'ST', 'PN', 'LT', 'UC', 'UT']); -/** Bytes of a VR the Specific Character Set does not reach are code points. */ -export const defaultRepertoire = (raw: string) => raw; - /** A repertoire in force over one run of bytes. */ type Repertoire = { decode: (bytes: Uint8Array) => string; diff --git a/packages/dicom/core/metadata/dicomDataset.ts b/packages/dicom/core/metadata/dicomDataset.ts index 1e5f347b9..e2c712b06 100644 --- a/packages/dicom/core/metadata/dicomDataset.ts +++ b/packages/dicom/core/metadata/dicomDataset.ts @@ -3,13 +3,11 @@ import { ParsedElement, ParsedValue, parseDicomElements, - toBytes, } from './dcmjsParser'; -import { concatBytes, trimDicomPadding } from '../utils'; +import { trimDicomPadding } from '../utils'; import { CHARSET_VRS, characterSetDecoder, - defaultRepertoire, VALUE_DELIMITER, } from './dicomCharacterSet'; @@ -20,46 +18,12 @@ type DicomTagKey = string; type AttributeTag = { group: number; element: number }; -/** VRs whose values are text under the default repertoire or a declared set. */ -const TEXT_VRS = new Set([ - 'AE', - 'AS', - 'CS', - 'DA', - 'DT', - 'LO', - 'LT', - 'PN', - 'SH', - 'ST', - 'TM', - 'UC', - 'UI', - 'UR', - 'UT', -]); - /** Text VRs of value multiplicity 1, whose backslash is a character. */ const SINGLE_VALUED_TEXT_VRS = new Set(['LT', 'ST', 'UT']); /** VRs holding a number written as characters. */ const DECIMAL_VRS = new Set(['DS', 'IS']); -/** VRs holding a number written as bytes. */ -const NUMBER_VRS = new Set(['FL', 'FD', 'SL', 'SS', 'SV', 'UL', 'US', 'UV']); - -/** VRs whose value is an opaque buffer. */ -const BYTES_VRS = new Set(['OB', 'OD', 'OF', 'OL', 'OV', 'OW', 'UN']); - -const KNOWN_VRS = new Set([ - ...TEXT_VRS, - ...DECIMAL_VRS, - ...NUMBER_VRS, - ...BYTES_VRS, - 'AT', - 'SQ', -]); - type DicomValues = /** A text VR, one entry per value, with the Specific Character Set applied. */ | { kind: 'text'; values: string[] } @@ -83,8 +47,6 @@ export type DicomElement = { element: number; vr: string; values: DicomValues; - /** Value bytes, kept where the VR alone does not say how to read them. */ - bytes?: Uint8Array; }; export type DicomDataset = { @@ -122,21 +84,6 @@ const attributeTagOf = (packed: number) => ({ element: packed & 0xffff, }); -/** Undecoded value bytes, where every value carries them. */ -const rawBytesOf = ({ values }: ParsedElement) => { - if (values.every(isText)) return toBytes(values.join(VALUE_DELIMITER)); - if (values.every(isBytes)) - return values.length === 1 ? values[0] : concatBytes(values); - return undefined; -}; - -/** - * A private element's meaning follows its private creator, and an unknown VR - * says nothing at all, so both keep the bytes the file wrote. - */ -const keepsBytes = ({ group, vr }: ParsedElement) => - (group & 1) === 1 || vr === 'UN' || !KNOWN_VRS.has(vr); - type CharacterSetDecoder = ReturnType; /** @@ -149,8 +96,7 @@ const textValues = ( values: string[], decode: CharacterSetDecoder ) => { - if (!CHARSET_VRS.has(vr) || values.length === 0) - return values.map(defaultRepertoire); + if (!CHARSET_VRS.has(vr) || values.length === 0) return values; const raw = values.join(VALUE_DELIMITER); return SINGLE_VALUED_TEXT_VRS.has(vr) ? [decode.value(raw)] @@ -200,18 +146,13 @@ const buildElement = ( parsed: ParsedElement, decode: CharacterSetDecoder, charset: string[] | null -): DicomElement => { - const bytes = - !parsed.items && keepsBytes(parsed) ? rawBytesOf(parsed) : undefined; - return { - tag: tagKey(parsed.group, parsed.element), - group: parsed.group, - element: parsed.element, - vr: parsed.vr, - values: elementValues(parsed, decode, charset), - ...(bytes ? { bytes } : {}), - }; -}; +): DicomElement => ({ + tag: tagKey(parsed.group, parsed.element), + group: parsed.group, + element: parsed.element, + vr: parsed.vr, + values: elementValues(parsed, decode, charset), +}); // The declared set is the values the data set itself wrote, so a data set that // declares none stays distinguishable from one that declares the default. @@ -241,9 +182,9 @@ function buildDataset( } /** - * Reads a Part 10 file's header into a standards-shaped data set: every element - * keeps its tag, VR, value multiplicity, nested items and, where the VR alone - * cannot say how to read it, its bytes. Nothing missing is filled in. + * Reads a header into a standards-shaped data set: every element before Pixel + * Data keeps its tag, VR, value multiplicity and nested items. Nothing missing + * is filled in. */ export const readDicomDataset = (bytes: Uint8Array) => buildDataset(parseDicomElements(bytes), null); @@ -267,3 +208,7 @@ export const withoutPrivateElements = ( : element ), }); + +/** The data set an instance carries, filtered where it is parsed. */ +export const readPublicDataset = (bytes: Uint8Array) => + withoutPrivateElements(readDicomDataset(bytes)); diff --git a/packages/dicom/core/metadata/dicomLayout.ts b/packages/dicom/core/metadata/dicomLayout.ts index 8aae9ae53..621e98830 100644 --- a/packages/dicom/core/metadata/dicomLayout.ts +++ b/packages/dicom/core/metadata/dicomLayout.ts @@ -9,13 +9,18 @@ import { toAscii } from '../utils'; * information may start at the first byte, or the data set itself may, with * nothing to name its transfer syntax but the shape of its first element. */ -export const PREAMBLE_LENGTH = 128; +const PREAMBLE_LENGTH = 128; const DICOM_PREFIX = 'DICM'; /** The bytes a Part 10 file spends before its first element. */ export const PART_10_HEADER_LENGTH = PREAMBLE_LENGTH + DICOM_PREFIX.length; export const IMPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2'; export const EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1'; +export const EXPLICIT_VR_BIG_ENDIAN = '1.2.840.10008.1.2.2'; +export const DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1.99'; + +/** The length field of a value whose end a delimiter marks. */ +export const UNDEFINED_LENGTH = 0xffffffff; export type DicomLayout = /** Part 10: preamble, prefix and file meta information. */ diff --git a/packages/dicom/core/metadata/functionalGroups.ts b/packages/dicom/core/metadata/functionalGroups.ts index 0b0937264..63035cb98 100644 --- a/packages/dicom/core/metadata/functionalGroups.ts +++ b/packages/dicom/core/metadata/functionalGroups.ts @@ -3,7 +3,7 @@ import { findElement } from './dicomDataset'; import { canonicalTag, getDatasetTag } from './datasetAccess'; import { getNmDetectorTag } from './nmReconstruction'; -const SHARED_GROUPS = '52009229'; +export const SHARED_GROUPS = '52009229'; const PER_FRAME_GROUPS = '52009230'; const IMAGE_MACROS = new Map([ diff --git a/packages/dicom/core/metadata/modalityRescale.ts b/packages/dicom/core/metadata/modalityRescale.ts index 24a70e515..8d2acf165 100644 --- a/packages/dicom/core/metadata/modalityRescale.ts +++ b/packages/dicom/core/metadata/modalityRescale.ts @@ -22,11 +22,3 @@ export function hasUniformModalityRescale(metadata: DicomDataset) { ); }); } - -/** GDCM applies one transform to an instance, so its frames must agree. */ -export function assertUniformModalityRescale(metadata: DicomDataset) { - if (!hasUniformModalityRescale(metadata)) - throw new Error( - 'Cannot load DICOM frames with differing modality rescale: the decoder applies one transform to the entire instance' - ); -} diff --git a/packages/dicom/core/metadata/readDicomDataset.worker.ts b/packages/dicom/core/metadata/readDicomDataset.worker.ts index 4446f9a64..0fcd78a32 100644 --- a/packages/dicom/core/metadata/readDicomDataset.worker.ts +++ b/packages/dicom/core/metadata/readDicomDataset.worker.ts @@ -1,5 +1,7 @@ import * as Comlink from 'comlink'; -import { readDicomDataset } from './dicomDataset'; +import { readPublicDataset } from './dicomDataset'; -export type DicomDatasetWorker = { readDicomDataset: typeof readDicomDataset }; -Comlink.expose({ readDicomDataset }); +export type DicomDatasetWorker = { + readPublicDataset: typeof readPublicDataset; +}; +Comlink.expose({ readPublicDataset }); diff --git a/packages/dicom/core/metadata/ultrasoundRegion.ts b/packages/dicom/core/metadata/ultrasoundRegion.ts index 4482b25fd..48dae7531 100644 --- a/packages/dicom/core/metadata/ultrasoundRegion.ts +++ b/packages/dicom/core/metadata/ultrasoundRegion.ts @@ -10,7 +10,7 @@ import { Tags } from './dicomTags'; // 5=hertz, 6=dB/sec, 7=cm/sec, 8=cm², 9=cm²/sec, 10=cm³, 11=cm³/sec, // 12=degrees) are time, frequency, velocity, area, volume, or angle, so // they are not converted to a VTK image spacing. -export const US_UNIT_CENTIMETERS = 3; +const US_UNIT_CENTIMETERS = 3; // Returns the multiplier that converts a physical-delta value in the given // unit to millimetres, or null when the unit is not a spatial spacing. diff --git a/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts b/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts index f3c956a8c..bc1a7d2f8 100644 --- a/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts +++ b/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { encapsulatedPixelData, pixelItem } from '@/tests/specs/syntheticDicom'; +import { + encapsulatedPixelData, + sequenceItem, +} from '@/tests/specs/syntheticDicom'; import { splitEncapsulatedFrames } from '../encapsulatedFrames'; const SOI = [0xff, 0xd8]; @@ -77,9 +80,9 @@ describe('splitEncapsulatedFrames', () => { it('reads a value that ends after its last item without a delimiter', () => { const value = concat( - pixelItem(new Uint8Array()), - pixelItem(jpeg(1)), - pixelItem(jpeg(2)) + sequenceItem(new Uint8Array()), + sequenceItem(jpeg(1)), + sequenceItem(jpeg(2)) ); expect(bytesOf(splitEncapsulatedFrames(value, 2))).toEqual([ @@ -100,9 +103,9 @@ describe('splitEncapsulatedFrames', () => { it('keeps an odd item length as written', () => { const odd = jpeg(1, 2, 3).subarray(0, 6); const value = concat( - pixelItem(new Uint8Array()), - pixelItem(odd), - pixelItem(jpeg(2)), + sequenceItem(new Uint8Array()), + sequenceItem(odd), + sequenceItem(jpeg(2)), DELIMITER ); @@ -126,7 +129,7 @@ describe('splitEncapsulatedFrames', () => { [ 'a tag that is not an item', concat( - pixelItem(new Uint8Array()), + sequenceItem(new Uint8Array()), Uint8Array.from([0xe0, 0x7f, 0x10, 0, 2, 0, 0, 0, 1, 2]) ), /expected an item at byte 8/, @@ -134,22 +137,26 @@ describe('splitEncapsulatedFrames', () => { [ 'an item of undefined length', concat( - pixelItem(new Uint8Array()), + sequenceItem(new Uint8Array()), Uint8Array.from([0xfe, 0xff, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff]) ), /undefined length/, ], [ 'an offset table whose length is not a multiple of four', - concat(pixelItem(Uint8Array.from([0, 0])), pixelItem(jpeg(1)), DELIMITER), + concat( + sequenceItem(Uint8Array.from([0, 0])), + sequenceItem(jpeg(1)), + DELIMITER + ), /Basic Offset Table holds 2 bytes/, ], [ 'an offset that starts no fragment', concat( - pixelItem(Uint8Array.from([0, 0, 0, 0, 3, 0, 0, 0])), - pixelItem(jpeg(1)), - pixelItem(jpeg(2)), + sequenceItem(Uint8Array.from([0, 0, 0, 0, 3, 0, 0, 0])), + sequenceItem(jpeg(1)), + sequenceItem(jpeg(2)), DELIMITER ), /entry 1 \(3\) starts no fragment/, @@ -157,10 +164,10 @@ describe('splitEncapsulatedFrames', () => { [ 'an offset table that skips the first fragment', concat( - pixelItem(Uint8Array.from([13, 0, 0, 0, 26, 0, 0, 0])), - pixelItem(jpeg(1)), - pixelItem(jpeg(2)), - pixelItem(jpeg(3)), + sequenceItem(Uint8Array.from([13, 0, 0, 0, 26, 0, 0, 0])), + sequenceItem(jpeg(1)), + sequenceItem(jpeg(2)), + sequenceItem(jpeg(3)), DELIMITER ), /^Malformed encapsulated Pixel Data: Basic Offset Table entry 0 \(13\) skips the first fragment$/, @@ -168,7 +175,7 @@ describe('splitEncapsulatedFrames', () => { ['no offset table item', DELIMITER, /no Basic Offset Table/], [ 'no fragments', - concat(pixelItem(new Uint8Array()), DELIMITER), + concat(sequenceItem(new Uint8Array()), DELIMITER), /no fragments/, ], ])('rejects %s', (_name, value, error) => { diff --git a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts index 2ac8379ee..89aa025c7 100644 --- a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts +++ b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest'; import { indexFrames } from '../frameIndex'; -import { fromBlob } from '../../source/byteSource'; import { EXPLICIT_BE, EXPLICIT_LE, @@ -50,34 +49,37 @@ describe('indexFrames', () => { ); it.each([ - ['encapsulated', { transferSyntaxUid: '1.2.840.10008.1.2.4.50' }], - ['truncated', { extra: [{ tag: 0x00280008, vr: 'IS', value: '9' }] }], - ['invalid-shape', { extra: [{ tag: 0x00280008, vr: 'IS', value: '0' }] }], - ] as const)('reports %s Pixel Data as unindexed', async (reason, options) => { - const { instance } = await pixelInstance(options); - expect(indexFrames(instance)).toMatchObject({ kind: 'unindexed', reason }); - }); - - it('reports a file cut short after its header as truncated', async () => { - const { bytes, instance } = await pixelInstance({ - rows: 2, - columns: 3, - frames: 4, - words, - }); - const cut = fromBlob(new Blob([bytes.subarray(0, bytes.length - 12)])); - - expect(indexFrames({ ...instance, source: cut })).toMatchObject({ - kind: 'unindexed', - reason: 'truncated', - }); - }); + [ + 'encapsulated', + { transferSyntaxUid: '1.2.840.10008.1.2.4.50' }, + /not indexable without a codec/, + ], + [ + 'truncated', + { extra: [{ tag: 0x00280008, vr: 'IS', value: '9' }] }, + /Pixel Data holds 30 bytes; its frames need 270/, + ], + [ + 'misshapen', + { extra: [{ tag: 0x00280008, vr: 'IS', value: '0' }] }, + /Number of Frames is unusable/, + ], + ] as const)( + 'reports %s Pixel Data as unindexed', + async (_name, options, detail) => { + const { instance } = await pixelInstance(options); + expect(indexFrames(instance)).toEqual({ + kind: 'unindexed', + detail: expect.stringMatching(detail), + }); + } + ); it('reports samples packed across bytes as unindexed', async () => { const { instance } = await pixelInstance(); - expect(indexFrames(withNumber(instance, '00280100', 1))).toMatchObject({ + expect(indexFrames(withNumber(instance, '00280100', 1))).toEqual({ kind: 'unindexed', - reason: 'packed-bits', + detail: 'Bits Allocated 1 packs samples across bytes', }); }); @@ -91,6 +93,9 @@ describe('indexFrames', () => { transferSyntaxUid: EXPLICIT_LE, pixelData: null, }) - ).toMatchObject({ kind: 'unindexed', reason: 'no-pixel-data' }); + ).toEqual({ + kind: 'unindexed', + detail: 'The header locates no Pixel Data', + }); }); }); diff --git a/packages/dicom/core/pixels/decoderTable.ts b/packages/dicom/core/pixels/decoderTable.ts index fee95ac7b..9ebf1a817 100644 --- a/packages/dicom/core/pixels/decoderTable.ts +++ b/packages/dicom/core/pixels/decoderTable.ts @@ -1,4 +1,10 @@ import type { Instance } from '../instance/readInstance'; +import { + DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN, + EXPLICIT_VR_BIG_ENDIAN, + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, +} from '../metadata/dicomLayout'; import type { VolumeBufferConstructor } from '../volume/pixelFormat'; import { nativeFrameDecoder } from './nativeFrame'; import type { DecodeUnit, PixelDecoder } from './pixelDecoder'; @@ -23,10 +29,10 @@ type Codec = 'native' | 'gdcm' | 'none'; // prettier-ignore const SYNTAXES: Array<[string, string, Codec]> = [ - ['1.2.840.10008.1.2', 'Implicit VR Little Endian', 'native'], - ['1.2.840.10008.1.2.1', 'Explicit VR Little Endian', 'native'], - ['1.2.840.10008.1.2.2', 'Explicit VR Big Endian', 'native'], - ['1.2.840.10008.1.2.1.99', 'Deflated Explicit VR Little Endian', 'gdcm'], + [IMPLICIT_VR_LITTLE_ENDIAN, 'Implicit VR Little Endian', 'native'], + [EXPLICIT_VR_LITTLE_ENDIAN, 'Explicit VR Little Endian', 'native'], + [EXPLICIT_VR_BIG_ENDIAN, 'Explicit VR Big Endian', 'native'], + [DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN, 'Deflated Explicit VR Little Endian', 'gdcm'], ['1.2.840.10008.1.2.4.50', 'JPEG Baseline', 'gdcm'], ['1.2.840.10008.1.2.4.51', 'JPEG Extended', 'gdcm'], ['1.2.840.10008.1.2.4.57', 'JPEG Lossless', 'gdcm'], diff --git a/packages/dicom/core/pixels/encapsulatedFrames.ts b/packages/dicom/core/pixels/encapsulatedFrames.ts index ac77126e5..ecca72ad5 100644 --- a/packages/dicom/core/pixels/encapsulatedFrames.ts +++ b/packages/dicom/core/pixels/encapsulatedFrames.ts @@ -1,8 +1,9 @@ +import { UNDEFINED_LENGTH } from '../metadata/dicomLayout'; + const ITEM = 0xe000; const SEQUENCE_DELIMITER = 0xe0dd; const ITEM_GROUP = 0xfffe; const ITEM_HEAD_LENGTH = 8; -const UNDEFINED_LENGTH = 0xffffffff; type Fragment = Readonly<{ /** Offset of the item tag from the first fragment item, as offset tables count. */ diff --git a/packages/dicom/core/pixels/frameIndex.ts b/packages/dicom/core/pixels/frameIndex.ts index e0626080a..7c9c03ae9 100644 --- a/packages/dicom/core/pixels/frameIndex.ts +++ b/packages/dicom/core/pixels/frameIndex.ts @@ -2,13 +2,14 @@ import type { Instance } from '../instance/readInstance'; import type { ByteRange } from '../source/byteSource'; import { getDatasetTag } from '../metadata/datasetAccess'; import { + DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN, + EXPLICIT_VR_BIG_ENDIAN, EXPLICIT_VR_LITTLE_ENDIAN, IMPLICIT_VR_LITTLE_ENDIAN, } from '../metadata/dicomLayout'; +import { Tags } from '../metadata/dicomTags'; import { numberOr } from '../utils'; - -export const EXPLICIT_VR_BIG_ENDIAN = '1.2.840.10008.1.2.2'; -export const DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN = '1.2.840.10008.1.2.1.99'; +import { frameCount } from './pixelDecoder'; /** Transfer syntaxes whose Pixel Data is a plain run of fixed-size frames. */ const NATIVE_ENCODINGS: ReadonlyMap = @@ -18,101 +19,69 @@ const NATIVE_ENCODINGS: ReadonlyMap = [EXPLICIT_VR_BIG_ENDIAN, { littleEndian: false }], ]); -type UnindexedReason = - | 'no-pixel-data' - | 'deflated' - | 'encapsulated' - | 'packed-bits' - | 'invalid-shape' - | 'truncated'; - -/** - * Where each frame's bytes live. Only native encodings are indexed today; an - * encapsulated index (offset tables, then a fragment scan) would add an - * `encoding: 'encapsulated'` variant whose frames list fragment ranges. - */ +/** Where each frame's bytes live, for native encodings. */ type FrameIndex = | Readonly<{ kind: 'indexed'; - encoding: 'native'; littleEndian: boolean; frameLength: number; frames: readonly ByteRange[]; }> - | Readonly<{ kind: 'unindexed'; reason: UnindexedReason; detail: string }>; + | Readonly<{ kind: 'unindexed'; detail: string }>; -const unindexed = (reason: UnindexedReason, detail: string): FrameIndex => ({ +const unindexed = (detail: string): FrameIndex => ({ kind: 'unindexed', - reason, detail, }); -const shapeOf = (instance: Instance) => { - const valueOf = (tag: string) => - numberOr(getDatasetTag(instance.dataset, tag), NaN); +/** The header's frame shape, NaN where a required value is unreadable. */ +export const shapeOf = ({ dataset }: Instance) => { + const valueOf = (tag: string) => numberOr(getDatasetTag(dataset, tag), NaN); return { - rows: valueOf('00280010'), - columns: valueOf('00280011'), - samplesPerPixel: numberOr(getDatasetTag(instance.dataset, '00280002'), 1), - bitsAllocated: valueOf('00280100'), - frames: numberOr(getDatasetTag(instance.dataset, '00280008'), 1), + rows: valueOf(Tags.Rows), + columns: valueOf(Tags.Columns), + samplesPerPixel: numberOr(getDatasetTag(dataset, Tags.SamplesPerPixel), 1), + bitsAllocated: valueOf(Tags.BitsAllocated), + frames: frameCount(dataset), }; }; const positiveInteger = (value: number) => Number.isSafeInteger(value) && value > 0; -// A file cut short after its header would otherwise fail once per frame. -const truncation = ( - needed: number, - held: number, - end: number, - size: number | undefined -) => { - if (needed > held) - return `Pixel Data holds ${held} bytes; its frames need ${needed}`; - return size !== undefined && end > size - ? `The file holds ${size} bytes; its frames end at byte ${end}` - : null; -}; - /** Byte ranges of every frame, from the header alone. */ export function indexFrames(instance: Instance): FrameIndex { const { pixelData, transferSyntaxUid } = instance; if (!pixelData || !transferSyntaxUid) - return unindexed('no-pixel-data', 'The header locates no Pixel Data'); + return unindexed('The header locates no Pixel Data'); if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) - return unindexed('deflated', 'The whole data set is deflated'); + return unindexed('The whole data set is deflated'); const encoding = NATIVE_ENCODINGS.get(transferSyntaxUid); - if (!encoding || pixelData.length === null) + if (!encoding) return unindexed( - 'encapsulated', `Transfer syntax ${transferSyntaxUid} is not indexable without a codec` ); + if (pixelData.length === null) + return unindexed('Pixel Data has undefined length'); const { rows, columns, samplesPerPixel, bitsAllocated, frames } = shapeOf(instance); if (![rows, columns, samplesPerPixel, frames].every(positiveInteger)) return unindexed( - 'invalid-shape', 'Rows, Columns, Samples per Pixel or Number of Frames is unusable' ); if (!positiveInteger(bitsAllocated) || bitsAllocated % 8 !== 0) return unindexed( - 'packed-bits', `Bits Allocated ${bitsAllocated} packs samples across bytes` ); const frameLength = rows * columns * samplesPerPixel * (bitsAllocated / 8); const needed = frameLength * frames; - const truncated = truncation( - needed, - pixelData.length, - pixelData.valueOffset + needed, - instance.source.size - ); - if (truncated) return unindexed('truncated', truncated); + // Frames past the element's end would read whatever follows it. + if (needed > pixelData.length) + return unindexed( + `Pixel Data holds ${pixelData.length} bytes; its frames need ${needed}` + ); return { kind: 'indexed', - encoding: 'native', littleEndian: encoding.littleEndian, frameLength, frames: Array.from({ length: frames }, (_, frame) => { diff --git a/packages/dicom/core/pixels/nativeFrame.ts b/packages/dicom/core/pixels/nativeFrame.ts index de8c73dfb..c77a46f19 100644 --- a/packages/dicom/core/pixels/nativeFrame.ts +++ b/packages/dicom/core/pixels/nativeFrame.ts @@ -1,13 +1,14 @@ import type { Instance } from '../instance/readInstance'; import type { DicomDataset } from '../metadata/dicomDataset'; import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; import { hasUniformModalityRescale, readModalityRescale, } from '../metadata/modalityRescale'; import { numberOr, trimDicomPadding } from '../utils'; import type { VolumeBufferConstructor } from '../volume/pixelFormat'; -import { indexFrames } from './frameIndex'; +import { indexFrames, shapeOf } from './frameIndex'; import type { PixelDecoder } from './pixelDecoder'; /** What decides how one native frame's bytes become samples. */ @@ -43,20 +44,19 @@ function readNativePixelFormat( littleEndian: boolean ): NativePixelFormat { const { dataset } = instance; - const { rescaleSlope, rescaleIntercept } = readModalityRescale(dataset); + const { rows, columns, samplesPerPixel, bitsAllocated } = shapeOf(instance); return { - rows: number(dataset, '00280010'), - columns: number(dataset, '00280011'), - samplesPerPixel: numberOr(getDatasetTag(dataset, '00280002'), 1), - photometricInterpretation: text(dataset, '00280004'), - planar: number(dataset, '00280006') === 1, - bitsAllocated: number(dataset, '00280100'), - bitsStored: number(dataset, '00280101'), + rows, + columns, + samplesPerPixel, + photometricInterpretation: text(dataset, Tags.PhotometricInterpretation), + planar: number(dataset, Tags.PlanarConfiguration) === 1, + bitsAllocated, + bitsStored: number(dataset, Tags.BitsStored), highBit: number(dataset, '00280102'), - signed: number(dataset, '00280103') === 1, + signed: number(dataset, Tags.PixelRepresentation) === 1, littleEndian, - rescaleSlope, - rescaleIntercept, + ...readModalityRescale(dataset), }; } @@ -108,8 +108,6 @@ const declineByteOrder = ({ const declineRescale = (format: NativePixelFormat) => { const { rescaleSlope: slope, rescaleIntercept: intercept } = format; - if (!Number.isFinite(slope) || !Number.isFinite(intercept)) - return 'Non-numeric modality rescale'; const rgb = format.samplesPerPixel === 3; const plain = format.bitsAllocated === 8 && !format.signed; return rgb && !(plain && slope === 1 && intercept === 0) @@ -154,6 +152,9 @@ export function nativeCapability( return reason ? { kind: 'declined', reason } : { kind: 'native', format }; } +const PLATFORM_LITTLE_ENDIAN = + new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + /** Stored words as unsigned integers, viewed in place where alignment allows. */ function storedWords( bytes: Uint8Array, @@ -164,9 +165,7 @@ function storedWords( if (bitsAllocated === 8) return bytes.subarray(0, count); const size = bitsAllocated / 8; const Words = bitsAllocated === 16 ? Uint16Array : Uint32Array; - const platformLittleEndian = - new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - if (littleEndian === platformLittleEndian && bytes.byteOffset % size === 0) + if (littleEndian === PLATFORM_LITTLE_ENDIAN && bytes.byteOffset % size === 0) return new Words(bytes.buffer as ArrayBuffer, bytes.byteOffset, count); const view = new DataView(bytes.buffer, bytes.byteOffset, count * size); const words = new Words(count); @@ -178,23 +177,6 @@ function storedWords( return words; } -/** Maps a stored word to its rescaled value. */ -function storedValue(format: NativePixelFormat) { - const { bitsStored, bitsAllocated, signed } = format; - const { rescaleSlope: slope, rescaleIntercept: intercept } = format; - // Bits Stored is below 32 when masking, so the bitwise result is nonnegative. - const mask = bitsStored < bitsAllocated ? 2 ** bitsStored - 1 : -1; - const signBit = signed ? 2 ** (bitsStored - 1) : Infinity; - const wrap = 2 ** bitsStored; - const stored = (word: number) => { - const value = mask === -1 ? word : word & mask; - return value >= signBit ? value - wrap : value; - }; - return slope === 1 && intercept === 0 - ? stored - : (word: number) => stored(word) * slope + intercept; -} - /** * Decodes one native frame into interleaved, modality-rescaled samples of the * given element type. `range` is each component's [min, max] before the @@ -206,35 +188,36 @@ export function decodeNativeFrame( Target: VolumeBufferConstructor ) { const { rows, columns, samplesPerPixel: components, planar } = format; + const { bitsStored, bitsAllocated, signed } = format; + const { rescaleSlope: slope, rescaleIntercept: intercept } = format; const pixels = rows * columns; const count = pixels * components; - const frameLength = count * (format.bitsAllocated / 8); + const frameLength = count * (bitsAllocated / 8); if (bytes.length < frameLength) throw new Error( `A frame needs ${frameLength} bytes of Pixel Data; ${bytes.length} were read` ); const words = storedWords(bytes, format, count); - const valueOf = storedValue(format); const samples = new Target(count); - const min = new Array(components).fill(Infinity); - const max = new Array(components).fill(-Infinity); - for (let component = 0; component < components; component += 1) { + const mask = bitsStored < bitsAllocated ? 2 ** bitsStored - 1 : 0xffffffff; + const signBit = signed ? 2 ** (bitsStored - 1) : Infinity; + const wrap = 2 ** bitsStored; + const range = Array.from({ length: components }, (_, component) => { + const first = planar ? component * pixels : component; + const stride = planar ? 1 : components; + let low = Infinity; + let high = -Infinity; for (let pixel = 0; pixel < pixels; pixel += 1) { - const source = planar - ? component * pixels + pixel - : pixel * components + component; - const value = valueOf(words[source]); + // The unsigned shift undoes the sign a full 32 bit mask leaves. + const word = (words[first + pixel * stride] & mask) >>> 0; + const value = (word >= signBit ? word - wrap : word) * slope + intercept; samples[pixel * components + component] = value; - if (value < min[component]) min[component] = value; - if (value > max[component]) max[component] = value; + if (value < low) low = value; + if (value > high) high = value; } - } - return { - samples, - range: min.map( - (low, component) => [low, max[component]] as [number, number] - ), - }; + return [low, high] as [number, number]; + }); + return { samples, range }; } /** Decodes each frame of an instance it reproduces exactly from its own ranged read. */ diff --git a/packages/dicom/core/pixels/pixelDecoder.ts b/packages/dicom/core/pixels/pixelDecoder.ts index 76ee33327..e9a7b40d5 100644 --- a/packages/dicom/core/pixels/pixelDecoder.ts +++ b/packages/dicom/core/pixels/pixelDecoder.ts @@ -1,6 +1,8 @@ import type { Instance } from '../instance/readInstance'; import type { ByteRange } from '../source/byteSource'; +import type { DicomDataset } from '../metadata/dicomDataset'; import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; import { numberOr, type Awaitable } from '../utils'; import type { VolumeBufferConstructor } from '../volume/pixelFormat'; @@ -23,7 +25,10 @@ export type DecodeUnit = Readonly<{ frames: number; /** Bytes of the instance's source to read; null for all of them. */ range: ByteRange | null; - /** The returned pixels belong to the caller; `bytes` may be transferred away. */ + /** + * The returned pixels belong to the caller. `bytes` may view a buffer other + * units share, so transfer it only when it spans its whole buffer. + */ decode: (bytes: Uint8Array, signal: AbortSignal) => Awaitable; }>; @@ -44,8 +49,8 @@ export type WholeInstanceDecode = ( signal: AbortSignal ) => Awaitable; -export const frameCount = (instance: Instance) => - numberOr(getDatasetTag(instance.dataset, '00280008'), 1); +export const frameCount = (dataset: DicomDataset) => + numberOr(getDatasetTag(dataset, Tags.NumberOfFrames), 1); /** A decoder that reads and decodes every instance whole. */ export const wholeInstanceDecoder = ( @@ -56,7 +61,7 @@ export const wholeInstanceDecoder = ( plan: (instance) => [ { firstFrame: 0, - frames: frameCount(instance), + frames: frameCount(instance.dataset), range: null, decode: (bytes, signal) => decode({ instance, bytes }, signal), }, diff --git a/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts b/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts deleted file mode 100644 index 63ed4cf6d..000000000 --- a/packages/dicom/core/runtime/__tests__/decoderCalibration.spec.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { createGdcmDecoder } from '../gdcmDecoder'; -import { readDicomDataset } from '../../metadata/dicomDataset'; -import { instanceFor } from '@/tests/dicomDataset'; -import type { DecodeUnit } from '../../pixels/pixelDecoder'; -import { enhancedFixtureBytes } from '@/tests/fixtures/dicom-pages/enhancedFixtures'; - -const assets = { - pipelineWorkerUrl: '/unused-worker.js', - imageIOUrl: '/unused-image-io', -}; - -describe('Default DICOM decoder calibration', () => { - it('rejects varying frame transforms before invoking GDCM', async () => { - const bytes = enhancedFixtureBytes({ - pixelValues: [2, 2], - transforms: [ - [1, 0], - [2, 0], - ], - }); - const runs: Uint8Array[] = []; - const gdcm = createGdcmDecoder(assets, 1, () => ({ - run: async (_name: string, data: Uint8Array) => { - runs.push(data); - throw new Error('GDCM ran'); - }, - reset: () => {}, - })); - const instance = instanceFor(readDicomDataset(bytes)); - const [unit] = gdcm.decoder.plan(instance, Float32Array) as DecodeUnit[]; - - await expect( - Promise.resolve(unit.decode(bytes, new AbortController().signal)) - ).rejects.toThrow('differing modality rescale'); - expect(runs).toEqual([]); - gdcm.dispose(new Error('done')); - }); -}); diff --git a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts index 333f294c9..afcc9b304 100644 --- a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts +++ b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts @@ -4,10 +4,11 @@ import { defaultDecodeConcurrency, } from '../createDicomRuntime'; import { createGdcmDecoder, type GdcmLane } from '../gdcmDecoder'; -import { defer } from '../../utils'; import { getDatasetTag } from '../../metadata/datasetAccess'; +import { readDicomDataset } from '../../metadata/dicomDataset'; import { fromBlob } from '../../source/byteSource'; import { instanceFor } from '@/tests/dicomDataset'; +import { enhancedFixtureBytes } from '@/tests/fixtures/dicom-pages/enhancedFixtures'; import { sliceDataset } from '../../collections/__tests__/sliceFixture'; import type { DecodedPixels, DecodeUnit } from '../../pixels/pixelDecoder'; import { syntheticSlice } from '@/tests/dicomSourceFixtures'; @@ -27,7 +28,7 @@ const signal = () => new AbortController().signal; function controlledLanes() { let active = 0; let peak = 0; - const gate = defer(); + const gate = Promise.withResolvers(); const runs: Array<() => void> = []; const resets: unknown[] = []; const createLane = (): GdcmLane => { @@ -145,4 +146,20 @@ describe('DICOM runtime', () => { 'GDCM decoding needs createDicomRuntime({ assets })' ); }); + + it('declines for GDCM, from the header, an instance whose frames differ in modality rescale', () => { + const bytes = enhancedFixtureBytes({ + pixelValues: [2, 2], + transforms: [ + [1, 0], + [2, 0], + ], + }); + const gdcm = createGdcmDecoder(assets, 1, controlledLanes().createLane); + + expect( + gdcm.decoder.plan(instanceFor(readDicomDataset(bytes)), Float32Array) + ).toEqual({ declined: 'Frames with differing modality rescale' }); + gdcm.dispose(new Error('done')); + }); }); diff --git a/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts b/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts similarity index 78% rename from packages/dicom/core/metadata/__tests__/metadataReader.spec.ts rename to packages/dicom/core/runtime/__tests__/metadataReader.spec.ts index 69d62820f..a7287edac 100644 --- a/packages/dicom/core/metadata/__tests__/metadataReader.spec.ts +++ b/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { readDicomDataset } from '../dicomDataset'; -import { createMetadataReader } from '../../runtime/metadataReader'; -const readDicomDatasetOffThread = createMetadataReader().read; +import { readDicomDataset } from '../../metadata/dicomDataset'; +import { createMetadataReader } from '../metadataReader'; import { buildSlice } from '@/tests/specs/dicomElementFixtures'; +import { rawElement } from '@/tests/specs/syntheticDicom'; + +const readDicomDatasetOffThread = createMetadataReader().read; // The test DOM has no Worker, so this covers the in-place path only; the // worker path is the same reader behind a message. @@ -15,6 +17,19 @@ describe('readDicomDatasetOffThread', () => { ); }); + it('returns no private element, so none crosses to the caller', async () => { + const bytes = buildSlice({ + extraElements: [ + rawElement(0x0029, 0x0010, 'LO', new TextEncoder().encode('VENDOR')), + rawElement(0x0029, 0x1010, 'OB', new Uint8Array(64)), + ], + }); + + expect(await readDicomDatasetOffThread(bytes)).toEqual( + readDicomDataset(buildSlice()) + ); + }); + it('reads a view that does not own its buffer', async () => { const whole = buildSlice(); const padded = new Uint8Array(whole.length + 3); diff --git a/packages/dicom/core/runtime/__tests__/requestPool.spec.ts b/packages/dicom/core/runtime/__tests__/requestPool.spec.ts index b5693228c..8ef50ca45 100644 --- a/packages/dicom/core/runtime/__tests__/requestPool.spec.ts +++ b/packages/dicom/core/runtime/__tests__/requestPool.spec.ts @@ -1,10 +1,5 @@ import { RequestPool } from '../requestPool'; import { describe, it, expect } from 'vitest'; -import { defer } from '../../utils'; - -const neverResolvingFetch = async () => { - return new Promise(() => {}); -}; const abortableFetch = async ( _input: RequestInfo | URL, @@ -26,11 +21,15 @@ const abortableFetch = async ( describe('requestPool', () => { it('should not have more active requests than the pool size', () => { const N = 4; - const pool = new RequestPool(N, neverResolvingFetch); + let started = 0; + const pool = new RequestPool(N, () => { + started += 1; + return new Promise(() => {}); + }); for (let i = 0; i < 10; i++) { pool.fetch('http://localhost/url'); } - expect(pool.activeConnections).to.equal(N); + expect(started).to.equal(N); }); it('should support removal of requests via an AbortController', async () => { @@ -57,7 +56,7 @@ describe('requestPool', () => { }); it('settles queued requests immediately on cancellation or disposal', async () => { - const fetchStarted = defer(); + const fetchStarted = Promise.withResolvers(); const pool = new RequestPool( 1, (_request, init) => @@ -124,21 +123,3 @@ describe('requestPool', () => { } ); }); - -it('imports a remote resource without AbortSignal.any', async () => { - const descriptor = Object.getOwnPropertyDescriptor(AbortSignal, 'any'); - Object.defineProperty(AbortSignal, 'any', { - configurable: true, - value: undefined, - }); - const pool = new RequestPool(1, async () => new Response('resource')); - try { - expect( - await (await pool.fetch('https://example.test/resource')).text() - ).toBe('resource'); - } finally { - pool.dispose(); - if (descriptor) Object.defineProperty(AbortSignal, 'any', descriptor); - else Reflect.deleteProperty(AbortSignal, 'any'); - } -}); diff --git a/packages/dicom/core/runtime/createDicomRuntime.ts b/packages/dicom/core/runtime/createDicomRuntime.ts index 8722b309d..9cc1316ef 100644 --- a/packages/dicom/core/runtime/createDicomRuntime.ts +++ b/packages/dicom/core/runtime/createDicomRuntime.ts @@ -63,32 +63,27 @@ export function createDicomRuntime( createGdcmLane ); - const withLifetime = async ( - signal: AbortSignal, - run: (linked: AbortSignal) => Promise - ) => { + const read = async (source: ByteSource, signal: AbortSignal) => { const { controller, release } = linkedController(signal, lifetime.signal); try { - return await untilAborted(run(controller.signal), controller.signal); + return await untilAborted( + readInstance(source, controller.signal, { + readDataset: metadata.read, + imageImportPolicy: options.imageImportPolicy, + }), + controller.signal + ); } finally { release(); } }; - const read = (source: ByteSource, signal: AbortSignal) => - withLifetime(signal, (linked) => - readInstance(source, linked, { - readDataset: metadata.read, - imageImportPolicy: options.imageImportPolicy, - }) - ); - const dispose = () => { if (lifetime.signal.aborted) return; const reason = abortError('DICOM runtime disposed'); lifetime.abort(reason); - requests.dispose(); - metadata.dispose(); + requests.dispose(reason); + metadata.dispose(reason); gdcm.dispose(reason); }; diff --git a/packages/dicom/core/runtime/gdcmDecoder.ts b/packages/dicom/core/runtime/gdcmDecoder.ts index 783d9c099..7eaa0042f 100644 --- a/packages/dicom/core/runtime/gdcmDecoder.ts +++ b/packages/dicom/core/runtime/gdcmDecoder.ts @@ -1,10 +1,10 @@ import type { Image, runPipeline, TypedArray } from 'itk-wasm'; -import type { Instance } from '../instance/readInstance'; -import { assertUniformModalityRescale } from '../metadata/modalityRescale'; +import { hasUniformModalityRescale } from '../metadata/modalityRescale'; import { linkedController, untilAborted } from '../utils'; import { wholeInstanceDecoder, type DecodedPixels, + type PixelDecoder, } from '../pixels/pixelDecoder'; export type DicomAssets = { pipelineWorkerUrl: string; imageIOUrl: string }; @@ -154,7 +154,6 @@ export function createGdcmDecoder( const decodeOn = async ( index: number, - instance: Instance, bytes: Uint8Array, signal: AbortSignal ) => { @@ -162,7 +161,6 @@ export function createGdcmDecoder( const lane = lanes[index]; if (!lane) throw new Error('GDCM decoding needs createDicomRuntime({ assets })'); - assertUniformModalityRescale(instance.dataset); // GDCM cannot be interrupted, so an abort terminates the worker. const stop = () => lane.reset(signal.reason); signal.addEventListener('abort', stop, { once: true }); @@ -173,26 +171,32 @@ export function createGdcmDecoder( } }; - const decoder = wholeInstanceDecoder( - 'GDCM', - async ({ instance, bytes }, signal) => { - 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, instance, bytes, linked); - } finally { - slots.release(index); - } - }; + const whole = wholeInstanceDecoder('GDCM', async ({ bytes }, signal) => { + const { controller, release } = linkedController(signal, lifetime.signal); + const linked = controller.signal; + const pooled = async () => { + const index = await slots.acquire(linked); try { - return await untilAborted(pooled(), linked); + return await decodeOn(index, bytes, linked); } finally { - release(); + slots.release(index); } + }; + try { + return await untilAborted(pooled(), linked); + } finally { + release(); } - ); + }); + + // GDCM applies one transform to an instance, so its frames must agree. + const decoder: PixelDecoder = { + ...whole, + plan: (instance, target) => + hasUniformModalityRescale(instance.dataset) + ? whole.plan(instance, target) + : { declined: 'Frames with differing modality rescale' }, + }; const dispose = (reason: unknown) => { lifetime.abort(reason); diff --git a/packages/dicom/core/runtime/metadataReader.ts b/packages/dicom/core/runtime/metadataReader.ts index 7b060352d..353ef342c 100644 --- a/packages/dicom/core/runtime/metadataReader.ts +++ b/packages/dicom/core/runtime/metadataReader.ts @@ -1,24 +1,23 @@ import * as Comlink from 'comlink'; -import { readDicomDataset, type DicomDataset } from '../metadata/dicomDataset'; +import { readPublicDataset, type DicomDataset } from '../metadata/dicomDataset'; import type { DicomDatasetWorker } from '../metadata/readDicomDataset.worker'; +import { abortError } from '../utils'; export type MetadataReaderOptions = { metadataWorkerFactory?: () => Worker; - metadataConcurrency?: number; }; +const WORKER_COUNT = 2; + /** Owns parser workers. Input bytes are copied before transfer; the caller keeps its buffer. */ export function createMetadataReader(options: MetadataReaderOptions = {}) { - const count = options.metadataConcurrency ?? 2; - if (!Number.isInteger(count) || count < 1) - throw new Error('Metadata concurrency must be a positive integer'); const workers: Array<{ worker: Worker; remote: Comlink.Remote; }> = []; const pending = new Set<(reason: unknown) => void>(); let next = 0; - let disposed = false; + let disposal: unknown; const createWorker = options.metadataWorkerFactory ?? (() => @@ -36,11 +35,10 @@ export function createMetadataReader(options: MetadataReaderOptions = {}) { workers.length = 0; }; const read = async (bytes: Uint8Array): Promise => { - if (disposed) - throw new DOMException('Metadata reader disposed', 'AbortError'); + if (disposal) throw disposal; if (typeof Worker === 'undefined' && !options.metadataWorkerFactory) - return readDicomDataset(bytes); - if (workers.length < count) { + return readPublicDataset(bytes); + if (workers.length < WORKER_COUNT) { const worker = createWorker(); const fail = (message: string) => { if (workers.some((entry) => entry.worker === worker)) @@ -66,15 +64,17 @@ export function createMetadataReader(options: MetadataReaderOptions = {}) { return new Promise((resolve, reject) => { pending.add(reject); remote - .readDicomDataset(Comlink.transfer(owned, [owned.buffer])) + .readPublicDataset(Comlink.transfer(owned, [owned.buffer])) .then(resolve, reject) .finally(() => pending.delete(reject)); }); }; - const dispose = () => { - if (disposed) return; - disposed = true; - resetWorkers(new DOMException('Metadata reader disposed', 'AbortError')); + const dispose = ( + reason: unknown = abortError('Metadata reader disposed') + ) => { + if (disposal) return; + disposal = reason; + resetWorkers(reason); }; return { read, dispose }; } diff --git a/packages/dicom/core/runtime/requestPool.ts b/packages/dicom/core/runtime/requestPool.ts index 896cd263d..167945829 100644 --- a/packages/dicom/core/runtime/requestPool.ts +++ b/packages/dicom/core/runtime/requestPool.ts @@ -1,9 +1,10 @@ -import { Deferred, defer } from '../utils'; +import { abortError } from '../utils'; type FetchRequest = { request: RequestInfo | URL; init?: RequestInit; - deferred: Deferred; + resolve: (response: Response) => void; + reject: (reason?: unknown) => void; controller: AbortController; cleanup: () => void; }; @@ -12,7 +13,6 @@ type FetchRequest = { export class RequestPool { private queue: FetchRequest[] = []; private inflight = new Set(); - private disposed = false; private lifetime = new AbortController(); constructor( @@ -24,62 +24,59 @@ export class RequestPool { throw new Error('Request concurrency must be a positive integer'); } - get activeConnections() { - return this.inflight.size; - } - fetch = (request: RequestInfo | URL, init?: RequestInit) => { - if (this.disposed) - return Promise.reject( - new DOMException('Request pool disposed', 'AbortError') - ); - const deferred = defer(); + const disposal = this.lifetime.signal; + if (disposal.aborted) return Promise.reject(disposal.reason); + // Promise.withResolvers is newer than the browsers the app supports. + let resolve!: FetchRequest['resolve']; + let reject!: FetchRequest['reject']; + const response = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); const controller = new AbortController(); const sourceSignal = init?.signal ?? (request instanceof Request ? request.signal : undefined); const abort = () => { controller.abort(sourceSignal?.reason); - deferred.reject(sourceSignal?.reason); + reject(sourceSignal?.reason); this.queue = this.queue.filter((entry) => entry !== queued); }; - const onDispose = () => controller.abort(this.lifetime.signal.reason); + const onDispose = () => { + controller.abort(disposal.reason); + reject(disposal.reason); + }; const queued: FetchRequest = { request, init, - deferred, + resolve, + reject, controller, cleanup: () => { sourceSignal?.removeEventListener('abort', abort); - this.lifetime.signal.removeEventListener('abort', onDispose); + disposal.removeEventListener('abort', onDispose); }, }; if (sourceSignal?.aborted) { - deferred.reject(sourceSignal.reason); - return deferred.promise; + reject(sourceSignal.reason); + return response; } sourceSignal?.addEventListener('abort', abort, { once: true }); - this.lifetime.signal.addEventListener('abort', onDispose, { once: true }); + disposal.addEventListener('abort', onDispose, { once: true }); controller.signal.addEventListener('abort', queued.cleanup, { once: true }); this.queue.push(queued); this.processQueue(); - return deferred.promise; + return response; }; - dispose() { - this.disposed = true; - const error = new DOMException('Request pool disposed', 'AbortError'); - this.lifetime.abort(error); - [...this.queue, ...this.inflight].forEach((request) => { - request.controller.abort(error); - request.deferred.reject(error); - request.cleanup(); - }); + dispose(reason: unknown = abortError('Request pool disposed')) { + this.lifetime.abort(reason); this.queue = []; } private processQueue() { while ( - !this.disposed && + !this.lifetime.signal.aborted && this.inflight.size < this.poolSize && this.queue.length ) { @@ -97,11 +94,11 @@ export class RequestPool { }); if (request.controller.signal.aborted) { response.body?.cancel().catch(() => {}); - request.deferred.reject(request.controller.signal.reason); - } else request.deferred.resolve(response); + request.reject(request.controller.signal.reason); + } else request.resolve(response); } catch (error) { request.cleanup(); - request.deferred.reject(error); + request.reject(error); } finally { this.inflight.delete(request); this.processQueue(); diff --git a/packages/dicom/core/source/__tests__/byteSource.spec.ts b/packages/dicom/core/source/__tests__/byteSource.spec.ts index ea0dd040f..44789b7ec 100644 --- a/packages/dicom/core/source/__tests__/byteSource.spec.ts +++ b/packages/dicom/core/source/__tests__/byteSource.spec.ts @@ -20,21 +20,27 @@ type ServerOptions = { honorRange?: boolean; exposeContentRange?: boolean; status?: number; + /** Moves the start of the range the server answers away from the one asked. */ + startShift?: number; + contentRange?: string; }; /** A fetch that serves `bytes` in 64-byte chunks and records what it was asked. */ const server = (options: ServerOptions = {}) => { const { honorRange = true, exposeContentRange = true, status } = options; + const { startShift = 0, contentRange } = options; const requests: Array = []; const caches: Array = []; + const signals: Array = []; const bodies: Array<{ cancelled: boolean }> = []; const fetchFn: typeof fetch = async (_input, init) => { const range = new Headers(init?.headers).get('Range'); requests.push(range); caches.push(init?.cache); + signals.push(init?.signal); const match = range?.match(/^bytes=(\d+)-(\d*)$/); const partial = honorRange && match !== null && match !== undefined; - const start = partial ? Number(match[1]) : 0; + const start = partial ? Number(match[1]) + startShift : 0; const end = partial && match[2] ? Number(match[2]) + 1 : bytes.length; const body = { cancelled: false }; bodies.push(body); @@ -54,13 +60,16 @@ const server = (options: ServerOptions = {}) => { }); const headers = new Headers({ 'content-length': String(end - start) }); if (partial && exposeContentRange) - headers.set('content-range', `bytes ${start}-${end - 1}/${bytes.length}`); + headers.set( + 'content-range', + contentRange ?? `bytes ${start}-${end - 1}/${bytes.length}` + ); return new Response(stream, { status: status ?? (partial ? 206 : 200), headers, }); }; - return { fetch: fetchFn, requests, caches, bodies }; + return { fetch: fetchFn, requests, caches, bodies, signals }; }; const signal = () => new AbortController().signal; @@ -84,6 +93,28 @@ describe('blob byte source', () => { ); }); + it('hands a range with an end over whole and an open read in growing slices', async () => { + const large = new Blob([new Uint8Array(500 * 1024)]); + const chunkSizes = async (range?: ByteRange) => { + const reader = fromBlob(large).read(signal(), range).getReader(); + const sizes: number[] = []; + for (;;) { + const { done, value } = await reader.read(); + if (done) return sizes; + sizes.push(value.length); + } + }; + expect(await chunkSizes({ start: 1024, end: 401 * 1024 })).toEqual([ + 400 * 1024, + ]); + expect(await chunkSizes()).toEqual([ + 64 * 1024, + 128 * 1024, + 256 * 1024, + 52 * 1024, + ]); + }); + it('errors its stream once the signal aborts', async () => { const controller = new AbortController(); const stream = fromBlob(new Blob([bytes])).read(controller.signal); @@ -154,8 +185,40 @@ describe('URL byte source', () => { expect(http.requests).toHaveLength(2); }); + it('reads a range from a 206 that starts before it', async () => { + const http = server({ startShift: -50 }); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + expect( + await readStream(source.read(signal(), { start: 100, end: 300 })) + ).toEqual(expected({ start: 100, end: 300 })); + }); + + it.each([ + ['starts after the range asked', { startShift: 50 }, /starts too late/], + [ + 'carries an unreadable Content-Range', + { contentRange: 'bytes 100-' }, + /Invalid content-range/, + ], + ])('fails a 206 that %s', async (_name, options, message) => { + const http = server(options); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + await expect( + readStream(source.read(signal(), { start: 100, end: 300 })) + ).rejects.toThrow(message); + }); + + it('aborts its request once the body is read to the end', async () => { + const http = server(); + const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + await readStream(source.read(signal(), { start: 0, end: 10 })); + expect(http.signals[0]?.aborted).toBe(true); + }); + it.each([ - [404, /could not be found/], + [401, /HTTP 401/], + [404, /HTTP 404/], + [500, /HTTP 500/], [416, /Range could not be satisfied/], ])('fails a %i response', async (status, message) => { const http = server({ status }); diff --git a/packages/dicom/core/source/byteSource.ts b/packages/dicom/core/source/byteSource.ts index 419e7472b..01f4d4f63 100644 --- a/packages/dicom/core/source/byteSource.ts +++ b/packages/dicom/core/source/byteSource.ts @@ -2,10 +2,8 @@ import { HTTP_STATUS_OK, HTTP_STATUS_PARTIAL_CONTENT, HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, - HttpNotFound, } from './httpCodes'; -import { linkedController } from '../utils'; -import { concatBytes } from '../utils'; +import { concatBytes, linkedController } from '../utils'; import { parseContentRangeHeader } from './parseContentRangeHeader'; /** Half-open byte interval; an absent end reads to the last byte. */ @@ -27,8 +25,8 @@ export type ByteSource = { export type RangeSupport = 'unknown' | 'honoured' | 'ignored'; -/** Read enough per pull that a header rarely needs a second slice. */ -const BLOB_CHUNK_SIZE = 64 * 1024; +/** Enough that a header rarely needs a second slice. */ +const OPEN_READ_FIRST_SLICE = 64 * 1024; const rangeLength = (range?: ByteRange) => range?.end === undefined ? Infinity : Math.max(0, range.end - range.start); @@ -38,6 +36,9 @@ export const fromBlob = (blob: Blob): ByteSource => ({ read: (signal, range) => { let offset = range?.start ?? 0; const end = Math.min(blob.size, offset + rangeLength(range)); + // Every slice costs a turn of the calling thread. A range with an end is + // wanted whole; an open read may stop early, so it starts small and doubles. + let step = range?.end === undefined ? OPEN_READ_FIRST_SLICE : end - offset; return new ReadableStream({ pull: async (controller) => { signal.throwIfAborted(); @@ -45,7 +46,8 @@ export const fromBlob = (blob: Blob): ByteSource => ({ controller.close(); return; } - const next = Math.min(end, offset + BLOB_CHUNK_SIZE); + const next = Math.min(end, offset + step); + step *= 2; const bytes = new Uint8Array( await blob.slice(offset, next).arrayBuffer() ); @@ -132,7 +134,7 @@ function assertReadableStatus(response: Response, url: string | URL) { response.body?.cancel().catch(() => {}); if (response.status === HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE) throw new Error('Range could not be satisfied'); - throw new HttpNotFound(url.toString()); + throw new Error(`HTTP ${response.status} for ${url}`); } /** @@ -182,7 +184,8 @@ export const fromUrl = ( stream.enqueue(value); return; } - release(); + // Abort is how a pooled fetch learns its body is done. + controller.abort(); stream.close(); }, cancel: async (reason) => { diff --git a/packages/dicom/core/source/httpCodes.ts b/packages/dicom/core/source/httpCodes.ts index 4a70c9eae..c395609a5 100644 --- a/packages/dicom/core/source/httpCodes.ts +++ b/packages/dicom/core/source/httpCodes.ts @@ -1,9 +1,3 @@ export const HTTP_STATUS_OK = 200; export const HTTP_STATUS_PARTIAL_CONTENT = 206; export const HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416; - -export class HttpNotFound extends Error { - constructor(url: string) { - super(`The following resource could not be found: ${url}`); - } -} diff --git a/packages/dicom/core/source/parseContentRangeHeader.ts b/packages/dicom/core/source/parseContentRangeHeader.ts index 4e798f127..fc26f9eab 100644 --- a/packages/dicom/core/source/parseContentRangeHeader.ts +++ b/packages/dicom/core/source/parseContentRangeHeader.ts @@ -7,13 +7,7 @@ export type ContentRange = | { type: 'unsatisfied-range'; length: number } | { type: 'range'; start: number; end: number; length: number | null }; -/** - * Parses a Content-Range header. - * - * Only supports bytes ranges. - * @param headerValue - * @returns - */ +/** Parses a Content-Range header. Only supports bytes ranges. */ export function parseContentRangeHeader( headerValue: string | null ): ContentRange { diff --git a/packages/dicom/core/utils.ts b/packages/dicom/core/utils.ts index 392900d2e..a7de0f0f9 100644 --- a/packages/dicom/core/utils.ts +++ b/packages/dicom/core/utils.ts @@ -1,35 +1,8 @@ -export type Maybe = T | null | undefined; export type Awaitable = T | Promise; /** Boundary padding accepted by numeric readers, without changing the stored text. */ export const trimDicomPadding = (value: string) => value.replace(/^[\s\0]+|[\s\0]+$/g, ''); -type PromiseResolveFunction = (value: T) => void; -type PromiseRejectFunction = (reason?: any) => void; -export type Deferred = { - promise: Promise; - resolve: PromiseResolveFunction; - reject: PromiseRejectFunction; -}; - -export function defer(): Deferred { - let innerResolve: PromiseResolveFunction | null = null; - let innerReject: PromiseRejectFunction | null = null; - - const resolve = (value: T) => { - if (innerResolve) innerResolve(value); - }; - const reject = (reason?: Error) => { - if (innerReject) innerReject(reason); - }; - - const promise = new Promise((res, rej) => { - innerResolve = res; - innerReject = rej; - }); - - return { promise, resolve, reject }; -} export function concatBytes( parts: readonly Uint8Array[], length = parts.reduce((total, part) => total + part.length, 0) diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts index 3710e4706..588c8205d 100644 --- a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -16,7 +16,6 @@ describe('allocateVolume', () => { expect(volume.origin).toEqual([0, 0, 5]); expect(volume.spacing).toEqual([0.5, 0.5, 1]); expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); - expect(volume.reconstruction.slots).toEqual([0, 1, 2]); expect(volume.data).toBeInstanceOf(Uint16Array); expect(volume.data).toHaveLength(48); expect([...volume.loaded]).toEqual([0, 0, 0]); @@ -40,21 +39,21 @@ describe('allocateVolume', () => { expect(volume.data).toBeInstanceOf(type); }); - it('keeps an irregular stack in order unless the policy rejects it', () => { - const members = [0, 1, 3].map((z) => pixelSlice(z)); + it('keeps an irregular stack in order and reports why it is irregular', () => { + const volume = allocated([0, 1, 3].map((z) => pixelSlice(z))); - expect(allocated(members).dimensions[2]).toBe(3); - expect(() => - allocated(members, undefined, { irregularGeometry: 'reject' }) - ).toThrow(/irregular/); + expect(volume.dimensions[2]).toBe(3); + expect(volume.spatialMetadata.reconstruction).toEqual({ + kind: 'irregular', + reason: 'uneven-slice-spacing', + }); }); - it('uses the planned spacing and slice mapping without reconstructing it', () => { + it('takes the planned slice spacing as given', () => { const update = plannedUpdate([pixelSlice(1), pixelSlice(19)]); const reconstruction = { - kind: 'regular' as const, + ...update.collection.reconstruction, sliceSpacing: 9, - slots: [0, 2], }; const volume = allocateVolume({ @@ -63,27 +62,11 @@ describe('allocateVolume', () => { }); expect(volume).toMatchObject({ - dimensions: [4, 4, 3], + dimensions: [4, 4, 2], spacing: [0.5, 0.5, 9], }); }); - it('rejects a plan whose first slice slot is not zero', () => { - const update = plannedUpdate([pixelSlice(10), pixelSlice(20)]); - const reconstruction = { - kind: 'regular' as const, - sliceSpacing: 10, - slots: [1, 2], - }; - - expect(() => - allocateVolume({ - ...update, - collection: { ...update.collection, reconstruction }, - }) - ).toThrow('slice slot'); - }); - it('applies the first ultrasound region as display spacing', () => { const { dataset, source } = pixelSlice(0, { modality: 'US' }); const ultrasound = { diff --git a/packages/dicom/core/volume/__tests__/enhancedFixture.ts b/packages/dicom/core/volume/__tests__/enhancedFixture.ts new file mode 100644 index 000000000..51bdf2f09 --- /dev/null +++ b/packages/dicom/core/volume/__tests__/enhancedFixture.ts @@ -0,0 +1,69 @@ +import type { DicomDataset } from '../../metadata/dicomDataset'; +import { datasetFromTags } from '@/tests/dicomDataset'; + +export const tags = (values: Record) => + datasetFromTags(Object.entries(values)); + +export function sequence(tag: string, items: DicomDataset[]) { + return { + tag, + group: parseInt(tag.slice(0, 4), 16), + element: parseInt(tag.slice(4), 16), + vr: 'SQ', + values: { kind: 'sequence' as const, items }, + }; +} + +export const groups = ( + items: Array> +): DicomDataset => ({ + specificCharacterSet: null, + elements: items, +}); + +/** An enhanced multiframe header: shared groups, one per-frame group per frame. */ +export function enhanced( + shared: DicomDataset, + frames: DicomDataset[], + root: Record = {} +): DicomDataset { + const header = tags({ + '00280010': '2', + '00280011': '2', + '00280008': String(frames.length), + '00280101': '16', + ...root, + }); + return { + ...header, + elements: [ + ...header.elements, + sequence('52009229', [shared]), + sequence('52009230', frames), + ], + }; +} + +export const positioned = (position: string) => + groups([sequence('00209113', [tags({ '00200032': position })])]); + +export const ctShared = () => + groups([ + sequence('00289110', [tags({ '00280030': '.388672\\.388672' })]), + sequence('00209116', [tags({ '00200037': '-1\\0\\0\\0\\1\\0' })]), + sequence('00289145', [tags({ '00281052': '-1024', '00281053': '1' })]), + ]); + +/** Two frames at one position that differ only in Temporal Position Index. */ +export function sharedPlaneTemporal() { + const shared = ctShared(); + shared.elements.push( + sequence('00209113', [tags({ '00200032': '10\\20\\30' })]) + ); + return enhanced( + shared, + [1, 2].map((time) => + groups([sequence('00209111', [tags({ '00209128': String(time) })])]) + ) + ); +} diff --git a/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts b/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts similarity index 59% rename from packages/dicom/core/volume/__tests__/functionalGroups.spec.ts rename to packages/dicom/core/volume/__tests__/frameGeometry.spec.ts index 80b6bccd3..4eb322db1 100644 --- a/packages/dicom/core/volume/__tests__/functionalGroups.spec.ts +++ b/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts @@ -1,93 +1,28 @@ import { describe, expect, it } from 'vitest'; import type { DicomDataset } from '../../metadata/dicomDataset'; -import { - readGeometryFacts, - readInstanceFacts, -} from '../../collections/instanceFacts'; -import { - planDicomCollections, - IRREGULAR_VOLUME_WARNING, - REPEATED_POSITIONS_WARNING, - UNREADABLE_FRAME_GEOMETRY_WARNING, - type DicomCollection, -} from '../../collections/planDicomCollections'; -import type { Reconstruction } from '../../collections/reconstructVolume'; -import { getFrameTag } from '../../metadata/functionalGroups'; +import { readGeometryFacts } from '../../collections/instanceFacts'; import { instanceFor } from '@/tests/dicomDataset'; import { createDicomRuntime } from '../../runtime/createDicomRuntime'; import { fromBlob } from '../../source/byteSource'; import { allocateVolume, type Volume } from '../allocateVolume'; import { loadVolume } from '../loadVolume'; import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; -import type { IrregularGeometryPolicy } from '../volumeLayout'; -import { datasetFromTags } from '../../../../../tests/dicomDataset'; - -const tags = (values: Record) => - datasetFromTags(Object.entries(values)); - -function sequence(tag: string, items: DicomDataset[]) { - return { - tag, - group: parseInt(tag.slice(0, 4), 16), - element: parseInt(tag.slice(4), 16), - vr: 'SQ', - values: { kind: 'sequence' as const, items }, - }; -} - -const groups = (items: Array>): DicomDataset => ({ - specificCharacterSet: null, - elements: items, -}); - -function enhanced( - shared: DicomDataset, - frames: DicomDataset[], - root: Record = {} -): DicomDataset { - const header = tags({ - '00280010': '2', - '00280011': '2', - '00280008': String(frames.length), - '00280101': '16', - ...root, - }); - return { - ...header, - elements: [ - ...header.elements, - sequence('52009229', [shared]), - sequence('52009230', frames), - ], - }; -} - -const positioned = (position: string) => - groups([sequence('00209113', [tags({ '00200032': position })])]); - -const ONE_SLOT: Reconstruction = { - kind: 'regular', - sliceSpacing: null, - slots: [0], -}; - -/** Allocates one instance against a supplied plan, as a planner would hand it. */ -const allocate = ( - metadata: DicomDataset, - policy: IrregularGeometryPolicy = 'preserve-order', - { orientation = null, reconstruction = ONE_SLOT } = {} as Partial< - Pick - > -) => - allocateVolume( - { - kind: 'image', - id: 'frames', - collection: { orientation, reconstruction } as DicomCollection, - members: [instanceFor(metadata)], - }, - { irregularGeometry: policy } - ); +import { + ctShared, + enhanced, + groups, + positioned, + sequence, + sharedPlaneTemporal, + tags, +} from './enhancedFixture'; + +/** Plans one instance and allocates the volume it fills. */ +const allocate = (metadata: DicomDataset) => + allocateVolume(plannedUpdate([instanceFor(metadata)])); + +const reconstructionOf = (metadata: DicomDataset) => + allocate(metadata).spatialMetadata.reconstruction; const indexToWorld = (volume: Volume, index: number[]) => [0, 1, 2].map( @@ -101,28 +36,18 @@ const indexToWorld = (volume: Volume, index: number[]) => ) ); -const ctShared = () => - groups([ - sequence('00289110', [tags({ '00280030': '.388672\\.388672' })]), - sequence('00209116', [tags({ '00200037': '-1\\0\\0\\0\\1\\0' })]), - sequence('00289145', [tags({ '00281052': '-1024', '00281053': '1' })]), - ]); - describe('enhanced volume Functional Groups', () => { - it('places stored enhanced CT frames at their patient positions and preserves negative values', () => { + it('places stored enhanced CT frames at their patient positions in a buffer that holds negative values', () => { const metadata = enhanced(ctShared(), [ positioned('99.5\\-301.5\\-159'), positioned('99.5\\-301.5\\-149'), ]); - const volume = allocate(metadata, 'reject'); + const volume = allocate(metadata); + expect(volume.spatialMetadata.reconstruction).toEqual({ kind: 'regular' }); expect(volume.spacing).toEqual([0.388672, 0.388672, 10]); expect(indexToWorld(volume, [0, 0, 0])).toEqual([99.5, -301.5, -159]); expect(indexToWorld(volume, [0, 0, 1])).toEqual([99.5, -301.5, -149]); - const buffer = volume.data; - buffer[0] = -1024; - buffer[4] = 172; - expect([buffer[0], buffer[4]]).toEqual([-1024, 172]); - expect(buffer).toBeInstanceOf(Float32Array); + expect(volume.data).toBeInstanceOf(Float32Array); }); it('uses the storage direction for an oblique enhanced MR stack', () => { @@ -141,7 +66,8 @@ describe('enhanced volume Functional Groups', () => { positioned('-81.8877146\\-123.869376\\159.934076'), ] ); - const volume = allocate(metadata, 'reject'); + const volume = allocate(metadata); + expect(volume.spatialMetadata.reconstruction).toEqual({ kind: 'regular' }); expect(volume.spacing[2]).toBeCloseTo(1.33, 8); expect(indexToWorld(volume, [0, 0, 1])[0]).toBeCloseTo(-81.8877146, 7); expect(volume.direction[1]).toBeCloseTo(0.9762960207, 8); @@ -198,48 +124,49 @@ describe('enhanced volume Functional Groups', () => { ]), ] ); - const { data } = allocate(metadata); - expect(data).toBeInstanceOf(Float32Array); - data[0] = -1023.5; - expect(data[0]).toBe(-1023.5); + expect(allocate(metadata).data).toBeInstanceOf(Float32Array); }); it.each([ ['repeated-position', [0, 0, 2]], ['uneven-slice-spacing', [0, 1, 3]], ])( - 'honors the irregular geometry policy for %s frames', + 'keeps %s frames in stored order and reports the reason', (reason, positions) => { - const metadata = enhanced( - ctShared(), - positions.map((z) => positioned(`0\\0\\${z}`)) + const volume = allocate( + enhanced( + ctShared(), + positions.map((z) => positioned(`0\\0\\${z}`)) + ) ); - expect(() => allocate(metadata, 'reject')).toThrow(reason); - expect(allocate(metadata).dimensions).toEqual([2, 2, 3]); + expect(volume.spatialMetadata.reconstruction).toEqual({ + kind: 'irregular', + reason, + }); + expect(volume.dimensions).toEqual([2, 2, 3]); } ); - it('rejects changing frame orientation instead of claiming a regular lattice', () => { + it('reports changing frame orientation as unreadable instead of claiming a regular lattice', () => { const second = positioned('0\\0\\1'); second.elements.push( sequence('00209116', [tags({ '00200037': '0\\1\\0\\1\\0\\0' })]) ); - expect(() => - allocate(enhanced(ctShared(), [positioned('0\\0\\0'), second]), 'reject') - ).toThrow('unreadable-geometry'); + expect( + reconstructionOf(enhanced(ctShared(), [positioned('0\\0\\0'), second])) + ).toEqual({ kind: 'irregular', reason: 'unreadable-geometry' }); }); - it('rejects changing pixel spacing and temporal frames under the regular geometry policy', () => { + it('reports changing pixel spacing and temporal frames as irregular', () => { const changedSpacing = positioned('0\\0\\1'); changedSpacing.elements.push( sequence('00289110', [tags({ '00280030': '2\\2' })]) ); - expect(() => - allocate( - enhanced(ctShared(), [positioned('0\\0\\0'), changedSpacing]), - 'reject' + expect( + reconstructionOf( + enhanced(ctShared(), [positioned('0\\0\\0'), changedSpacing]) ) - ).toThrow('mixed-pixel-spacing'); + ).toEqual({ kind: 'irregular', reason: 'mixed-pixel-spacing' }); const temporal = [0, 1].map((index) => { const frame = positioned(`0\\0\\${index}`); frame.elements.push( @@ -247,9 +174,10 @@ describe('enhanced volume Functional Groups', () => { ); return frame; }); - expect(() => allocate(enhanced(ctShared(), temporal), 'reject')).toThrow( - 'unreadable-geometry' - ); + expect(reconstructionOf(enhanced(ctShared(), temporal))).toEqual({ + kind: 'irregular', + reason: 'unreadable-geometry', + }); }); it('reads OCT in-plane calibration without using optical depth of field as frame separation', () => { @@ -267,35 +195,10 @@ describe('enhanced volume Functional Groups', () => { expect(allocate(metadata).spacing).toEqual([0.01174168, 0.001955034, 1]); }); - it('reads exact macro paths without changing raw tags or importing referenced-image geometry', () => { - const metadata = enhanced(ctShared(), [positioned('1\\2\\3')], { - '00280030': '9\\9', - }); - metadata.elements.push( - sequence('00081140', [tags({ '00200037': '0\\1\\0\\0\\0\\1' })]) - ); - const before = JSON.stringify(metadata); - expect(readGeometryFacts(metadata)).toEqual({ - orientation: [-1, 0, 0, 0, 1, 0], - position: [1, 2, 3], - pixelSpacing: [0.388672, 0.388672], - }); - expect(getFrameTag(metadata, '00280030')).toBe('.388672\\.388672'); - expect(JSON.stringify(metadata)).toBe(before); - const rootOnly = tags({ '00280030': '2\\3' }); - rootOnly.elements.push( - sequence('00081140', [tags({ '00200037': '0\\1\\0\\0\\0\\1' })]) - ); - expect(readGeometryFacts(rootOnly).orientation).toBeNull(); + it('reports shared-plane temporal frames as irregular', () => { + const metadata = sharedPlaneTemporal(); + expect(reconstructionOf(metadata)?.kind).toBe('irregular'); }); -}); - -describe('intra-instance frame planning', () => { - const collectionOf = (metadata: DicomDataset) => - planDicomCollections({ - seriesKey: 'frames', - instances: [readInstanceFacts(metadata)], - }).collections[0]; it.each([1, -1])( 'preserves stored frame direction %s through registration and image allocation', @@ -314,69 +217,6 @@ describe('intra-instance frame planning', () => { ); } ); - - it('rejects shared-plane temporal frames under strict geometry validation', () => { - const shared = ctShared(); - shared.elements.push( - sequence('00209113', [tags({ '00200032': '10\\20\\30' })]) - ); - const metadata = enhanced( - shared, - [1, 2].map((time) => - groups([sequence('00209111', [tags({ '00209128': String(time) })])]) - ) - ); - const collection = collectionOf(metadata); - expect(collection.reconstruction).toMatchObject({ - kind: 'irregular', - slots: [0], - }); - expect(collection.warnings).toContain(UNREADABLE_FRAME_GEOMETRY_WARNING); - expect(() => allocate(metadata, 'reject', collection)).toThrow( - 'irregular DICOM geometry' - ); - }); - - it('keeps an unreadable frame geometry warning for a lone multiframe source', () => { - const metadata = enhanced( - ctShared(), - [1, 2].map((index) => - groups([sequence('00209111', [tags({ '00209057': String(index) })])]) - ) - ); - const collection = collectionOf(metadata); - expect(collection.reconstruction).toMatchObject({ - kind: 'irregular', - reason: 'unreadable-geometry', - slots: [0], - }); - expect(collection.warnings).toContain(UNREADABLE_FRAME_GEOMETRY_WARNING); - }); - - it.each([ - [[0, 1, 3], 'uneven-slice-spacing', IRREGULAR_VOLUME_WARNING], - [[0, 0, 2], 'repeated-position', REPEATED_POSITIONS_WARNING], - ] as const)( - 'reports intra-instance geometry %s while retaining one source slot', - (positions, reason, warning) => { - const metadata = enhanced( - ctShared(), - positions.map((z) => positioned(`0\\0\\${z}`)) - ); - const collection = collectionOf(metadata); - expect(collection.reconstruction).toMatchObject({ - kind: 'irregular', - reason, - slots: [0], - }); - expect(collection.warnings).toContain(warning); - const volume = allocate(metadata, 'preserve-order', { - orientation: collection.orientation, - }); - expect(volume.reconstruction).toEqual(collection.reconstruction); - expect(volume.dimensions).toEqual([2, 2, 3]); - } - ); }); function nmMetadata(overrides: Record = {}) { @@ -453,9 +293,11 @@ describe('reconstructed NM spatial volumes', () => { 'uses the detector plane and signed NM slice progression %s', (sign) => { const volume = allocate( - nmMetadata({ '00180088': String(sign * 4.7951998710632) }), - 'reject' + nmMetadata({ '00180088': String(sign * 4.7951998710632) }) ); + expect(volume.spatialMetadata.reconstruction).toEqual({ + kind: 'regular', + }); expect(volume.spacing).toEqual([ 4.7951998710632, 4.7951998710632, 4.7951998710632, ]); @@ -474,7 +316,8 @@ describe('reconstructed NM spatial volumes', () => { '00540080': '1', '00180088': '', }); - const volume = allocate(metadata, 'reject'); + const volume = allocate(metadata); + expect(volume.spatialMetadata.reconstruction).toEqual({ kind: 'regular' }); expect(volume.origin).toEqual([4, 5, 6]); expect(volume.spacing).toEqual([4.7951998710632, 4.7951998710632, 1]); expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); @@ -528,19 +371,6 @@ describe('reconstructed NM spatial volumes', () => { }); }); -it('does not report normal segment-major SEG frames as an irregular volume', () => { - const metadata = enhanced( - ctShared(), - [0, 1, 0, 1].map((z) => positioned('0\\0\\' + z)), - { '00080060': 'SEG' } - ); - const plan = planDicomCollections({ - seriesKey: 'seg', - instances: [readInstanceFacts(metadata)], - }); - expect(plan.collections[0].warnings).toEqual([]); -}); - it('reports a missing NM NumberOfSlices without claiming temporal dimensions', () => { const metadata = nmMetadata(); metadata.elements = metadata.elements.filter((el) => el.tag !== '00540081'); diff --git a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts index 1560d2ede..871e7f476 100644 --- a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -9,13 +9,14 @@ import { fromUrl, type ByteRange, type ByteSource, - type RangeSupport, } from '../../source/byteSource'; import { loadVolume, type VolumeUpdate } from '../loadVolume'; -import { defaultDecoderTable } from '../../pixels/decoderTable'; +import { + defaultDecoderTable, + singleDecoderTable, +} from '../../pixels/decoderTable'; import type { DecodeUnit, PixelDecoder } from '../../pixels/pixelDecoder'; import { allocated } from './volumeFixture'; -import { hangingSource } from '@/tests/byteSourceFixtures'; import { nativePixelDicom, patternWords, @@ -86,6 +87,17 @@ const multiframe = (options: NativePixelOptions = {}) => { }; }; +/** One failure that spans every frame of `multiframe()`. */ +const failsWhole = (message: RegExp) => [ + { + slot: 0, + extent: [0, 2, 0, 1, 0, FRAMES - 1], + error: expect.objectContaining({ + message: expect.stringMatching(message), + }), + }, +]; + /** Frame `frame` of `multiframe()`, read from its own range. */ const frameUnit = (valueOffset: number, frame: number): DecodeUnit => { const start = valueOffset + frame * 12; @@ -146,6 +158,34 @@ describe('loadVolume with native frames', () => { expect(Array.from(volume.data)).toEqual(words); }); + it('loads the frames a file cut short still holds and fails the rest', async () => { + const { bytes, words } = multiframe(); + const instance = await readInstance(blobOf(bytes), signal()); + const cut = { ...instance, source: blobOf(bytes.subarray(0, -18)) }; + + const { volume, updates } = await load([cut], { readAhead: 1 }); + + const failed = updates.flatMap((update) => + 'error' in update ? [[update.slot, update.error.message]] : [] + ); + expect(failed).toEqual([ + [ + 4, + expect.stringMatching( + /frame 4 could not be decoded: A frame needs 12 bytes of Pixel Data; 0 were read$/ + ), + ], + [ + 3, + expect.stringMatching( + /frame 3 could not be decoded: A frame needs 12 bytes of Pixel Data; 6 were read$/ + ), + ], + ]); + expect(Array.from(volume.loaded)).toEqual([1, 1, 1, 0, 0]); + expect(Array.from(volume.data.subarray(0, 18))).toEqual(words.slice(0, 18)); + }); + it('reports the float32-rounded range a Float32 volume stores', async () => { const { bytes, words } = multiframe({ rescale: [0.1, 0.3] }); const instance = await readInstance(blobOf(bytes), signal()); @@ -178,7 +218,7 @@ describe('loadVolume with native frames', () => { sources.map(({ source }) => readInstance(source, signal())) ); - const { volume, updates } = await load(members); + const { volume, updates } = await load(members, { readAhead: 1 }); expect(updates.map((update) => update.slot)).toEqual([1, 0, 2]); sources.forEach(({ ranges }, index) => @@ -192,18 +232,18 @@ describe('loadVolume with native frames', () => { }); it.each([ - [true, 1 + FRAMES], - [false, 3], - ])( - 'reads frames from a server that honours Range (%s) in %i requests', - async (honoured, requests) => { + ['honours', 1 + FRAMES], + ['ignores', 3], + ] as const)( + 'probes a server that %s Range with one frame, then makes %i requests in all', + async (behaviour, requests) => { const { bytes, words } = multiframe(); const asked: Array = []; const fetchFn: typeof fetch = async (_url, init) => { const range = new Headers(init?.headers).get('Range'); asked.push(range); const [, from, to] = /bytes=(\d+)-(\d+)/.exec(range ?? '') ?? []; - return honoured && from + return behaviour === 'honours' && from ? new Response(bytes.slice(Number(from), Number(to) + 1), { status: 206, }) @@ -216,11 +256,68 @@ describe('loadVolume with native frames', () => { const { volume } = await load([instance]); - expect(asked).toHaveLength(requests); + const start = instance.pixelData!.valueOffset; + const frames = (index: number, count = 1) => + `bytes=${start + index * 12}-${start + (index + count) * 12 - 1}`; + const [header, probe, ...rest] = asked; + expect(header).toBeNull(); + expect(probe).toBe(frames(0)); + expect(rest).toHaveLength(requests - 2); + expect(rest).toEqual( + behaviour === 'honours' + ? expect.arrayContaining([1, 2, 3, 4].map((index) => frames(index))) + : [frames(1, FRAMES - 1)] + ); expect(Array.from(volume.data)).toEqual(words); } ); + it('hands the thread back once a run of decodes has had its share, so a load stopped then decodes no more', async () => { + const codec = '1.2.3.4'; + const { bytes } = multiframe({ transferSyntaxUid: codec }); + const source: ByteSource = { + ...blobOf(bytes), + rangeSupport: () => 'ignored', + }; + const instance = await readInstance(source, signal()); + const decoded: number[] = []; + // Each decode alone outlasts the run a load allows itself. + const slow = (unit: DecodeUnit): DecodeUnit => ({ + ...unit, + decode: (frameBytes, decodeSignal) => { + decoded.push(unit.firstFrame); + const until = performance.now() + 20; + while (performance.now() < until); + return unit.decode(frameBytes, decodeSignal); + }, + }); + const runtime = createDicomRuntime({ + decodeConcurrency: 1, + decoders: () => + singleDecoderTable({ + name: 'Slow per-frame codec', + plan: ({ pixelData }) => + Array.from({ length: FRAMES }, (_, frame) => + slow(frameUnit(pixelData!.valueOffset, frame)) + ), + }), + }); + runtimes.push(runtime); + const controller = new AbortController(); + + const slots: number[] = []; + for await (const update of loadVolume(allocated([instance]), { + runtime, + signal: controller.signal, + })) { + slots.push(update.slot); + controller.abort(); + } + + expect(slots).toHaveLength(1); + expect(decoded).toEqual(slots); + }); + it('fails every slice of an instance it cannot decode, without reading pixels', async () => { const { bytes } = multiframe({ transferSyntaxUid: '1.2.840.10008.1.2.4.102', @@ -230,15 +327,7 @@ describe('loadVolume with native frames', () => { const { updates } = await load([instance]); - expect(updates).toEqual([ - { - slot: 0, - extent: [0, 2, 0, 1, 0, FRAMES - 1], - error: expect.objectContaining({ - message: expect.stringMatching(/MPEG-4 .* has no decoder/), - }), - }, - ]); + expect(updates).toEqual(failsWhole(/MPEG-4 .* has no decoder/)); expect(ranges).toEqual([undefined]); }); @@ -248,33 +337,11 @@ describe('loadVolume with native frames', () => { const { updates } = await load([instance]); - expect(updates).toEqual([ - { - slot: 0, - extent: [0, 2, 0, 1, 0, FRAMES - 1], - error: new Error('GDCM decoding needs createDicomRuntime({ assets })'), - }, - ]); - }); - - it('stops frame reads and yields nothing once aborted', async () => { - const { bytes } = multiframe(); - const hanging = hangingSource(); - const blob = blobOf(bytes); - const source: ByteSource = { - read: (readSignal, range) => - range ? hanging.source.read(readSignal, range) : blob.read(readSignal), - }; - const instance = await readInstance(source, signal()); - const controller = new AbortController(); - - const loading = load([instance], { abort: controller.signal }); - await hanging.pulled; - const reason = new DOMException('closed', 'AbortError'); - controller.abort(reason); - - expect((await loading).updates).toEqual([]); - expect(await hanging.cancelled).toBe(reason); + expect(updates).toEqual( + failsWhole( + /^File .* \(member 0\) could not be decoded: GDCM decoding needs createDicomRuntime\(\{ assets \}\)$/ + ) + ); }); it('loads frame by frame through a per-frame decoder added to the table', async () => { @@ -351,79 +418,4 @@ describe('loadVolume with native frames', () => { expect(volume.loaded).toEqual(new Uint8Array(FRAMES)); } ); - - it.each([ - ['honours', FRAMES], - ['ignores', 2], - ] as const)( - 'probes a source that %s Range with one frame, then makes %i frame reads in all', - async (behaviour, frameReads) => { - const { bytes, words } = multiframe(); - const blob = recorded(blobOf(bytes)); - let support: RangeSupport = 'unknown'; - const source: ByteSource = { - read: (readSignal, range) => { - if (range) support = behaviour === 'honours' ? 'honoured' : 'ignored'; - return blob.source.read(readSignal, range); - }, - rangeSupport: () => support, - }; - const instance = await readInstance(source, signal()); - - const { volume } = await load([instance]); - - const start = instance.pixelData!.valueOffset; - const frame = (index: number, count = 1) => ({ - start: start + index * 12, - end: start + (index + count) * 12, - }); - const [header, probe, ...rest] = blob.ranges; - expect(header).toBeUndefined(); - expect(probe).toEqual(frame(0)); - expect(rest).toHaveLength(frameReads - 1); - expect(rest).toEqual( - behaviour === 'honours' - ? expect.arrayContaining([1, 2, 3, 4].map((index) => frame(index))) - : [frame(1, FRAMES - 1)] - ); - expect(Array.from(volume.data)).toEqual(words); - } - ); - - it('reads frame calibrations in time linear in the frame count', async () => { - const datasetReads = async (frames: number) => { - const bytes = nativePixelDicom({ - rows: 2, - columns: 3, - frames, - words: patternWords(frames * 6, 16), - rescale: [0.1, 0.3], - }); - const instance = await readInstance(blobOf(bytes), signal()); - const { dataset } = instance; - let reads = 0; - const counted = { - ...instance, - dataset: { - ...dataset, - get elements() { - reads += 1; - return dataset.elements; - }, - }, - }; - const { volume, updates } = await load([counted]); - expect(volume.data).toBeInstanceOf(Float32Array); - expect(updates).toHaveLength(frames); - return reads; - }; - - const [ten, twenty, forty] = [ - await datasetReads(10), - await datasetReads(20), - await datasetReads(40), - ]; - - expect(forty - twenty).toBe(2 * (twenty - ten)); - }); }); diff --git a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts index 6393381be..65fafe6ae 100644 --- a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -6,7 +6,6 @@ import { import type { WholeInstanceDecode } from '../../pixels/pixelDecoder'; import { singleDecoderTable } from '../../pixels/decoderTable'; import type { GdcmLane } from '../../runtime/gdcmDecoder'; -import { defer } from '../../utils'; import { hangingSource } from '@/tests/byteSourceFixtures'; import { loadedRange, type Volume } from '../allocateVolume'; import type { ByteSource } from '../../source/byteSource'; @@ -101,32 +100,53 @@ describe('loadVolume', () => { expect(loadedRange(volume)).toEqual([[0, 4]]); }); - it('reports a failed slice and keeps loading the rest', async () => { + it('names the file of each failed slice and keeps loading the rest', async () => { const decode = valueDecoder(); + const corrupt = new Error('corrupt pixel data'); const decoder: WholeInstanceDecode = async (request, signal) => { const image = await decode(request, signal); - if (image.data[0] === 1) throw new Error('corrupt pixel data'); + if (image.data[0] === 0) throw 4949048; + if (image.data[0] === 1) throw corrupt; if (image.data[0] === 3) return { ...image, size: [2, 8, 1] as const }; return image; }; const volume = stack(5); - const updates = await loadAll(volume, runtimeWith(decoder)); + const updates = await loadAll(volume, runtimeWith(decoder), { + readAhead: 1, + }); const errors = updates.flatMap((update) => - 'error' in update ? [[update.slot, update.error.message]] : [] + 'error' in update + ? [[update.slot, update.error.message, update.error.cause]] + : [] ); expect(errors).toEqual([ - [1, 'corrupt pixel data'], - [3, expect.stringMatching(/does not fit the volume/)], + [ + 0, + 'File pixel-0 (member 0) could not be decoded: the decoder failed without a message', + 4949048, + ], + [ + 1, + 'File pixel-1 (member 1) could not be decoded: corrupt pixel data', + corrupt, + ], + [ + 3, + expect.stringMatching( + /^File pixel-3 \(member 3\) does not fit the volume/ + ), + undefined, + ], ]); - expect(sliceValues(volume)).toEqual([0, null, 2, null, 4]); + expect(sliceValues(volume)).toEqual([null, null, 2, null, 4]); }); it('reorders reads around a focus that moves while a slice decodes', async () => { const decoded: number[] = []; const decode = valueDecoder(decoded); - const resume = defer(); + const resume = Promise.withResolvers(); const decoder: WholeInstanceDecode = async (request, signal) => { const image = await decode(request, signal); if (decoded.length === 1) await resume.promise; @@ -177,8 +197,8 @@ describe('loadVolume', () => { it('runs at most decodeConcurrency decodes at once', async () => { let active = 0; let peak = 0; - const gate = defer(); - const twoStarted = defer(); + const gate = Promise.withResolvers(); + const twoStarted = Promise.withResolvers(); const decode = valueDecoder(); const decoder: WholeInstanceDecode = async (request, signal) => { active += 1; @@ -197,11 +217,12 @@ describe('loadVolume', () => { expect(peak).toBe(2); }); - it('reports a failed read and keeps loading the rest', async () => { + it('names the file of a failed read and keeps loading the rest', async () => { + const reset = new Error('connection reset'); const failing: ByteSource = { read: () => new ReadableStream({ - pull: (controller) => controller.error(new Error('connection reset')), + pull: (controller) => controller.error(reset), }), }; const volume = allocated([ @@ -214,9 +235,13 @@ describe('loadVolume', () => { expect( updates.flatMap((update) => - 'error' in update ? [[update.slot, update.error.message]] : [] + 'error' in update + ? [[update.slot, update.error.message, update.error.cause]] + : [] ) - ).toEqual([[1, 'connection reset']]); + ).toEqual([ + [1, 'File pixel-1 (member 1) could not be read: connection reset', reset], + ]); expect(sliceValues(volume)).toEqual([0, null, 2]); }); @@ -247,25 +272,10 @@ describe('loadVolume', () => { expect(sliceValues(volume)).toEqual([null, 1, null]); }); - it('ends when the runtime is disposed during a decode', async () => { - const started = defer(); - const decoder: WholeInstanceDecode = () => { - started.resolve(); - return new Promise(() => {}); - }; - const runtime = runtimeWith(decoder); - - const loading = loadAll(stack(2), runtime); - await started.promise; - runtime.dispose(); - - expect(await loading).toEqual([]); - }); - it('keeps decoding while the consumer waits, marking slices loaded only as they are yielded', async () => { const decoded: number[] = []; const decode = valueDecoder(decoded); - const lastStarted = defer(); + const lastStarted = Promise.withResolvers(); const decoder: WholeInstanceDecode = (request, signal) => { if (decoded.length === 4) lastStarted.resolve(); return decode(request, signal); @@ -318,7 +328,7 @@ describe('loadVolume', () => { }); it('ends and stops the GDCM worker when the runtime is disposed mid-decode', async () => { - const started = defer(); + const started = Promise.withResolvers(); const resets: unknown[] = []; const hangingLane = (): GdcmLane => ({ run: () => { diff --git a/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts b/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts new file mode 100644 index 000000000..829d0aa93 --- /dev/null +++ b/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts @@ -0,0 +1,264 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, it, expect } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import { + getPixelFormat, + getRescaledValueRange, + getVolumeBufferType, +} from '../pixelFormat'; + +// Builds a format from exactly the tags given, with no defaults filled in, so +// each test states the whole instance it is describing. +function format(tags: Record) { + return getPixelFormat(datasetFromTags(Object.entries(tags))); +} + +const UNSIGNED_16 = format({ + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', +}); +const SIGNED_16 = format({ + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '1', +}); +const UNSIGNED_8 = format({ + [Tags.BitsStored]: '8', + [Tags.PixelRepresentation]: '0', +}); +// A CT stored as 12-bit unsigned and rescaled to Hounsfield units. +const RESCALED_CT = format({ + [Tags.BitsStored]: '12', + [Tags.PixelRepresentation]: '0', + [Tags.RescaleSlope]: '1', + [Tags.RescaleIntercept]: '-1024', +}); +const NEGATIVE_SLOPE_8 = format({ + [Tags.BitsStored]: '8', + [Tags.PixelRepresentation]: '0', + [Tags.RescaleSlope]: '-1', +}); +const PUBLIC_DSC_SLOPE = '112067.85375182'; +const PUBLIC_DSC = format({ + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', + [Tags.RescaleSlope]: PUBLIC_DSC_SLOPE, + [Tags.RescaleIntercept]: '0', +}); + +describe('getPixelFormat', () => { + it('uses the DICOM defaults for absent rescale tags', () => { + expect(UNSIGNED_16).toEqual({ + bitsStored: 16, + pixelRepresentation: 0, + rescaleSlope: 1, + rescaleIntercept: 0, + }); + }); + + it('reports bitsStored 0 when the tag is absent', () => { + expect(format({ [Tags.PixelRepresentation]: '0' }).bitsStored).toBe(0); + }); + + it('treats a zero-length element as absent rather than as zero', () => { + expect( + format({ [Tags.BitsStored]: '16', [Tags.RescaleSlope]: '' }).rescaleSlope + ).toBe(1); + expect( + format({ [Tags.BitsStored]: '16', [Tags.RescaleSlope]: ' ' }) + .rescaleSlope + ).toBe(1); + expect( + format({ [Tags.BitsStored]: '', [Tags.PixelRepresentation]: '' }) + ).toEqual({ + bitsStored: 0, + pixelRepresentation: 0, + rescaleSlope: 1, + rescaleIntercept: 0, + }); + }); + + it('parses padded numeric strings', () => { + expect( + format({ [Tags.BitsStored]: '16', [Tags.RescaleIntercept]: ' -1024 ' }) + .rescaleIntercept + ).toBe(-1024); + }); +}); + +describe('getRescaledValueRange', () => { + it('spans the stored range put through slope and intercept', () => { + expect(getRescaledValueRange(UNSIGNED_16)).toEqual({ min: 0, max: 65535 }); + expect(getRescaledValueRange(SIGNED_16)).toEqual({ + min: -32768, + max: 32767, + }); + expect(getRescaledValueRange(RESCALED_CT)).toEqual({ + min: -1024, + max: 3071, + }); + }); + + it('orders the endpoints when the slope is negative', () => { + expect(getRescaledValueRange(NEGATIVE_SLOPE_8)).toEqual({ + min: -255, + max: 0, + }); + }); + + it('is null when BitsStored is missing', () => { + expect(getRescaledValueRange(format({}))).toBeNull(); + }); +}); + +describe('getVolumeBufferType', () => { + it('widens to hold the rescaled range', () => { + expect(getVolumeBufferType([UNSIGNED_8])).toBe(Uint8Array); + expect(getVolumeBufferType([UNSIGNED_16])).toBe(Uint16Array); + expect(getVolumeBufferType([SIGNED_16])).toBe(Int16Array); + expect( + getVolumeBufferType([ + format({ [Tags.BitsStored]: '8', [Tags.PixelRepresentation]: '1' }), + ]) + ).toBe(Int8Array); + expect(getVolumeBufferType([RESCALED_CT])).toBe(Int16Array); + expect(getVolumeBufferType([NEGATIVE_SLOPE_8])).toBe(Int16Array); + expect( + getVolumeBufferType([ + format({ [Tags.BitsStored]: '16', [Tags.RescaleIntercept]: '-1024' }), + ]) + ).toBe(Float32Array); + }); + + it('throws when BitsStored is missing', () => { + expect(() => getVolumeBufferType([format({})])).toThrow(); + }); + + it('keeps the public DSC perfusion series in float32, whose spacing stays below its slope', () => { + expect(getVolumeBufferType([PUBLIC_DSC])).toBe(Float32Array); + }); + + it('uses Float32 when fractional rescale has integral endpoints', () => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '12', + [Tags.RescaleSlope]: '0.2', + [Tags.RescaleIntercept]: '0', + }), + ]) + ).toBe(Float32Array); + }); + + // 65535 * 256 + 256 is exactly 2^24, the last integer float32 counts to. + it.each([ + ['256', Float32Array], + ['257', Uint32Array], + ])( + 'keeps integers in float32 only up to 2^24 (intercept %s)', + (intercept, type) => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '16', + [Tags.RescaleSlope]: '256', + [Tags.RescaleIntercept]: intercept, + }), + ]) + ).toBe(type); + } + ); + + it('keeps signed integers beyond 2^24 in Int32', () => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '1', + [Tags.RescaleSlope]: '513', + }), + ]) + ).toBe(Int32Array); + }); + + // Values reach 2^23 + 1.5 + slope, so float32's spacing there is just above + // 1 + 1.788e-7: one slope keeps steps apart and the other merges them. + it.each([ + ['1.0000002', Float32Array], + ['1.0000001', Float64Array], + ])( + 'uses Float32 for fractional slope %s only while steps stay apart', + (slope, type) => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '1', + [Tags.RescaleSlope]: slope, + [Tags.RescaleIntercept]: '8388608.5', + }), + ]) + ).toBe(type); + } + ); + + it.each([ + ['24', Float32Array], + ['25', Float64Array], + ])( + 'stores at most 24 bits of fractional rescale in Float32 (Bits Stored %s)', + (bitsStored, type) => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: bitsStored, + [Tags.PixelRepresentation]: '1', + [Tags.RescaleSlope]: '0.5', + [Tags.RescaleIntercept]: '0.25', + }), + ]) + ).toBe(type); + } + ); + + it('uses Float64 when an integral modality range exceeds 32 bits', () => { + expect( + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '16', + [Tags.RescaleSlope]: '112068', + [Tags.RescaleIntercept]: '0', + }), + ]) + ).toBe(Float64Array); + }); + + it('rejects a non-finite modality range', () => { + expect(() => + getVolumeBufferType([ + format({ + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', + [Tags.RescaleSlope]: '1e308', + }), + ]) + ).toThrow( + 'No instance declares Bits Stored and a finite modality rescale range' + ); + }); + + it('leaves an instance with no usable range out of the union', () => { + // The containment guard rejects such an instance when it decodes; its + // faulty tags must not stop the rest of the series from allocating. + expect(getVolumeBufferType([format({}), UNSIGNED_16])).toBe(Uint16Array); + expect( + getVolumeBufferType([ + UNSIGNED_16, + format({ [Tags.BitsStored]: '16', [Tags.RescaleSlope]: '1e308' }), + ]) + ).toBe(Uint16Array); + }); + + it('chooses one type that represents every instance in the volume', () => { + expect(getVolumeBufferType([UNSIGNED_8, UNSIGNED_16])).toBe(Uint16Array); + expect(getVolumeBufferType([UNSIGNED_16, PUBLIC_DSC])).toBe(Float32Array); + }); +}); diff --git a/packages/dicom/core/volume/__tests__/volumeFixture.ts b/packages/dicom/core/volume/__tests__/volumeFixture.ts index 5391f87d7..c831c0cbe 100644 --- a/packages/dicom/core/volume/__tests__/volumeFixture.ts +++ b/packages/dicom/core/volume/__tests__/volumeFixture.ts @@ -7,11 +7,7 @@ import { plannedUpdate } from '@/tests/dicomVolumeFixtures'; import type { Instance } from '../../instance/readInstance'; import type { WholeInstanceDecode } from '../../pixels/pixelDecoder'; import { fromBlob } from '../../source/byteSource'; -import { - allocateVolume, - type AllocateVolumeOptions, - type Volume, -} from '../allocateVolume'; +import { allocateVolume, type Volume } from '../allocateVolume'; export const PIXELS_PER_SLICE = 16; @@ -33,11 +29,8 @@ export const pixelSlice = (value: number, options: SliceOptions = {}) => fromBlob(new Blob([String(value)])) ); -export const allocated = ( - members: Instance[], - previous?: Volume, - options: AllocateVolumeOptions = {} -) => allocateVolume(plannedUpdate(members), options, previous); +export const allocated = (members: Instance[], previous?: Volume) => + allocateVolume(plannedUpdate(members), previous); /** The slice a source written by `pixelSlice` decodes to. */ export const slicePixels = (bytes: Uint8Array) => { diff --git a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts index 03fb0b984..8c7fba876 100644 --- a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts +++ b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts @@ -6,16 +6,6 @@ import { } from '../../collections/instanceFacts'; import { reconstructVolume } from '../../collections/reconstructVolume'; import { Tags } from '../../metadata/dicomTags'; -import { - getPixelFormat, - getRescaledValueRange, - getBufferValueRange, - getTypedArrayForDataRange, - getTypedArrayValueRange, - getVolumeBufferType, - samplesAreIntegral, - valuesFitBuffer, -} from '../pixelFormat'; import { volumeLayout, type VolumeSource } from '../volumeLayout'; function volumeSource(overrides: Record = {}): VolumeSource { @@ -40,437 +30,77 @@ function positionedSource(z: number, overrides: Record = {}) { }); } -describe('getTypedArrayForDataRange', () => { - it('should handle edge cases', () => { - expect(getTypedArrayForDataRange(-(2 ** 7), 2 ** 7 - 1)).toBe(Int8Array); - expect(getTypedArrayForDataRange(-(2 ** 15), 2 ** 15 - 1)).toBe(Int16Array); - expect(getTypedArrayForDataRange(-(2 ** 31), 2 ** 31 - 1)).toBe(Int32Array); - expect(getTypedArrayForDataRange(0, 2 ** 8 - 1)).toBe(Uint8Array); - expect(getTypedArrayForDataRange(0, 2 ** 16 - 1)).toBe(Uint16Array); - expect(getTypedArrayForDataRange(0, 2 ** 32 - 1)).toBe(Uint32Array); - }); -}); - -// Builds a format from exactly the tags given, with no defaults filled in, so -// each test states the whole instance it is describing. -function format(tags: Record) { - return getPixelFormat(datasetFromTags(Object.entries(tags))); -} - -const UNSIGNED_16 = format({ - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '0', -}); -const SIGNED_16 = format({ - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '1', -}); -const UNSIGNED_8 = format({ - [Tags.BitsStored]: '8', - [Tags.PixelRepresentation]: '0', -}); -// A CT stored as 12-bit unsigned and rescaled to Hounsfield units. -const RESCALED_CT = format({ - [Tags.BitsStored]: '12', - [Tags.PixelRepresentation]: '0', - [Tags.RescaleSlope]: '1', - [Tags.RescaleIntercept]: '-1024', -}); -const NEGATIVE_SLOPE_8 = format({ - [Tags.BitsStored]: '8', - [Tags.PixelRepresentation]: '0', - [Tags.RescaleSlope]: '-1', -}); -const PUBLIC_DSC_SLOPE = '112067.85375182'; -const PUBLIC_DSC = format({ - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '0', - [Tags.RescaleSlope]: PUBLIC_DSC_SLOPE, - [Tags.RescaleIntercept]: '0', -}); - -describe('getPixelFormat', () => { - it('uses the DICOM defaults for absent rescale tags', () => { - expect(UNSIGNED_16).toEqual({ - bitsStored: 16, - pixelRepresentation: 0, - rescaleSlope: 1, - rescaleIntercept: 0, - }); - }); - - it('reports bitsStored 0 when the tag is absent', () => { - expect(format({ [Tags.PixelRepresentation]: '0' }).bitsStored).toBe(0); - }); - - it('treats a zero-length element as absent rather than as zero', () => { - expect( - format({ [Tags.BitsStored]: '16', [Tags.RescaleSlope]: '' }).rescaleSlope - ).toBe(1); - expect( - format({ [Tags.BitsStored]: '16', [Tags.RescaleSlope]: ' ' }) - .rescaleSlope - ).toBe(1); - expect( - format({ [Tags.BitsStored]: '', [Tags.PixelRepresentation]: '' }) - ).toEqual({ - bitsStored: 0, - pixelRepresentation: 0, - rescaleSlope: 1, - rescaleIntercept: 0, - }); - }); - - it('parses padded numeric strings', () => { - expect( - format({ [Tags.BitsStored]: '16', [Tags.RescaleIntercept]: ' -1024 ' }) - .rescaleIntercept - ).toBe(-1024); - }); -}); - -describe('getRescaledValueRange', () => { - it('spans the stored range put through slope and intercept', () => { - expect(getRescaledValueRange(UNSIGNED_16)).toEqual({ min: 0, max: 65535 }); - expect(getRescaledValueRange(SIGNED_16)).toEqual({ - min: -32768, - max: 32767, - }); - expect(getRescaledValueRange(RESCALED_CT)).toEqual({ - min: -1024, - max: 3071, - }); - }); - - it('orders the endpoints when the slope is negative', () => { - expect(getRescaledValueRange(NEGATIVE_SLOPE_8)).toEqual({ - min: -255, - max: 0, - }); - }); - - it('is null when BitsStored is missing', () => { - expect(getRescaledValueRange(format({}))).toBeNull(); - }); -}); - -describe('getVolumeBufferType', () => { - it('widens to hold the rescaled range', () => { - expect(getVolumeBufferType([UNSIGNED_8])).toBe(Uint8Array); - expect(getVolumeBufferType([UNSIGNED_16])).toBe(Uint16Array); - expect(getVolumeBufferType([SIGNED_16])).toBe(Int16Array); - expect(getVolumeBufferType([RESCALED_CT])).toBe(Int16Array); - expect(getVolumeBufferType([NEGATIVE_SLOPE_8])).toBe(Int16Array); - expect( - getVolumeBufferType([ - format({ [Tags.BitsStored]: '16', [Tags.RescaleIntercept]: '-1024' }), - ]) - ).toBe(Float32Array); - }); - - it('throws when BitsStored is missing', () => { - expect(() => getVolumeBufferType([format({})])).toThrow(); - }); - - it('keeps the public DSC perfusion series in float32, whose spacing stays below its slope', () => { - expect(getVolumeBufferType([PUBLIC_DSC])).toBe(Float32Array); - }); - - it('uses Float32 when fractional rescale has integral endpoints', () => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '12', - [Tags.RescaleSlope]: '0.2', - [Tags.RescaleIntercept]: '0', - }), - ]) - ).toBe(Float32Array); - }); +const AXIAL = [1, 0, 0, 0, 1, 0]; - // 65535 * 256 + 256 is exactly 2^24, the last integer float32 counts to. - it.each([ - ['256', Float32Array], - ['257', Uint32Array], - ])( - 'keeps integers in float32 only up to 2^24 (intercept %s)', - (intercept, type) => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '16', - [Tags.RescaleSlope]: '256', - [Tags.RescaleIntercept]: intercept, - }), - ]) - ).toBe(type); - } - ); - - it('keeps signed integers beyond 2^24 in Int32', () => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '1', - [Tags.RescaleSlope]: '513', - }), - ]) - ).toBe(Int32Array); - }); - - // Values reach 2^23 + 1.5 + slope, so float32's spacing there is just above - // 1 + 1.788e-7: one slope keeps steps apart and the other merges them. - it.each([ - ['1.0000002', Float32Array], - ['1.0000001', Float64Array], - ])( - 'uses Float32 for fractional slope %s only while steps stay apart', - (slope, type) => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '1', - [Tags.RescaleSlope]: slope, - [Tags.RescaleIntercept]: '8388608.5', - }), - ]) - ).toBe(type); - } - ); - - it.each([ - ['24', Float32Array], - ['25', Float64Array], - ])( - 'stores at most 24 bits of fractional rescale in Float32 (Bits Stored %s)', - (bitsStored, type) => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: bitsStored, - [Tags.PixelRepresentation]: '1', - [Tags.RescaleSlope]: '0.5', - [Tags.RescaleIntercept]: '0.25', - }), - ]) - ).toBe(type); - } +/** Plans the members' stack as the collection planner would, then lays it out. */ +function layoutOf(sources: VolumeSource[], orientation: number[] | null) { + const reconstruction = reconstructVolume( + sources.map((item) => readGeometryFacts(item.dataset)), + sliceNormalOf(orientation) ); + return volumeLayout(sources, orientation, reconstruction); +} - it('uses Float64 when an integral modality range exceeds 32 bits', () => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '16', - [Tags.RescaleSlope]: '112068', - [Tags.RescaleIntercept]: '0', - }), - ]) - ).toBe(Float64Array); - }); - - it('rejects a non-finite modality range', () => { - expect(() => - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '0', - [Tags.RescaleSlope]: '1e308', - }), - ]) - ).toThrow('No instance declares a finite modality rescale range'); - }); - - it('leaves an instance with no usable range out of the union', () => { - // The containment guard rejects such an instance when it decodes; its - // faulty tags must not stop the rest of the series from allocating. - expect(getVolumeBufferType([format({}), UNSIGNED_16])).toBe(Uint16Array); - expect( - getVolumeBufferType([ - UNSIGNED_16, - format({ [Tags.BitsStored]: '16', [Tags.RescaleSlope]: '1e308' }), - ]) - ).toBe(Uint16Array); - }); - - it('chooses one type that represents every instance in the volume', () => { - expect(getVolumeBufferType([UNSIGNED_8, UNSIGNED_16])).toBe(Uint16Array); - expect(getVolumeBufferType([UNSIGNED_16, PUBLIC_DSC])).toBe(Float32Array); - }); -}); - -describe('getTypedArrayValueRange', () => { - it('reports what each element type holds', () => { - expect(getTypedArrayValueRange(Uint8Array)).toEqual({ min: 0, max: 255 }); - expect(getTypedArrayValueRange(Int16Array)).toEqual({ - min: -32768, - max: 32767, - }); - }); - - it('has no range to report for element types the allocator never makes', () => { - expect(getTypedArrayValueRange(Float32Array)).toBeUndefined(); - }); -}); - -describe('getBufferValueRange', () => { - it('reads the range off the buffer itself', () => { - expect(getBufferValueRange(new Uint16Array(4))).toEqual({ - min: 0, - max: 65535, - }); - expect(getBufferValueRange(new Int32Array(4))).toEqual({ - min: -(2 ** 31), - max: 2 ** 31 - 1, - }); - }); -}); - -describe('valuesFitBuffer', () => { - it('accepts a range inside the buffer type', () => { - expect(valuesFitBuffer({ min: 0, max: 255 }, new Uint16Array(1))).toBe( - true - ); - expect(valuesFitBuffer({ min: -1024, max: 3071 }, new Int16Array(1))).toBe( - true - ); - }); - - it('accepts the exact bounds of the buffer type', () => { - expect(valuesFitBuffer({ min: 0, max: 65535 }, new Uint16Array(1))).toBe( - true - ); - expect( - valuesFitBuffer({ min: -32768, max: 32767 }, new Int16Array(1)) - ).toBe(true); - }); - - it('rejects negative values in an unsigned buffer', () => { - expect( - valuesFitBuffer({ min: -2048, max: -2048 }, new Uint16Array(1)) - ).toBe(false); - }); - - it('rejects values wider than the buffer type', () => { - expect(valuesFitBuffer({ min: 0, max: 5000 }, new Uint8Array(1))).toBe( - false - ); - expect(valuesFitBuffer({ min: 0, max: 65536 }, new Uint16Array(1))).toBe( - false - ); - }); - - it('accepts a slice whose declared range would overflow but whose values do not', () => { - // A slice declaring BitsStored 16 could reach 65535, which an Int16Array - // volume cannot hold, but what it actually decoded to fits. - const declaredRange = getRescaledValueRange(UNSIGNED_16)!; - expect(valuesFitBuffer(declaredRange, new Int16Array(1))).toBe(false); - expect(valuesFitBuffer({ min: 2000, max: 2000 }, new Int16Array(1))).toBe( - true - ); - }); - - it('judges the range only, leaving fractions to samplesAreIntegral', () => { - expect(valuesFitBuffer({ min: 0.5, max: 100.5 }, new Uint16Array(1))).toBe( - true - ); - }); - - it('constrains nothing when the buffer has no integer range', () => { - expect( - valuesFitBuffer({ min: -1e30, max: 1e30 }, new Float64Array(1)) - ).toBe(true); - }); -}); - -describe('samplesAreIntegral', () => { - it('trusts integer typed arrays without scanning them', () => { - expect( - samplesAreIntegral(new Uint16Array([1, 5000]), new Uint8Array(1)) - ).toBe(true); - }); - - it('rejects fractional float samples bound for an integer buffer', () => { - expect( - samplesAreIntegral(new Float64Array([0, 0.5, 1]), new Uint16Array(1)) - ).toBe(false); - expect(samplesAreIntegral([1, 1.5], new Int16Array(1))).toBe(false); - }); - - it('accepts float samples that are whole numbers', () => { - expect( - samplesAreIntegral(new Float64Array([0, 1, 2]), new Uint16Array(1)) - ).toBe(true); - expect( - samplesAreIntegral(new Float32Array([-3, 4]), new Int16Array(1)) - ).toBe(true); - }); +const spacingOf = (layout: ReturnType) => + layout.spatialMetadata.axes.map((axis) => axis.value); - it('accepts anything bound for a float buffer', () => { - expect( - samplesAreIntegral(new Float64Array([0.5, 1e30]), new Float64Array(1)) - ).toBe(true); - }); -}); +const dimensionsOf = ({ + columns, + rows, + slices, +}: ReturnType) => [columns, rows, slices]; describe('volumeLayout', () => { it.each([ ['0.0104\\0', [1, 0.0104, 1]], ['0.0104\\NaN', [1, 0.0104, 1]], - ['0.0104', [0.0104, 0.0104, 1]], - ['0.5', [0.5, 0.5, 1]], - ['0', [1, 1, 1]], - ['-0.5', [1, 1, 1]], - ['NaN', [1, 1, 1]], - ['Infinity', [1, 1, 1]], ['0\\0.046875', [0.046875, 1, 1]], ['NaN\\0.046875', [0.046875, 1, 1]], ['0\\0', [1, 1, 1]], ])( 'preserves valid axes independently for PixelSpacing %s', (value, expected) => { - const image = layoutOf( - [volumeSource({ [Tags.PixelSpacing]: value as string })], - [1, 0, 0, 0, 1, 0] + const layout = layoutOf( + [volumeSource({ [Tags.PixelSpacing]: value })], + AXIAL ); - expect(image.getSpacing()).toEqual(expected); + expect(spacingOf(layout)).toEqual(expected); } ); it('allocates for the modality range of every member', () => { - const image = layoutOf( + const layout = layoutOf( [ positionedSource(0), positionedSource(1, { [Tags.BitsStored]: '16', [Tags.PixelRepresentation]: '0', - [Tags.RescaleSlope]: PUBLIC_DSC_SLOPE, + [Tags.RescaleSlope]: '112067.85375182', [Tags.RescaleIntercept]: '0', }), ], - [1, 0, 0, 0, 1, 0] + AXIAL ); - expect(image.bufferType).toBe(Float32Array); - expect(image.getDimensions()).toEqual([4, 3, 2]); + expect(layout.bufferType).toBe(Float32Array); + expect(dimensionsOf(layout)).toEqual([4, 3, 2]); }); it('matches ITK spacing order for single-slice images with SpacingBetweenSlices', () => { - const image = layoutOf( + const layout = layoutOf( [ volumeSource({ [Tags.PixelSpacing]: '2.5\\0.75', [Tags.SpacingBetweenSlices]: '7.25', }), ], - [1, 0, 0, 0, 1, 0] + AXIAL ); - expect(Array.from(image.getSpacing())).toEqual([0.75, 2.5, 7.25]); + expect(spacingOf(layout)).toEqual([0.75, 2.5, 7.25]); }); it('uses declared inter-frame spacing for a multi-frame volume', () => { - const image = layoutOf( + const layout = layoutOf( [ volumeSource({ [Tags.NumberOfFrames]: '32', @@ -478,14 +108,14 @@ describe('volumeLayout', () => { [Tags.SpacingBetweenSlices]: '0.1875', }), ], - [1, 0, 0, 0, 1, 0] + AXIAL ); - expect(Array.from(image.getDimensions())).toEqual([4, 3, 32]); - expect(Array.from(image.getSpacing())).toEqual([0.046875, 0.0104, 0.1875]); + expect(dimensionsOf(layout)).toEqual([4, 3, 32]); + expect(spacingOf(layout)).toEqual([0.046875, 0.0104, 0.1875]); }); - it('takes the multi-slice Z spacing from an even stack of positions', () => { - const image = layoutOf( + it('takes the multi-slice Z spacing from positions over a declared SpacingBetweenSlices', () => { + const layout = layoutOf( [ positionedSource(0, { [Tags.PixelSpacing]: '2.5\\0.75', @@ -494,60 +124,44 @@ describe('volumeLayout', () => { positionedSource(9), positionedSource(18), ], - [1, 0, 0, 0, 1, 0] + AXIAL ); - expect(Array.from(image.getSpacing())).toEqual([0.75, 2.5, 9]); - }); - - // Two 4mm runs with a hole between them, as the bilateral sagittal slabs of - // idcSeriesFixtures.ts are. Endpoint distance over slice count would call - // that a 17.33mm lattice, which describes neither run. - it('does not fit an irregular stack to a lattice its slices never sit on', () => { - const image = layoutOf( - [0, 4, 8, 48, 52].map((z) => positionedSource(z)), - [1, 0, 0, 0, 1, 0] - ); - - expect(image.getSpacing()[2]).toBeCloseTo(4, 12); + expect(spacingOf(layout)).toEqual([0.75, 2.5, 9]); }); it('orients the image along the validated slice normal', () => { - const image = layoutOf( + const layout = layoutOf( [volumeSource({ [Tags.ImageOrientationPatient]: '0\\1\\0\\0\\0\\-1' })], [0, 1, 0, 0, 0, -1] ); - expect(Array.from(image.getDirection())).toEqual([ - 0, 1, 0, 0, 0, -1, -1, 0, 0, - ]); + expect(layout.direction).toEqual([0, 1, 0, 0, 0, -1, -1, 0, 0]); }); - it('keeps the identity direction for an orientation that spans no plane', () => { - const image = layoutOf( + it('gives no direction for an orientation that spans no plane', () => { + const layout = layoutOf( [volumeSource({ [Tags.ImageOrientationPatient]: '1\\0\\0\\1\\0\\0' })], null ); - expect(Array.from(image.getDirection())).toEqual([ - 1, 0, 0, 0, 1, 0, 0, 0, 1, - ]); + expect(layout.direction).toBeNull(); }); it('leaves the Z spacing alone when no position can be read', () => { - const image = layoutOf( + const layout = layoutOf( [ volumeSource({ [Tags.ImagePositionPatient]: '' }), volumeSource({ [Tags.ImagePositionPatient]: '' }), ], - [1, 0, 0, 0, 1, 0] + AXIAL ); - expect(image.getSpacing()[2]).toBe(1); + expect(spacingOf(layout)[2]).toBe(1); }); it('takes the declared SpacingBetweenSlices when no position can be read', () => { - const image = layoutOf( + const layout = layoutOf( [ volumeSource({ [Tags.ImagePositionPatient]: '', @@ -555,60 +169,24 @@ describe('volumeLayout', () => { }), volumeSource({ [Tags.ImagePositionPatient]: '' }), ], - [1, 0, 0, 0, 1, 0] + AXIAL ); - expect(image.getSpacing()[2]).toBe(2.5); + expect(spacingOf(layout)[2]).toBe(2.5); }); it('takes the declared SpacingBetweenSlices for a multi-frame instance', () => { - const image = layoutOf( + const layout = layoutOf( [ volumeSource({ [Tags.NumberOfFrames]: '4', [Tags.SpacingBetweenSlices]: '1.5', }), ], - [1, 0, 0, 0, 1, 0] - ); - - expect(Array.from(image.getDimensions())).toEqual([4, 3, 4]); - expect(image.getSpacing()[2]).toBe(1.5); - }); - - // A tilted gantry leans every slice plane sideways of the last, so no lattice - // holds them; the extent the table stepped over is kept all the same. - it('steps a tilted gantry stack by the distance its slices advance', () => { - const theta = Math.PI / 9; - const tilted = [1, 0, 0, 0, Math.cos(theta), Math.sin(theta)]; - - const image = layoutOf( - [0, 3, 6, 9].map((z) => - positionedSource(z, { - [Tags.ImageOrientationPatient]: tilted.join('\\'), - }) - ), - tilted + AXIAL ); - expect(image.getSpacing()[2]).toBeCloseTo(3, 12); - expect(image.getDirection()[5]).toBeCloseTo(Math.sin(theta), 12); + expect(dimensionsOf(layout)).toEqual([4, 3, 4]); + expect(spacingOf(layout)[2]).toBe(1.5); }); }); - -const IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - -/** Plans the members' stack as the collection planner would, then lays it out. */ -function layoutOf(sources: VolumeSource[], orientation: number[] | null) { - const reconstruction = reconstructVolume( - sources.map((item) => readGeometryFacts(item.dataset)), - sliceNormalOf(orientation) - ); - const layout = volumeLayout(sources, orientation, reconstruction); - return { - bufferType: layout.bufferType, - getDimensions: () => [layout.columns, layout.rows, layout.slices], - getSpacing: () => layout.spatialMetadata.axes.map((axis) => axis.value), - getDirection: () => layout.direction ?? IDENTITY, - }; -} diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts index 117f2c40c..cb9e65415 100644 --- a/packages/dicom/core/volume/allocateVolume.ts +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -1,13 +1,8 @@ import type { Instance } from '../instance/readInstance'; import type { ImageCollectionUpdate } from '../collections/instanceRegistry'; -import type { DicomCollection } from '../collections/planDicomCollections'; -import type { Reconstruction } from '../collections/reconstructVolume'; import type { SpatialMetadata } from '../metadata/spatialMetadata'; import type { VolumeBuffer } from './pixelFormat'; -import { - planVolumeAllocation, - type IrregularGeometryPolicy, -} from './volumeLayout'; +import { planVolumeAllocation } from './volumeLayout'; type Vector3 = readonly [number, number, number]; @@ -16,11 +11,8 @@ type Vector3 = readonly [number, number, number]; * `data` and `loaded`, which only `loadVolume` writes. */ export type Volume = Readonly<{ - id: string; - collection: DicomCollection; - /** Planned order; `reconstruction.slots[i]` is member i's first slice. */ + /** Planned order; in a multi-file volume member i fills slice i. */ members: readonly Instance[]; - reconstruction: Reconstruction; /** Columns, rows, slices. */ dimensions: Vector3; components: number; @@ -36,16 +28,12 @@ export type Volume = Readonly<{ loaded: Uint8Array; }>; -export type AllocateVolumeOptions = { - irregularGeometry?: IrregularGeometryPolicy; -}; - const IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1]; /** The slices one member fills: one per file, or every frame of a lone instance. */ export const memberSlices = (volume: Volume, member: number) => volume.members.length > 1 - ? [volume.reconstruction.slots[member]] + ? [member] : Array.from({ length: volume.dimensions[2] }, (_, slice) => slice); export const memberLoaded = (volume: Volume, member: number) => @@ -98,23 +86,18 @@ function copyDecoded(volume: Volume, previous: Volume) { * again. */ export function allocateVolume( - update: Pick, - options: AllocateVolumeOptions = {}, + update: Pick, previous?: Volume ) { - const { id, collection, members } = update; - const { reconstruction, layout, warnings } = planVolumeAllocation( + const { collection, members } = update; + const { layout, warnings } = planVolumeAllocation( members, collection.orientation, - collection.reconstruction, - options.irregularGeometry ?? 'preserve-order' + collection.reconstruction ); const { columns, rows, slices, samplesPerPixel } = layout; const volume: Volume = Object.freeze({ - id, - collection, members: Object.freeze([...members]), - reconstruction, dimensions: [columns, rows, slices] as const, components: samplesPerPixel, origin: (layout.origin ?? [0, 0, 0]) as unknown as Vector3, diff --git a/packages/dicom/core/volume/loadVolume.ts b/packages/dicom/core/volume/loadVolume.ts index 3c9da58f1..781a0984c 100644 --- a/packages/dicom/core/volume/loadVolume.ts +++ b/packages/dicom/core/volume/loadVolume.ts @@ -1,15 +1,10 @@ import type { DicomRuntime } from '../runtime/createDicomRuntime'; -import type { Instance } from '../instance/readInstance'; import { getDatasetTag } from '../metadata/datasetAccess'; import { Tags } from '../metadata/dicomTags'; -import { abortError, linkedController, numberOr } from '../utils'; +import { abortError, linkedController } from '../utils'; import { readBytes } from '../source/byteSource'; import { planDecode, type DecoderTable } from '../pixels/decoderTable'; -import { - frameCount, - type DecodedPixels, - type DecodeUnit, -} from '../pixels/pixelDecoder'; +import type { DecodedPixels, DecodeUnit } from '../pixels/pixelDecoder'; import { getPixelFormat, type VolumeBufferConstructor } from './pixelFormat'; import { componentRanges, @@ -18,12 +13,7 @@ import { sliceLength, type Volume, } from './allocateVolume'; -import { - assertSamplesRepresentable, - assertSingleFramePerFile, - assertUnitFits, - type UnitShape, -} from './pixelValidation'; +import { assertSamplesRepresentable, assertUnitFits } from './pixelValidation'; import { pickNextSlot } from './slotOrder'; /** [xMin, xMax, yMin, yMax, zMin, zMax], inclusive, as vtk.js extents are. */ @@ -57,6 +47,19 @@ export type LoadVolumeOptions = { type Unit = DecodeUnit & Readonly<{ member: number; slices: readonly number[]; slot: number }>; +/** How long decodes may run back to back before the thread is handed back. */ +const DECODE_RUN_MS = 8; + +const nextTask = () => + new Promise((resolve) => { + const { port1, port2 } = new MessageChannel(); + port1.onmessage = () => { + port1.close(); + resolve(); + }; + port2.postMessage(null); + }); + const ensureError = (error: unknown) => error instanceof Error ? error : new Error(String(error)); @@ -94,26 +97,6 @@ const unitName = (volume: Volume, unit: Unit) => { : `${name}, frame ${unit.firstFrame}`; }; -function headerShape(instance: Instance): UnitShape { - const value = (tag: string, fallback: number) => - numberOr(getDatasetTag(instance.dataset, tag), fallback); - const [columns, rows] = [value(Tags.Columns, 0), value(Tags.Rows, 0)]; - const components = value(Tags.SamplesPerPixel, 1); - const frames = frameCount(instance); - return { - size: [columns, rows, frames], - components, - samples: columns * rows * frames * components, - }; -} - -const roomFor = (volume: Volume, frames: number) => ({ - dims: volume.dimensions, - components: volume.components, - frames, - multiFile: volume.members.length > 1, -}); - /** A Float32 volume holds rounded values, so the range it reports is rounded too. */ const storedRange = ( volume: Volume, @@ -126,13 +109,31 @@ const storedRange = ( ]); }; +/** A read or decode failure naming what it lost, with the thrown value as `cause`. */ +const unitFailure = ( + where: string, + stage: 'read' | 'decoded', + cause: unknown +) => { + const culprit = stage === 'read' ? 'source' : 'decoder'; + const detail = + (cause instanceof Error && cause.message) || + `the ${culprit} failed without a message`; + return new Error(`${where} could not be ${stage}: ${detail}`, { cause }); +}; + /** Validates decoded pixels and writes them into the buffer. */ function write(volume: Volume, unit: Unit, pixels: DecodedPixels) { const where = unitName(volume, unit); const { data, size, components } = pixels; assertUnitFits( { size, components, samples: data.length }, - roomFor(volume, unit.frames), + { + dims: volume.dimensions, + components: volume.components, + frames: unit.frames, + multiFile: volume.members.length > 1, + }, where ); const range = pixels.range ?? componentRanges(data, volume.components); @@ -180,14 +181,14 @@ function planMember(volume: Volume, member: number, decoders: DecoderTable) { const slices = memberSlices(volume, member); const target = volume.data.constructor as VolumeBufferConstructor; const planned = planDecode(decoders, instance, target); - if ('error' in planned) throw planned.error; - const where = memberName(volume, member); - const header = headerShape(instance); - assertSingleFramePerFile(header.size[2], volume.members.length, where); - assertUnitFits(header, roomFor(volume, slices.length), where); + if ('error' in planned) + throw new Error( + `${memberName(volume, member)} cannot be decoded: ${planned.error.message}`, + { cause: planned.error } + ); if (!tiles(planned.units, slices.length)) throw new Error( - `${planned.decoder.name} planned units that do not cover frames 0 to ${slices.length - 1} of ${where} exactly once` + `${planned.decoder.name} planned units that do not cover frames 0 to ${slices.length - 1} of ${memberName(volume, member)} exactly once` ); return planned.units.map((unit): Unit => { const covered = slices.slice( @@ -217,6 +218,12 @@ function planUnits(volume: Volume, decoders: DecoderTable) { return { units, failures }; } +// A decoded unit's extent spans exactly the slices it wrote. +const markLoaded = (volume: Volume, update: VolumeUpdate) => { + if ('range' in update) + volume.loaded.fill(1, update.extent[4], update.extent[5] + 1); +}; + /** The first slice of the middle member, the default focus. */ export const middleSlot = (volume: Volume) => memberSlices(volume, Math.floor(volume.members.length / 2))[0]; @@ -229,9 +236,6 @@ type Loader = { readAhead: number; }; -/** An update waiting to be yielded, with the slices it marks loaded then. */ -type Settled = Readonly<{ update: VolumeUpdate; slices: readonly number[] }>; - /** * Starts reads and decodes whenever one settles: decodes first, up to the * decode concurrency, then reads while fewer than `readAhead` units are being @@ -244,10 +248,7 @@ function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { const ready = new Map(); /** Members whose source has not yet shown it honours ranges. */ const probing = new Set(); - const updates: Settled[] = failures.map((update) => ({ - update, - slices: [], - })); + const updates = [...failures]; let reading = 0; let decoding = 0; let wake: (() => void) | undefined; @@ -262,18 +263,16 @@ function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { }); stopped.addEventListener('abort', notify, { once: true }); - const settle = (settled: Settled) => { - if (!stopped.aborted) updates.push(settled); + const settle = (update: VolumeUpdate) => { + if (!stopped.aborted) updates.push(update); notify(); }; - const failed = (lost: Unit[], error: unknown): Settled => ({ - update: failure( + const failed = (lost: Unit[], error: unknown) => + failure( volume, lost.flatMap((unit) => unit.slices), error - ), - slices: [], - }); + ); const next = (slots: Iterable) => pickNextSlot(slots, focus()); const sourceOf = (unit: Unit) => volume.members[unit.member].source; const rangeSupport = (unit: Unit) => @@ -318,7 +317,13 @@ function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { batch.forEach((each, index) => ready.set(each.slot, { unit: each, bytes: bytes[index] }) ), - (error) => settle(failed(batch, error)) + (error) => { + const where = + batch.length > 1 + ? memberName(volume, unit.member) + : unitName(volume, unit); + settle(failed(batch, unitFailure(where, 'read', error))); + } ) .finally(() => { if (probe) probing.delete(unit.member); @@ -327,27 +332,51 @@ function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { }); }; - const written = (unit: Unit, pixels: DecodedPixels): Settled => { + const written = (unit: Unit, pixels: DecodedPixels): VolumeUpdate => { try { - return { update: write(volume, unit, pixels), slices: unit.slices }; + return write(volume, unit, pixels); } catch (error) { return failed([unit], error); } }; + // A decode that returns at once lets its successor start in the same task, + // so a batch of frames would hold the thread until all are decoded. While + // pump starts what follows a decode, `inherited` is when that run began. + let inherited: number | undefined; + const startDecode = (slot: number) => { const { unit, bytes } = ready.get(slot)!; ready.delete(slot); decoding += 1; - (async () => unit.decode(bytes, stopped))() + let runStarted = inherited; + Promise.resolve() + .then(async () => { + if ( + runStarted !== undefined && + performance.now() - runStarted > DECODE_RUN_MS + ) { + await nextTask(); + runStarted = undefined; + } + runStarted ??= performance.now(); + stopped.throwIfAborted(); + const pixels = unit.decode(bytes, stopped); + // An awaited decode resumes in a task of its own. + if (pixels instanceof Promise) runStarted = undefined; + return pixels; + }) .then( (pixels) => (stopped.aborted ? undefined : written(unit, pixels)), - (error) => failed([unit], error) + (error) => + failed([unit], unitFailure(unitName(volume, unit), 'decoded', error)) ) - .then((settled) => { + .then((update) => { decoding -= 1; - if (settled) settle(settled); + if (update) settle(update); + inherited = runStarted; pump(); + inherited = undefined; }); }; @@ -407,10 +436,8 @@ export async function* loadVolume( for (;;) { const next = stopped.aborted ? undefined : loader.updates.shift(); if (next) { - next.slices.forEach((slice) => { - volume.loaded[slice] = 1; - }); - yield next.update; + markLoaded(volume, next); + yield next; } else if (stopped.aborted || loader.done()) return; else await loader.changed(); } diff --git a/packages/dicom/core/volume/nmGeometry.ts b/packages/dicom/core/volume/nmGeometry.ts index a4bf6ee0f..ce72c16eb 100644 --- a/packages/dicom/core/volume/nmGeometry.ts +++ b/packages/dicom/core/volume/nmGeometry.ts @@ -14,7 +14,6 @@ export function nmGeometry(metadata: DicomDataset) { const reconstruction: Reconstruction = { kind: 'regular', sliceSpacing: nm.sliceSpacing ? Math.abs(nm.sliceSpacing) : null, - slots: [0], }; return { ...geometry, diff --git a/packages/dicom/core/volume/pixelFormat.ts b/packages/dicom/core/volume/pixelFormat.ts index c37447cf2..224eb0cf9 100644 --- a/packages/dicom/core/volume/pixelFormat.ts +++ b/packages/dicom/core/volume/pixelFormat.ts @@ -1,21 +1,10 @@ import type { DicomDataset } from '../metadata/dicomDataset'; -import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; import { getFrameTag } from '../metadata/functionalGroups'; import { readModalityRescale } from '../metadata/modalityRescale'; +import { frameCount } from '../pixels/pixelDecoder'; import { numberOr } from '../utils'; -const BitsStoredTag = '00280101'; -const PixelRepresentationTag = '00280103'; -const NumberOfFramesTag = '00280008'; - -function getBitStorageSize(num: number, signed: boolean) { - const addSignedBit = signed ? 1 : 0; - const val = num < 0 ? -num : num + 1; // range shift for log2 - const nbits = Math.ceil(Math.log2(val) + addSignedBit); - // round up to a word size - return 2 ** Math.ceil(Math.log2(nbits)); -} - type IntegerArrayConstructor = | typeof Int8Array | typeof Uint8Array @@ -30,32 +19,27 @@ export type VolumeBufferConstructor = | typeof Float64Array; export type VolumeBuffer = InstanceType; -const TYPED_ARRAY_VALUE_RANGES = new Map< +// In the order a range is matched: unsigned before signed, narrow before wide. +const INTEGER_VALUE_RANGES = new Map< IntegerArrayConstructor, { min: number; max: number } >([ - [Int8Array, { min: -(2 ** 7), max: 2 ** 7 - 1 }], [Uint8Array, { min: 0, max: 2 ** 8 - 1 }], - [Int16Array, { min: -(2 ** 15), max: 2 ** 15 - 1 }], [Uint16Array, { min: 0, max: 2 ** 16 - 1 }], - [Int32Array, { min: -(2 ** 31), max: 2 ** 31 - 1 }], [Uint32Array, { min: 0, max: 2 ** 32 - 1 }], + [Int8Array, { min: -(2 ** 7), max: 2 ** 7 - 1 }], + [Int16Array, { min: -(2 ** 15), max: 2 ** 15 - 1 }], + [Int32Array, { min: -(2 ** 31), max: 2 ** 31 - 1 }], ]); -/** - * The values a buffer of the given element type can hold without wrapping. - * Undefined for element types the allocator never produces, floats included. - */ -export function getTypedArrayValueRange(ctor: unknown) { - return TYPED_ARRAY_VALUE_RANGES.get(ctor as IntegerArrayConstructor); -} - /** * The values `buffer` can hold without wrapping, or undefined if its element * type has no fixed integer range to enforce. */ export function getBufferValueRange(buffer: ArrayBufferView) { - return getTypedArrayValueRange(buffer.constructor); + return INTEGER_VALUE_RANGES.get( + buffer.constructor as IntegerArrayConstructor + ); } /** @@ -93,23 +77,6 @@ export function samplesAreIntegral( ); } -export function getTypedArrayForDataRange(min: number, max: number) { - if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max)) - throw new Error('Input must be integers'); - - const isSigned = min < 0; - const nbits = getBitStorageSize( - Math.abs(min) > Math.abs(max) ? min : max, - isSigned - ); - - if (nbits <= 8) return isSigned ? Int8Array : Uint8Array; - if (nbits <= 16) return isSigned ? Int16Array : Uint16Array; - if (nbits <= 32) return isSigned ? Int32Array : Uint32Array; - - throw new Error(`Cannot handle ${nbits}-bit sized ranges`); -} - /** * The tags that decide what values an instance decodes to. * @@ -122,8 +89,8 @@ export function getPixelFormat( ) { const valueOf = (tag: string) => getFrameTag(metadata, tag, frameIndex); return { - bitsStored: numberOr(valueOf(BitsStoredTag), 0), - pixelRepresentation: numberOr(valueOf(PixelRepresentationTag), 0), + bitsStored: numberOr(valueOf(Tags.BitsStored), 0), + pixelRepresentation: numberOr(valueOf(Tags.PixelRepresentation), 0), ...readModalityRescale(metadata, frameIndex), }; } @@ -202,19 +169,12 @@ function fractionalBufferType(usable: UsableFormat[]) { } function integralBufferType(usable: UsableFormat[]): VolumeBufferConstructor { - if ( - usable.some( - ({ range }) => - !Number.isSafeInteger(range.min) || !Number.isSafeInteger(range.max) - ) - ) - return Float64Array; const min = Math.min(...usable.map(({ range }) => range.min)); const max = Math.max(...usable.map(({ range }) => range.max)); - const exceedsSigned32 = min < 0 && (min < -(2 ** 31) || max > 2 ** 31 - 1); - const exceedsUnsigned32 = min >= 0 && max > 2 ** 32 - 1; - if (exceedsSigned32 || exceedsUnsigned32) return Float64Array; - const type = getTypedArrayForDataRange(min, max); + const fit = [...INTEGER_VALUE_RANGES].find( + ([, held]) => min >= held.min && max <= held.max + ); + const type = fit?.[0] ?? Float64Array; const wide = type === Int32Array || type === Uint32Array; return wide && float32KeepsIntegers({ min, max }) ? Float32Array : type; } @@ -235,7 +195,9 @@ export function getVolumeBufferType( : []; }); if (usable.length === 0) - throw new Error('No instance declares a finite modality rescale range'); + throw new Error( + 'No instance declares Bits Stored and a finite modality rescale range' + ); // vtk.js uploads only 8/16-bit integer and float32 buffers without converting the whole volume. return usable.some(({ format }) => !isIntegralRescale(format)) @@ -245,7 +207,6 @@ export function getVolumeBufferType( /** One format per frame, since enhanced instances calibrate frames separately. */ export const instancePixelFormats = (dataset: DicomDataset) => - Array.from( - { length: numberOr(getDatasetTag(dataset, NumberOfFramesTag), 1) }, - (_, index) => getPixelFormat(dataset, index) + Array.from({ length: frameCount(dataset) }, (_, index) => + getPixelFormat(dataset, index) ); diff --git a/packages/dicom/core/volume/pixelValidation.ts b/packages/dicom/core/volume/pixelValidation.ts index 9cb9676ea..c94ec69bd 100644 --- a/packages/dicom/core/volume/pixelValidation.ts +++ b/packages/dicom/core/volume/pixelValidation.ts @@ -59,19 +59,6 @@ export function assertSamplesRepresentable( } } -export function assertSingleFramePerFile( - frames: number, - count: number, - where: string -) { - if (frames > 1 && count > 1) { - throw new Error( - `Loading a single volume from multiple DICOM files where individual files contain multiple frames is not supported. ` + - `${where} contains ${frames} frames.` - ); - } -} - // One frame per file in a multi-file volume, or any run of a lone instance's // frames. A decoded unit has to fill its slices exactly. export function assertUnitFits( diff --git a/packages/dicom/core/volume/ultrasoundSpacing.ts b/packages/dicom/core/volume/ultrasoundSpacing.ts index cdeb59d38..811d14b6e 100644 --- a/packages/dicom/core/volume/ultrasoundSpacing.ts +++ b/packages/dicom/core/volume/ultrasoundSpacing.ts @@ -16,20 +16,18 @@ const regionNotes = (count: number) => ] : []; -/** The display spacing is `axes[n].value` of the returned metadata. */ +/** The display spacing is `axes[n].value` of the returned metadata; warnings are [title, details]. */ export function applyUltrasoundSpacing( spatialMetadata: SpatialMetadata, - sources: readonly VolumeSource[], - warn: (title: string, details: string) => void -): SpatialMetadata { - if (getDatasetModality(sources[0].dataset) !== 'US') return spatialMetadata; + sources: readonly VolumeSource[] +): { spatialMetadata: SpatialMetadata; warnings: Array<[string, string]> } { + const unchanged = { spatialMetadata, warnings: [] }; + if (getDatasetModality(sources[0].dataset) !== 'US') return unchanged; // Ultrasound DICOMs are typically a single multi-frame instance, so the // first region table applies to the whole image. - const regions = sources[0]?.ultrasoundRegions; - if (!regions?.region) return spatialMetadata; - - warnMultipleRegions(regions.regionCount); + const regions = sources[0].ultrasoundRegions; + if (!regions?.region) return unchanged; const { region } = regions; const notes = [...spatialMetadata.notes, ...regionNotes(regions.regionCount)]; @@ -39,47 +37,42 @@ export function applyUltrasoundSpacing( // cm and the other is seconds, or unitless) the metadata can't be trusted // as a 2D physical spacing, so leave the default 1mm fallback in place. if (xFactor === null || yFactor === null) { - console.warn( - `Ultrasound spacing not applied: PhysicalUnitsXDirection=${region.physicalUnitsXDirection}, PhysicalUnitsYDirection=${region.physicalUnitsYDirection}; only code 3 (cm) is converted to mm.` - ); notes.push( 'The first ultrasound region does not declare two spatial axes; its calibration is not applied.' ); - return { ...spatialMetadata, notes }; + return { spatialMetadata: { ...spatialMetadata, notes }, warnings: [] }; } const spacingX = region.physicalDeltaX * xFactor; const spacingY = region.physicalDeltaY * yFactor; if (!isUsableSpacing(spacingX) || !isUsableSpacing(spacingY)) { - warn( - 'Invalid ultrasound calibration', - `The ultrasound region declares PhysicalDeltaX=${region.physicalDeltaX} and PhysicalDeltaY=${region.physicalDeltaY}. Measurements use the image pixel spacing instead.` - ); notes.push( 'The first ultrasound region has unusable physical deltas; its calibration is not applied.' ); - return { ...spatialMetadata, notes }; + return { + spatialMetadata: { ...spatialMetadata, notes }, + warnings: [ + [ + 'Invalid ultrasound calibration', + `The ultrasound region declares PhysicalDeltaX=${region.physicalDeltaX} and PhysicalDeltaY=${region.physicalDeltaY}. Measurements use the image pixel spacing instead.`, + ], + ], + }; } notes.push( 'Ultrasound physical spacing applies within the calibrated region, not necessarily the entire image.' ); return { - ...spatialMetadata, - axes: [ - physicalSpacing(spacingX, 'Ultrasound region (cm converted to mm)'), - physicalSpacing(spacingY, 'Ultrasound region (cm converted to mm)'), - spatialMetadata.axes[2], - ], - notes, + spatialMetadata: { + ...spatialMetadata, + axes: [ + physicalSpacing(spacingX, 'Ultrasound region (cm converted to mm)'), + physicalSpacing(spacingY, 'Ultrasound region (cm converted to mm)'), + spatialMetadata.axes[2], + ], + notes, + }, + warnings: [], }; } - -function warnMultipleRegions(count: number) { - // vtkImageData has one global spacing even when the acquisition contains - // regions with different physical calibration. - if (count > 1) - console.warn( - `Ultrasound image has ${count} regions; only the first region's physical spacing is applied. Multi-region (e.g. dual-pane B-mode + Doppler) ultrasound is not fully supported.` - ); -} diff --git a/packages/dicom/core/volume/volumeLayout.ts b/packages/dicom/core/volume/volumeLayout.ts index 1116cae65..96181b683 100644 --- a/packages/dicom/core/volume/volumeLayout.ts +++ b/packages/dicom/core/volume/volumeLayout.ts @@ -1,10 +1,8 @@ import type { DicomDataset } from '../metadata/dicomDataset'; import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; -import { - reconstructInstances, - type Reconstruction, -} from '../collections/reconstructVolume'; +import type { Reconstruction } from '../collections/reconstructVolume'; import { readDatasetDetails } from '../collections/datasetDetails'; import { declaredSpacing, @@ -14,47 +12,34 @@ import { } from '../metadata/spatialMetadata'; import { getFrameTag } from '../metadata/functionalGroups'; import type { UltrasoundRegions } from '../metadata/ultrasoundRegion'; +import { frameCount } from '../pixels/pixelDecoder'; import { numberOr } from '../utils'; import { nmGeometry } from './nmGeometry'; import { getVolumeBufferType, instancePixelFormats } from './pixelFormat'; import { applyUltrasoundSpacing } from './ultrasoundSpacing'; -const SpacingBetweenSlicesTag = '00180088'; -const RowsTag = '00280010'; -const ColumnsTag = '00280011'; -const SamplesPerPixelTag = '00280002'; -const NumberOfFrames = '00280008'; - /** What allocation reads from one member: its header and ultrasound regions. */ export type VolumeSource = { dataset: DicomDataset; ultrasoundRegions?: UltrasoundRegions | null; }; -/** Preserve acquisition order and its fallback spacing, or require a regular lattice. */ -export type IrregularGeometryPolicy = 'preserve-order' | 'reject'; - const isPositiveFiniteNumber = (value: number) => Number.isFinite(value) && value > 0; -const frameCountOf = (dataset: DicomDataset) => - numberOr(getDatasetTag(dataset, NumberOfFrames), 1); - -function assertRegularGeometry( - reconstruction: Reconstruction, - policy: IrregularGeometryPolicy -) { - if (reconstruction.kind === 'irregular' && policy === 'reject') - throw new Error( - `Cannot allocate irregular DICOM geometry: ${reconstruction.reason}` - ); -} - -const instanceGeometry = (dataset: DicomDataset, count: number) => { +// One instance alone places its own frames: NM by its detector, an enhanced +// object by its functional groups. +const frameGeometry = (sources: readonly VolumeSource[]) => { + if (sources.length !== 1) return { frames: null }; + const { dataset } = sources[0]; const nm = nmGeometry(dataset); - if (nm) return nm; - if (count < 2) return null; - return readDatasetDetails(dataset).frameGeometry; + if (nm) return { frames: nm, sliceSpacingSource: nm.sliceSpacingSource }; + return { + frames: + frameCount(dataset) < 2 + ? null + : readDatasetDetails(dataset).frameGeometry, + }; }; function allocationDirection( @@ -68,56 +53,29 @@ function allocationDirection( function allocationGeometry( sources: readonly VolumeSource[], orientation: number[] | null, - reconstruction: Reconstruction, - policy: IrregularGeometryPolicy + reconstruction: Reconstruction ) { const { dataset } = sources[0]; - const frames = - sources.length === 1 - ? instanceGeometry(dataset, frameCountOf(dataset)) - : null; + const { frames, sliceSpacingSource = 'ImagePositionPatient' } = + frameGeometry(sources); const geometry = frames ?? readGeometryFacts(dataset); - const plan = frames?.reconstruction ?? reconstruction; - assertRegularGeometry(plan, policy); const effectiveOrientation = orientation ?? geometry.orientation; return { ...geometry, - reconstruction: plan, - sliceSpacingSource: frames?.sliceSpacingSource ?? 'ImagePositionPatient', + reconstruction: frames?.reconstruction ?? reconstruction, + sliceSpacingSource, direction: allocationDirection(effectiveOrientation, frames?.direction), }; } -function assertSliceSlots(slots: number[], count: number) { - if ( - slots.length !== count || - new Set(slots).size !== count || - slots.some((slot) => !Number.isSafeInteger(slot) || slot < 0) || - (count > 0 && slots[0] !== 0) - ) - throw new Error( - 'Reconstruction must map each instance to one distinct nonnegative slice slot, starting at zero' - ); -} - -function allocationShape( - sources: readonly VolumeSource[], - reconstruction: Reconstruction -) { - const valueOf = (tag: string) => getDatasetTag(sources[0].dataset, tag); - const numberOfFrames = numberOr(valueOf(NumberOfFrames), 1); - if (numberOfFrames > 1 && sources.length > 1) - throw new Error( - 'A multi-frame instance cannot share a volume with other instances' - ); +function allocationShape(sources: readonly VolumeSource[]) { + const { dataset } = sources[0]; + const valueOf = (tag: string) => getDatasetTag(dataset, tag); return { - rows: numberOr(valueOf(RowsTag), 0), - columns: numberOr(valueOf(ColumnsTag), 0), - samplesPerPixel: numberOr(valueOf(SamplesPerPixelTag), 1), - slices: - sources.length > 1 - ? Math.max(...reconstruction.slots) + 1 - : numberOfFrames, + rows: numberOr(valueOf(Tags.Rows), 0), + columns: numberOr(valueOf(Tags.Columns), 0), + samplesPerPixel: numberOr(valueOf(Tags.SamplesPerPixel), 1), + slices: sources.length > 1 ? sources.length : frameCount(dataset), }; } @@ -168,7 +126,7 @@ function allocationSpatialMetadata( sliceSpacingSource === 'ImagePositionPatient' ? 'derived' : 'declared' ) : declaredSpacing( - getFrameTag(metadata, SpacingBetweenSlicesTag), + getFrameTag(metadata, Tags.SpacingBetweenSlices), 'SpacingBetweenSlices' ); return { @@ -191,20 +149,12 @@ function allocationSpatialMetadata( export function volumeLayout( sources: readonly VolumeSource[], orientation: number[] | null, - reconstruction: Reconstruction, - irregularGeometry: IrregularGeometryPolicy = 'preserve-order' + reconstruction: Reconstruction ) { if (sources.length === 0) throw new Error('Cannot allocate an image from zero instances'); - assertRegularGeometry(reconstruction, irregularGeometry); - assertSliceSlots(reconstruction.slots, sources.length); - const shape = allocationShape(sources, reconstruction); - const geometry = allocationGeometry( - sources, - orientation, - reconstruction, - irregularGeometry - ); + const shape = allocationShape(sources); + const geometry = allocationGeometry(sources, orientation, reconstruction); return { ...shape, origin: geometry.position, @@ -216,42 +166,16 @@ export function volumeLayout( }; } -const reconstructionFor = ( - sources: readonly VolumeSource[], - orientation: number[] | null, - supplied: Reconstruction | undefined -) => { - const needsFrameGeometry = - sources.length === 1 && frameCountOf(sources[0].dataset) > 1; - return supplied && !needsFrameGeometry - ? supplied - : reconstructInstances( - sources.map((source) => readDatasetDetails(source.dataset).facts), - sliceNormalOf(orientation), - supplied - ); -}; - -/** Plans an allocation for the planned members of an image collection. */ +/** Lays out the planned members of an image collection, with allocation warnings. */ export function planVolumeAllocation( sources: readonly VolumeSource[], orientation: number[] | null, - supplied: Reconstruction | undefined, - policy: IrregularGeometryPolicy + reconstruction: Reconstruction ) { - if (sources.length === 0) - throw new Error('Cannot allocate an image from zero instances'); - const reconstruction = reconstructionFor(sources, orientation, supplied); - const warnings: Array<[string, string]> = []; - const layout = volumeLayout(sources, orientation, reconstruction, policy); - const spatialMetadata = applyUltrasoundSpacing( + const layout = volumeLayout(sources, orientation, reconstruction); + const { spatialMetadata, warnings } = applyUltrasoundSpacing( layout.spatialMetadata, - sources, - (...warning) => warnings.push(warning) + sources ); - return { - reconstruction, - layout: { ...layout, spatialMetadata }, - warnings, - }; + return { layout: { ...layout, spatialMetadata }, warnings }; } diff --git a/packages/dicom/vtk/__tests__/thumbnail.spec.ts b/packages/dicom/vtk/__tests__/thumbnail.spec.ts index 2975ed3c7..66e827c41 100644 --- a/packages/dicom/vtk/__tests__/thumbnail.spec.ts +++ b/packages/dicom/vtk/__tests__/thumbnail.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { sliceToThumbnail, THUMBNAIL_MAX_SIZE } from '../thumbnail'; +import { sliceToThumbnail } from '../thumbnail'; const bytes = (slice: { data: Uint8Array }) => Array.from(slice.data); @@ -9,8 +9,8 @@ describe('sliceToThumbnail', () => { data: [0, 10, 20, 30, 40, 50, 60, 70], width: 4, height: 2, + components: 1, range: [0, 70], - maxSize: 4, }); expect(slice.width).toBe(4); @@ -24,8 +24,8 @@ describe('sliceToThumbnail', () => { data: [0, 10, 15, 20, 30], width: 5, height: 1, + components: 1, range: [10, 20], - maxSize: 8, }); expect(bytes(slice)).toEqual([0, 0, 128, 255, 255]); @@ -36,8 +36,8 @@ describe('sliceToThumbnail', () => { data: [1, 5, 9], width: 3, height: 1, + components: 1, range: [5, 5], - maxSize: 8, }); expect(bytes(slice)).toEqual([0, 0, 0]); @@ -48,26 +48,27 @@ describe('sliceToThumbnail', () => { data: [NaN, Infinity, -Infinity, 1], width: 4, height: 1, + components: 1, range: [0, 1], - maxSize: 8, }); expect(bytes(slice)).toEqual([0, 0, 0, 255]); }); - it('downsamples both axes by one stride', () => { + it('downsamples both axes by one stride to at most 256 on the longer side', () => { + const width = 512; const slice = sliceToThumbnail({ - data: [0, 10, 20, 30, 40, 50, 60, 70], - width: 4, + data: Uint16Array.from({ length: width * 2 }, (_, index) => index), + width, height: 2, - range: [0, 70], - maxSize: 2, + components: 1, + range: [0, 255], }); - expect(slice.width).toBe(2); + expect(slice.width).toBe(256); expect(slice.height).toBe(1); - // The samples at (0,0) and (2,0), the corners of the 2x2 source blocks. - expect(bytes(slice)).toEqual([0, 73]); + // Every second sample of the first row, the corners of the 2x2 blocks. + expect(bytes(slice).slice(0, 4)).toEqual([0, 2, 4, 6]); }); it('keeps every sample of a slice that already fits', () => { @@ -75,6 +76,7 @@ describe('sliceToThumbnail', () => { data: [0, 1, 2, 3], width: 2, height: 2, + components: 1, range: [0, 3], }); @@ -83,20 +85,6 @@ describe('sliceToThumbnail', () => { expect(slice.data).toHaveLength(4); }); - it('bounds a large slice by the default maximum size', () => { - const width = THUMBNAIL_MAX_SIZE * 2; - const slice = sliceToThumbnail({ - data: new Uint16Array(width).fill(1), - width, - height: 1, - range: [0, 1], - }); - - expect(slice.width).toBe(THUMBNAIL_MAX_SIZE); - expect(slice.height).toBe(1); - expect(slice.data).toHaveLength(THUMBNAIL_MAX_SIZE); - }); - it('samples RGB luminance for color slices', () => { const slice = sliceToThumbnail({ data: [255, 0, 0, 0, 255, 0, 0, 0, 255], @@ -104,15 +92,8 @@ describe('sliceToThumbnail', () => { height: 1, components: 3, range: [0, 255], - maxSize: 8, }); expect(bytes(slice)).toEqual([76, 150, 29]); }); - - it('does not mutate the samples it reads', () => { - const data = [0, 10, 20, 30]; - sliceToThumbnail({ data, width: 4, height: 1, range: [0, 30] }); - expect(data).toEqual([0, 10, 20, 30]); - }); }); diff --git a/packages/dicom/vtk/__tests__/volumeImage.spec.ts b/packages/dicom/vtk/__tests__/volumeImage.spec.ts index 18f7e08d5..fad7666b3 100644 --- a/packages/dicom/vtk/__tests__/volumeImage.spec.ts +++ b/packages/dicom/vtk/__tests__/volumeImage.spec.ts @@ -122,4 +122,20 @@ describe('vtk volume adapter', () => { expect(Array.from(sliceThumbnail(image, 0).data)).toEqual([0, 255, 50]); image.delete(); }); + + it('windows a color slice to its own luminance, whatever the other slices hold', () => { + const image = vtkImageData.newInstance(); + image.setDimensions(2, 1, 2); + image.getPointData().setScalars( + vtkDataArray.newInstance({ + numberOfComponents: 3, + values: new Uint8Array([ + 0, 0, 0, 100, 100, 100, 255, 255, 255, 0, 0, 0, + ]), + }) + ); + + expect(Array.from(sliceThumbnail(image, 0).data)).toEqual([0, 255]); + image.delete(); + }); }); diff --git a/packages/dicom/vtk/thumbnail.ts b/packages/dicom/vtk/thumbnail.ts index 8433aa63f..319f88737 100644 --- a/packages/dicom/vtk/thumbnail.ts +++ b/packages/dicom/vtk/thumbnail.ts @@ -10,13 +10,12 @@ type SliceToThumbnailInput = { width: number; height: number; // Samples per pixel; RGB samples are converted to luminance. - components?: number; + components: number; // The window mapped onto 0..255. range: readonly [number, number]; - maxSize?: number; }; -export const THUMBNAIL_MAX_SIZE = 256; +const THUMBNAIL_MAX_SIZE = 256; const BYTE_MAX = 255; @@ -46,15 +45,17 @@ export function sliceToThumbnail({ data, width, height, - components = 1, + components, range, - maxSize = THUMBNAIL_MAX_SIZE, }: SliceToThumbnailInput): ThumbnailSlice { const [low, high] = range; const span = high - low; // One integer stride on both axes, so the aspect ratio survives. - const stride = Math.max(1, Math.ceil(Math.max(width, height) / maxSize)); + const stride = Math.max( + 1, + Math.ceil(Math.max(width, height) / THUMBNAIL_MAX_SIZE) + ); const thumbWidth = Math.ceil(width / stride); const thumbHeight = Math.ceil(height / stride); diff --git a/packages/dicom/vtk/volumeImage.ts b/packages/dicom/vtk/volumeImage.ts index e4f8d2526..6ef7a701c 100644 --- a/packages/dicom/vtk/volumeImage.ts +++ b/packages/dicom/vtk/volumeImage.ts @@ -54,15 +54,20 @@ export function applyVolumeUpdate(image: vtkImageData, update: VolumeUpdate) { image.modified(); } -/** An 8 bit thumbnail of one loaded slice, windowed to the loaded range. */ +/** + * An 8 bit thumbnail of one loaded slice, windowed to the loaded range, or + * to the slice's own luminance for color. + */ export function sliceThumbnail(image: vtkImageData, slice: number) { const scalars = image.getPointData().getScalars(); const components = scalars.getNumberOfComponents(); const [width, height] = image.getDimensions(); const samplesPerSlice = width * height * components; - const data = scalars.getData(); + const data = scalars + .getData() + .subarray(slice * samplesPerSlice, (slice + 1) * samplesPerSlice); return sliceToThumbnail({ - data: data.subarray(slice * samplesPerSlice, (slice + 1) * samplesPerSlice), + data, width, height, components, diff --git a/scripts/checks/conventions.mjs b/scripts/checks/conventions.mjs index 0d34fb75c..3711e5bff 100644 --- a/scripts/checks/conventions.mjs +++ b/scripts/checks/conventions.mjs @@ -12,7 +12,6 @@ const BINARY_DIRS = [ 'docs/public/', 'public/', 'src/assets/', - 'src/io/itk-dicom/emscripten-build/', 'src/io/resample/emscripten-build/', ]; const { base } = stagedContext(); diff --git a/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts index 24de812ed..8f0edc389 100644 --- a/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts +++ b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts @@ -26,6 +26,7 @@ import { LoadedVtkImage } from '@/src/core/progressiveImage'; import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useMessageStore } from '@/src/store/messages'; +import { untilLoaded } from '@/src/composables/untilLoaded'; import { seatVolume } from '@/src/store/__tests__/datasetFixtures'; import { defer } from '@/src/utils'; @@ -185,7 +186,7 @@ describe('volume browser thumbnail lifetime', () => { expect(wrapper.get('.thumbnail-container').text()).toContain('CT'); expect(wrapper.find('[role="progressbar"]').exists()).toBe(false); - expect(messageTitles()).toEqual(['Error loading DICOM data']); + expect(messageTitles()).toEqual(['Error loading Pending volume']); }); it.each([false, true])( @@ -224,18 +225,20 @@ describe('volume browser thumbnail lifetime', () => { ); it('settles a thumbnail after a growth is undone while it decodes', async () => { - const { image, started, decode } = importPendingThumbnail(); + const { id, image, started, decode } = importPendingThumbnail(); const wrapper = mountBrowser(); await started.promise; const original = image.getVolume()!; const volumeOf = (members: Volume['members'], previous?: Volume) => - allocateVolume(plannedUpdate([...members]), {}, previous); + allocateVolume(plannedUpdate([...members]), previous); const grown = volumeOf([...original.members, sliceInstance(1)]); image.setVolume(grown); image.setVolume(volumeOf(original.members, grown)); image.startLoad(); decode.resolve(decoded()); + // The restarted load reads its bytes again before it decodes. + await untilLoaded(id); await flushPromises(); expectCurrentThumbnail(wrapper); @@ -255,11 +258,8 @@ describe('volume browser thumbnail lifetime', () => { it.each([ ['image', 'success'], - ['image', 'empty'], - ['image', 'failure'], - ['record', 'success'], ['record', 'empty'], - ['record', 'failure'], + ['image', 'failure'], ])( 'keeps the replacement %s thumbnail after a late %s', async (replacement, outcome) => { diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index 581dad92e..709a80f38 100644 --- a/src/core/cine/DicomCineImage.ts +++ b/src/core/cine/DicomCineImage.ts @@ -22,7 +22,6 @@ import { abortError } from '@/src/utils'; import { type CineHeader, isNativeTransferSyntax, - isSupportedCineTransferSyntax, readCineFrames, readCineHeader, } from './cineInstance'; @@ -201,14 +200,6 @@ export default class DicomCineImage extends BaseProgressiveImage { // Decode frame 0 so the canonical vtkImageData has valid scalars for // consumers that read it synchronously (thumbnail, getVtkImageData). if (this.disposed) return; - if (!isSupportedCineTransferSyntax(this.header.transferSyntaxUID)) { - this.reportError( - new Error( - `Unsupported cine transfer syntax: ${this.header.transferSyntaxUID}` - ) - ); - return; - } this.events.emit('loading', true); this.getFrame(0) .then((frame) => { diff --git a/src/core/cine/__tests__/cineInstance.spec.ts b/src/core/cine/__tests__/cineInstance.spec.ts index 0acb12b0e..78f951efd 100644 --- a/src/core/cine/__tests__/cineInstance.spec.ts +++ b/src/core/cine/__tests__/cineInstance.spec.ts @@ -136,10 +136,6 @@ describe('readCineHeader', () => { rows: 4, cols: 3, pixelSpacing: [1.8, 0.45], - patientName: 'DOE^JANE', - patientId: 'P-77', - seriesNumber: 12, - studyDate: '20250304', extraElements: [ rawElement( 0x0018, @@ -160,31 +156,10 @@ describe('readCineHeader', () => { cols: 3, numberOfFrames: 5, samplesPerPixel: 1, - bitsAllocated: 8, planarConfiguration: 0, photometricInterpretation: 'MONOCHROME2', pixelSpacing: [1.8, 0.45], frameTimeMs: null, - patient: { - PatientID: 'P-77', - PatientName: 'DOE^JANE', - PatientBirthDate: '19700101', - PatientSex: 'O', - }, - study: { - StudyID: '1', - StudyInstanceUID: '1.2.3', - StudyDate: '20250304', - StudyTime: '', - AccessionNumber: '', - StudyDescription: '', - }, - series: { - SeriesInstanceUID: '1.2.3.4', - SeriesNumber: '12', - SeriesDescription: 'Synthetic cine', - Modality: 'US', - }, regions: [ { physicalDeltaX: 0.5, diff --git a/src/core/cine/cineInstance.ts b/src/core/cine/cineInstance.ts index ad85e22d1..ecc65cc1c 100644 --- a/src/core/cine/cineInstance.ts +++ b/src/core/cine/cineInstance.ts @@ -28,40 +28,16 @@ const SUPPORTED_TRANSFER_SYNTAXES = new Set([ export const isNativeTransferSyntax = (uid: string) => NATIVE_TRANSFER_SYNTAXES.has(uid); -export const isSupportedCineTransferSyntax = (uid: string) => - SUPPORTED_TRANSFER_SYNTAXES.has(uid); - export type CineHeader = { transferSyntaxUID: string; rows: number; cols: number; numberOfFrames: number; samplesPerPixel: number; - bitsAllocated: number; planarConfiguration: number; photometricInterpretation: string; pixelSpacing: [number, number] | null; frameTimeMs: number | null; - patient: { - PatientID: string; - PatientName: string; - PatientBirthDate: string; - PatientSex: string; - }; - study: { - StudyID: string; - StudyInstanceUID: string; - StudyDate: string; - StudyTime: string; - AccessionNumber: string; - StudyDescription: string; - }; - series: { - SeriesInstanceUID: string; - SeriesNumber: string; - SeriesDescription: string; - Modality: string; - }; regions: ReturnType; }; @@ -105,31 +81,10 @@ export function readCineHeader(instance: Instance): CineHeader { cols: countOr(dataset, Tags.Columns, 0), numberOfFrames: countOr(dataset, Tags.NumberOfFrames, 1), samplesPerPixel: countOr(dataset, Tags.SamplesPerPixel, 1), - bitsAllocated: countOr(dataset, Tags.BitsAllocated, 8), planarConfiguration: countOr(dataset, Tags.PlanarConfiguration, 0), photometricInterpretation: tag(Tags.PhotometricInterpretation), pixelSpacing: positivePair(dataset, Tags.PixelSpacing), frameTimeMs: finiteOrNull(dataset, Tags.FrameTime), - patient: { - PatientID: tag(Tags.PatientID), - PatientName: tag(Tags.PatientName), - PatientBirthDate: tag(Tags.PatientBirthDate), - PatientSex: tag(Tags.PatientSex), - }, - study: { - StudyID: tag(Tags.StudyID), - StudyInstanceUID: tag(Tags.StudyInstanceUID), - StudyDate: tag(Tags.StudyDate), - StudyTime: tag(Tags.StudyTime), - AccessionNumber: tag(Tags.AccessionNumber), - StudyDescription: tag(Tags.StudyDescription), - }, - series: { - SeriesInstanceUID: tag(Tags.SeriesInstanceUID), - SeriesNumber: tag(Tags.SeriesNumber), - SeriesDescription: tag(Tags.SeriesDescription), - Modality: tag(Tags.Modality), - }, regions: ultrasoundRegionsOf(dataset), }; } @@ -155,7 +110,7 @@ export function isCineInstance(instance: Instance) { instance.pixelData !== null && isUltrasoundMultiframeSopClass(text(dataset, Tags.SOPClassUID)) && numberOf(getDatasetTag(dataset, Tags.NumberOfFrames)) > 1 && - isSupportedCineTransferSyntax(transferSyntax) && + SUPPORTED_TRANSFER_SYNTAXES.has(transferSyntax) && (!isNativeTransferSyntax(transferSyntax) || supportedNativePixels(dataset)) ); } diff --git a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts index 9b2cbcdc3..65dc516ad 100644 --- a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts +++ b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts @@ -1,146 +1,93 @@ -import { createDicomRuntime } from '@/packages/dicom/core'; -import { - CachedStreamFetcher, - sliceChunks, -} from '@/src/core/streaming/cachedStreamFetcher'; -import { describe, expect, it } from 'vitest'; +import { CachedStreamFetcher } from '@/src/core/streaming/cachedStreamFetcher'; +import { expect, it } from 'vitest'; -const readStream = async ( - stream: ReadableStream, - stopAfter = Infinity -) => { - const reader = stream.getReader(); - const chunks: Uint8Array[] = []; - let size = 0; - let completed = false; - try { - while (size <= stopAfter) { - const result = await reader.read(); - if (result.done) { - completed = true; - break; - } - chunks.push(result.value); - size += result.value.length; - } - } finally { - if (!completed) await reader.cancel(); - reader.releaseLock(); - } +const SOURCE = Uint8Array.from( + { length: 3 * 4096 + 123 }, + (_, index) => (index * 31) % 251 +); - const bytes = new Uint8Array(size); - let offset = 0; - chunks.forEach((chunk) => { - bytes.set(chunk, offset); - offset += chunk.length; - }); - return bytes; -}; - -describe('CachedStreamFetcher', () => { - it('should support stopping and resuming', async () => { - const source = Uint8Array.from( - { length: 32 * 1024 + 123 }, - (_, index) => (index * 31) % 251 - ); - const requestedRanges: Array = []; - const fetchRange: typeof fetch = async (_input, init) => { - const range = new Headers(init?.headers).get('Range'); - requestedRanges.push(range); - const start = range ? Number(range.match(/^bytes=(\d+)-$/)?.[1]) : 0; - let offset = start; - const body = new ReadableStream({ +/** Serves SOURCE in 4096 byte chunks, recording each request's signal. */ +function serving() { + const signals: AbortSignal[] = []; + const fetchSource: typeof fetch = async (_input, init) => { + signals.push(init!.signal!); + let offset = 0; + return new Response( + new ReadableStream({ pull(controller) { - if (offset === source.length) { + if (offset === SOURCE.length) { controller.close(); return; } - const end = Math.min(offset + 4096, source.length); - controller.enqueue(source.slice(offset, end)); + const end = Math.min(offset + 4096, SOURCE.length); + controller.enqueue(SOURCE.slice(offset, end)); offset = end; }, - }); - return new Response(body, { - status: start === 0 ? 200 : 206, - headers: { - 'content-length': String(source.length - start), - ...(start === 0 - ? {} - : { - 'content-range': `bytes ${start}-${source.length - 1}/${source.length}`, - }), - }, - }); - }; - const runtime = createDicomRuntime({ - requestConcurrency: 1, - fetch: fetchRange, - }); - const fetcher = new CachedStreamFetcher('https://example.test/data', { - fetch: runtime.fetch, - }); + }) + ); + }; + return { signals, fetchSource }; +} - await fetcher.connect(); - const partial = await readStream(fetcher.getStream(), 4096 * 3); - expect(partial).toEqual(source.slice(0, partial.length)); - const resumeAt = fetcher.size; - expect(resumeAt).toBeGreaterThanOrEqual(partial.length); - expect(resumeAt).toBeLessThan(source.length); - fetcher.close(); +const bytesOf = async (stream: ReadableStream) => + new Uint8Array(await new Response(stream).arrayBuffer()); - await fetcher.connect(); - expect(requestedRanges).toEqual([null, `bytes=${resumeAt}-`]); +it('replays one download from its start to every stream', async () => { + const { signals, fetchSource } = serving(); + const fetcher = new CachedStreamFetcher('https://example.test/data', { + fetch: fetchSource, + }); + await fetcher.connect(); + + const reader = fetcher.getStream().getReader(); + const first = await reader.read(); + await reader.cancel(); + expect(first.value).toEqual(SOURCE.slice(0, 4096)); - for (let i = 0; i < 2; i++) { - expect(await readStream(fetcher.getStream())).toEqual(source); - } - expect(fetcher.size).toBe(source.length); - expect(requestedRanges).toHaveLength(2); + await fetcher.connect(); + expect(await bytesOf(fetcher.getStream())).toEqual(SOURCE); + expect(await bytesOf(fetcher.getStream())).toEqual(SOURCE); + expect(new Uint8Array(await (await fetcher.blob()).arrayBuffer())).toEqual( + SOURCE + ); + expect(signals).toHaveLength(1); +}); - fetcher.close(); - runtime.dispose(); +it('releases its request once the download is read to its end', async () => { + const { signals, fetchSource } = serving(); + const fetcher = new CachedStreamFetcher('https://example.test/data', { + fetch: fetchSource, }); + await fetcher.connect(); + expect(signals[0].aborted).toBe(false); + + await fetcher.blob(); + + expect(signals[0].aborted).toBe(true); + expect(fetcher.connected).toBe(true); + expect(await bytesOf(fetcher.getStream())).toEqual(SOURCE); }); -describe('sliceChunks', () => { - it('should work', () => { - expect(sliceChunks([new Uint8Array([1, 2, 3])], 0)).toEqual([]); - expect(sliceChunks([new Uint8Array([1, 2, 3])], 1)).toEqual([ - new Uint8Array([1]), - ]); - expect(sliceChunks([new Uint8Array([1])], 1)).toEqual([ - new Uint8Array([1]), - ]); - expect(sliceChunks([new Uint8Array([1, 2])], 1)).toEqual([ - new Uint8Array([1]), - ]); - expect(sliceChunks([new Uint8Array([1, 2])], 3)).toEqual([ - new Uint8Array([1, 2]), - ]); - expect( - sliceChunks([new Uint8Array([1, 2]), new Uint8Array([3, 4])], 3) - ).toEqual([new Uint8Array([1, 2]), new Uint8Array([3])]); +it('aborts its request and ends its streams when closed', async () => { + const { signals, fetchSource } = serving(); + const fetcher = new CachedStreamFetcher('https://example.test/data', { + fetch: fetchSource, }); + await fetcher.connect(); + + fetcher.close(); + + expect(signals[0].aborted).toBe(true); + expect(fetcher.connected).toBe(false); + expect(await bytesOf(fetcher.getStream())).toEqual(new Uint8Array()); }); -it('rejects an unverified resumed range while preserving the cached header', async () => { - const prefix = new Uint8Array([1, 2, 3, 4]); - let requests = 0; - const fetcher = new CachedStreamFetcher( - 'https://example.test/hidden-headers', - { - prefixChunks: [prefix], - fetch: async () => - new Response(new Uint8Array([5, 6]), { - status: 206, - headers: requests++ === 0 ? {} : { 'content-range': 'bytes 4-5/6' }, - }), - } +it('reports a missing resource', async () => { + const fetcher = new CachedStreamFetcher('https://example.test/missing', { + fetch: async () => new Response('gone', { status: 404 }), + }); + await expect(fetcher.connect()).rejects.toThrow( + 'https://example.test/missing' ); - await expect(fetcher.connect()).rejects.toThrow('readable content range'); expect(fetcher.connected).toBe(false); - expect(new Uint8Array(await (await fetcher.blob()).arrayBuffer())).toEqual( - new Uint8Array([1, 2, 3, 4, 5, 6]) - ); - fetcher.close(); }); diff --git a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts index d41b255ee..9cc62e288 100644 --- a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts +++ b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts @@ -26,9 +26,6 @@ import DicomVolumeImage, { const ROWS = 2; const COLUMNS = 2; const PIXELS_PER_SLICE = ROWS * COLUMNS; -// Physical Units X/Y Direction code for centimeters. -const CENTIMETERS = 3; -const PUBLIC_DSC_SLOPE = 112067.85375182; // The slice's z position is also its pixel value, so decoded contents say // which instance a slice came from. @@ -50,7 +47,7 @@ function sliceAt(z: number, overrides: Record = {}) { } const volumeOf = (members: Instance[], previous?: Volume) => - allocateVolume(plannedUpdate(members), {}, previous); + allocateVolume(plannedUpdate(members), previous); const stack = (count: number) => volumeOf(Array.from({ length: count }, (_, z) => sliceAt(z))); @@ -199,77 +196,6 @@ describe('DicomVolumeImage loading', () => { expect(decoded).toEqual([7, 3, 5, 1, 6, 8, 4, 2, 0]); }); - - it('starts from the middle slice when no view shows one', async () => { - const { decoder, decoded } = constantSlices(); - const { image } = holder(decoder, { focus: () => undefined }, 1); - - await show(image, stack(9)); - - expect(decoded).toEqual([4, 0, 8, 2, 6, 3, 5, 1, 7]); - }); - - it('keeps modality-rescaled pixels from the public DSC series to float32 precision', async () => { - // The public frames are 200x230; reduced geometry keeps the exact encoding, - // rescale, and an observed stored-pixel maximum. - const decoded = Float64Array.from([ - 0, - PUBLIC_DSC_SLOPE, - 2 * PUBLIC_DSC_SLOPE, - 65131 * PUBLIC_DSC_SLOPE, - ]); - const { image } = holder(decodeTo(() => decoded).decoder); - - await show( - image, - volumeOf([ - sliceAt(1, { - [Tags.RescaleSlope]: String(PUBLIC_DSC_SLOPE), - [Tags.RescaleIntercept]: '0', - }), - ]) - ); - - const data = image.getVtkImageData().getPointData().getScalars().getData(); - // Float32 keeps every stored step apart: the slope dwarfs float32's spacing. - expect(data).toBeInstanceOf(Float32Array); - expect(Array.from(data)).toEqual(Array.from(decoded, Math.fround)); - }); - - // PixelSpacing is row\column, so the fallback in-plane spacing is [0.7, 0.6]. - it.each([ - { physicalDeltaX: 0.05, expected: [0.5, 0.3], warnings: 0 }, - { physicalDeltaX: 0, expected: [0.7, 0.6], warnings: 1 }, - ])( - 'shows ultrasound region spacing only when nonzero and finite (deltaX $physicalDeltaX)', - ({ physicalDeltaX, expected, warnings }) => { - const { image } = holder(constantSlices().decoder); - const volume = volumeOf([ - { - ...sliceAt(1, { - [Tags.Modality]: 'US', - [Tags.PixelSpacing]: '0.6\\0.7', - }), - ultrasoundRegions: { - region: { - physicalDeltaX, - physicalDeltaY: 0.03, - physicalUnitsXDirection: CENTIMETERS, - physicalUnitsYDirection: CENTIMETERS, - }, - regionCount: 1, - }, - }, - ]); - - image.setVolume(volume); - - const [x, y] = image.getVtkImageData().getSpacing(); - expect(x).toBeCloseTo(expected[0]); - expect(y).toBeCloseTo(expected[1]); - expect(volume.warnings).toHaveLength(warnings); - } - ); }); describe('DicomVolumeImage failures', () => { @@ -296,16 +222,6 @@ describe('DicomVolumeImage failures', () => { expect(message).toContain('Uint8Array'); }); - it('settles after rejecting fractional samples bound for an integer buffer', async () => { - const message = await loadRejected((value) => - value === 2 - ? new Float64Array(PIXELS_PER_SLICE).fill(2.5) - : new Uint8Array(PIXELS_PER_SLICE).fill(value) - ); - expect(message).toContain('fractional'); - expect(message).toContain('Uint8Array'); - }); - it('settles once every frame of a multiframe instance loaded or failed', async () => { const file = fromBlob( new Blob([nativePixelDicom({ rows: ROWS, columns: COLUMNS, frames: 3 })]) @@ -330,7 +246,9 @@ describe('DicomVolumeImage failures', () => { await show(image, volumeOf([instance])); - expect(errors.map(({ message }) => message)).toEqual(['reset']); + expect(errors.map(({ message }) => message)).toEqual([ + expect.stringMatching(/frame 2 could not be read: reset$/), + ]); expect(image.isLoading()).toBe(false); expect(image.isLoaded()).toBe(true); }); @@ -345,7 +263,9 @@ describe('DicomVolumeImage failures', () => { return slice; }); await show(image, stack(3)); - expect(errors.map(({ message }) => message)).toEqual(['corrupt slice']); + expect(errors.map(({ message }) => message)).toEqual([ + expect.stringMatching(/could not be decoded: corrupt slice$/), + ]); expect(sliceOf(image, 1)).toEqual(filledWith(0)); image.startLoad(); @@ -467,6 +387,24 @@ describe('DicomVolumeImage thumbnails', () => { expect(encoded).toEqual([]); }); + it('thumbnails a volume whose retry loads after every slice failed', async () => { + let failing = true; + const { decoder } = constantSlices(); + const { image, encoded } = holder(async (request, signal) => { + if (failing) throw new Error('server down'); + return decoder(request, signal); + }); + await show(image, stack(3)); + expect(await image.getThumbnail()).toBeNull(); + + failing = false; + image.startLoad(); + await idle(image); + + expect(await image.getThumbnail()).not.toBeNull(); + expect(encoded).toEqual([thumbnailOf(image, 1)]); + }); + it('thumbnails the new middle slice after the volume changes', async () => { const { decoder } = constantSlices(); const { image, encoded } = holder(decoder); @@ -481,30 +419,6 @@ describe('DicomVolumeImage thumbnails', () => { expect(encoded).toHaveLength(2); expect(encoded[1]).toEqual(thumbnailOf(image, 1)); }); - - it('windows a color thumbnail on luminance across the volume', async () => { - const OTHER_COMPONENT = 1000; - const { decoder } = decodeTo( - (value) => - Uint16Array.from({ length: PIXELS_PER_SLICE * 3 }, (_, index) => - index % 3 === 0 ? value * 100 : OTHER_COMPONENT - ), - 3 - ); - const { image, encoded } = holder(decoder); - const rgb = { [Tags.SamplesPerPixel]: '3' }; - - await show(image, volumeOf([1, 2, 3].map((z) => sliceAt(z, rgb)))); - await image.getThumbnail(); - - // The middle slice has the volume's middle luminance, within one byte of - // mid grey after floating-point windowing. - expect( - Array.from(encoded[0].data).every( - (value) => Math.abs(value - 127.5) <= 0.5 - ) - ).toBe(true); - }); }); describe('DicomVolumeImage segmentation', () => { diff --git a/src/core/streaming/cachedStreamFetcher.ts b/src/core/streaming/cachedStreamFetcher.ts index dee71a767..880dc637e 100644 --- a/src/core/streaming/cachedStreamFetcher.ts +++ b/src/core/streaming/cachedStreamFetcher.ts @@ -1,284 +1,116 @@ -import { - HTTP_STATUS_OK, - HTTP_STATUS_PARTIAL_CONTENT, - HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, - HttpNotFound, -} from '@/src/core/streaming/httpCodes'; -import { Fetcher, FetcherInit } from '@/src/core/streaming/types'; -import { - ContentRange, - parseContentRangeHeader, -} from '@/src/utils/parseContentRangeHeader'; -import { Maybe } from '@/src/types'; +import { HTTP_STATUS_OK, HttpNotFound } from '@/src/core/streaming/httpCodes'; +import type { Fetcher } from '@/src/core/streaming/types'; type FetchFunction = typeof fetch; export type CachedStreamFetcherRequestInit = RequestInit & { - prefixChunks?: Uint8Array[]; - contentLength?: number; fetch?: FetchFunction; }; export const StopSignal = Symbol('StopSignal'); -export function sliceChunks(chunks: T[], start: number) { - const newChunks: T[] = []; - let size = 0; - for (let i = 0; i < chunks.length && size < start; i++) { - const chunk = chunks[i]; - if (size + chunk.length > start) { - const offset = start - size; - const newChunk = chunk.slice(0, offset) as T; - newChunks.push(newChunk); - size += newChunk.length; - } else { - newChunks.push(chunk); - size += chunk.length; - } - } - return newChunks; -} - -/** - * Infers the content range from a full content length and a remaining content length. - * - * The remaining length is expected to be the length of the remaining bytes to - * be downloaded. - */ -function inferContentRange( - remainingLength: number | null, - totalLength: number | null -): ContentRange { - if (remainingLength == null || totalLength == null) - return { type: 'empty-range' }; - - if (remainingLength > totalLength) { - return { type: 'invalid-range' }; - } - - const start = totalLength - remainingLength; - const end = totalLength - 1; - return { type: 'range', start, end, length: totalLength }; -} - /** - * A cached stream fetcher that caches a URI stream. - * - * Supports servers that accept Range requests. - * - * This fetcher falls back to downloading the entire stream if the server does - * not support the Range header with bytes. + * Downloads a URL once and replays what has arrived, from the start, to every + * stream it hands out. */ export class CachedStreamFetcher implements Fetcher { - private abortController: Maybe; - private fetch: typeof fetch; - private chunks: Uint8Array[]; - private contentLength: number | null = null; - private activeNetworkStream: ReadableStream | null = null; - private activeNetworkStreamReader: ReadableStreamDefaultReader | null = - null; + private fetch: FetchFunction; + private open = false; + private request: AbortController | null = null; + private chunks: Uint8Array[] = []; + private reader: ReadableStreamDefaultReader | null = null; + private pending: Promise> | null = null; - public contentType: string = ''; - public contentDisposition: string = ''; + public contentType = ''; + public contentDisposition = ''; constructor( - private request: RequestInfo | URL, + private url: RequestInfo | URL, private init?: CachedStreamFetcherRequestInit ) { - this.chunks = [...(init?.prefixChunks ?? [])] as Uint8Array[]; - this.contentLength = init?.contentLength ?? null; - const fetchFn = - init?.fetch ?? ((input, options) => globalThis.fetch(input, options)); + const fetchFn = init?.fetch ?? globalThis.fetch; this.fetch = (input, options) => fetchFn(input, options); } get connected() { - return !!this.abortController; - } - - get size() { - return this.chunks.reduce((sum, chunk) => sum + chunk.length, 0); - } - - get abortSignal() { - return this.abortController?.signal; + return this.open; } - async connect(init?: FetcherInit) { - if (this.connected) return; - - this.abortController = init?.abortController ?? new AbortController(); - const connection = this.abortController; - this.abortController.signal.addEventListener('abort', () => { - this.cleanupAfterAbort(); - }); - - // do not actually send the request, since we've cached the entire response - if (this.size === this.contentLength) return; - - // Use fromEntries as a workaround to handle - // jsdom not setting Range properly. - const headers = Object.fromEntries(new Headers(this.init?.headers ?? {})); - if (this.size > 0) { - headers.Range = `bytes=${this.size}-`; - } - - const response = await this.fetch(new Request(this.request), { - ...this.init, - headers, - signal: this.abortController.signal, - }); - - this.validateConnection(connection, response); - this.contentType = response.headers.get('content-type') ?? ''; - this.contentDisposition = response.headers.get('content-disposition') ?? ''; - - let remainingContentLength: number | null = null; - if (response.headers.has('content-length')) { - remainingContentLength = Number(response.headers.get('content-length')); - } - - // set this.contentLength if we didn't submit a partial request - if ( - this.size === 0 && - this.contentLength == null && - remainingContentLength != null - ) { - this.contentLength = remainingContentLength; - } - - if (!response.body) throw new Error('Did not receive a response body'); - - const noMoreContent = remainingContentLength === 0; - // Content-Range needs to be in Access-Control-Expose-Headers. If not, then - // try to infer based on the remaining content length and the total content - // length. - const contentRange = response.headers.has('content-range') - ? parseContentRangeHeader(response.headers.get('content-range')) - : inferContentRange(remainingContentLength, this.contentLength); - const rangeNotSatisfiable = - response.status === HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE; - - if (rangeNotSatisfiable && !noMoreContent) { - throw new Error('Range could not be satisfied'); - } - - if ( - !noMoreContent && - response.status !== HTTP_STATUS_OK && - response.status !== HTTP_STATUS_PARTIAL_CONTENT - ) { - throw new HttpNotFound(this.request.toString()); - } - - if (response.status === HTTP_STATUS_PARTIAL_CONTENT) { - this.resumeChunks(response, contentRange); - } else if (!noMoreContent) { - this.chunks = []; - } - - this.activeNetworkStream = response.body; - this.activeNetworkStreamReader = this.activeNetworkStream.getReader(); - } - - private resumeChunks(response: Response, contentRange: ContentRange) { - if (contentRange.type === 'invalid-range') - throw new Error('Invalid content-range header'); - if (contentRange.type === 'unsatisfied-range') - throw new Error('Range could not be satisfied'); - if (contentRange.type === 'empty-range' && this.size > 0) { - response.body?.cancel().catch(() => {}); + async connect() { + if (this.open) return; + this.open = true; + this.chunks = []; + const request = new AbortController(); + this.request = request; + try { + const response = await this.fetch(new Request(this.url), { + ...this.init, + signal: request.signal, + }); + if (response.status !== HTTP_STATUS_OK) + throw new HttpNotFound(this.url.toString()); + if (!response.body) throw new Error('Did not receive a response body'); + this.contentType = response.headers.get('content-type') ?? ''; + this.contentDisposition = + response.headers.get('content-disposition') ?? ''; + this.reader = response.body.getReader(); + } catch (error) { this.close(); - throw new Error( - 'Cannot resume a DICOM download without a readable content range' - ); - } - const start = contentRange.type === 'range' ? contentRange.start : 0; - this.chunks = sliceChunks(this.chunks, start); - } - - private validateConnection(connection: AbortController, response: Response) { - if (connection.signal.aborted || connection !== this.abortController) { - response.body?.cancel().catch(() => {}); - throw new DOMException('DICOM request cancelled', 'AbortError'); + throw error; } } close() { - if (!this.abortController) return; - this.abortController.abort(StopSignal); - this.cleanupAfterAbort(); + this.open = false; + this.release(); } getStream() { - let chunkIndex = 0; - return new ReadableStream({ + let index = 0; + return new ReadableStream({ pull: async (controller) => { - if (!this.connected) { + if ( + !this.open || + (index === this.chunks.length && (await this.readNext()).done) + ) { controller.close(); return; } - - if (chunkIndex > this.chunks.length) - throw new Error('Did chunks get truncated?'); - - if (chunkIndex === this.chunks.length) { - const result = await this.readNextNetworkChunk(); - if (result.done) { - controller.close(); - return; - } - } - - // invariant: chunkIndex < this.chunks.length - controller.enqueue(this.chunks[chunkIndex++]); + controller.enqueue(this.chunks[index++]); }, }); } - private promise: Promise> | null = null; - - private readNextNetworkChunk() { - if (!this.activeNetworkStreamReader) - return Promise.resolve>({ - done: true, - value: undefined, - }); - - if (!this.promise) { - const connection = this.abortController; - this.promise = this.activeNetworkStreamReader - .read() - .then((result) => { - if (connection !== this.abortController) throw StopSignal; - if (!result.done) { - this.chunks.push(result.value as Uint8Array); - } else if (this.contentLength === null) { - // Entire stream finished but had no Content-Length header; treat full cache as total length - this.contentLength = this.size; - } - return result; - }) - .finally(() => { - if (connection === this.abortController) this.promise = null; - }); - } - return this.promise; - } - async blob() { await this.connect(); - - const stream = this.getStream(); - const sink = new WritableStream(); - await stream.pipeTo(sink); + await this.getStream().pipeTo(new WritableStream()); return new Blob(this.chunks, { type: this.contentType }); } - private cleanupAfterAbort() { - this.promise = null; - this.activeNetworkStreamReader = null; - this.activeNetworkStream = null; - this.abortController = null; + // A pooled fetch holds its request until the caller's signal aborts. + private release() { + this.reader = null; + this.request?.abort(StopSignal); + this.request = null; + } + + private readNext() { + const { reader } = this; + if (!reader) + return Promise.resolve>({ + done: true, + value: undefined, + }); + this.pending ??= reader + .read() + .then((result) => { + if (result.done) this.release(); + else this.chunks.push(result.value as Uint8Array); + return result; + }) + .finally(() => { + this.pending = null; + }); + return this.pending; } } diff --git a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts index 82700fb95..fb7909c07 100644 --- a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts +++ b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts @@ -1,14 +1,14 @@ import { deflateRawSync } from 'node:zlib'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { fromBlob, + fromUrl, readDicomDataset, readInstance, Tags, } from '@/packages/dicom/core'; -import { dicomMetadataForDisplay } from '@/src/core/streaming/dicom/octMetadata'; +import { enFaceTags } from '@/src/core/streaming/dicom/octMetadata'; import { trackedSource } from '@/tests/byteSourceFixtures'; -import { dicomDatasetToTags } from '@/src/io/readDicomTags'; import { isOCTMetadata, @@ -39,7 +39,7 @@ const never = new AbortController().signal; async function projectFile(file: Blob) { const { dataset } = await readInstance(fromBlob(file), never); - return dicomMetadataForDisplay(dataset); + return enFaceTags(dataset); } async function augmented(bytes = fixtureBytes()) { @@ -74,14 +74,14 @@ describe('OCT DICOM activation', () => { } ); - it('preserves non-OCT metadata without adding projection fields', () => { + it('adds no projection fields to non-OCT metadata', () => { const bytes = fixtureBytes({ set: { '00080016': '1.2.840.10008.5.1.4.1.1.2', '00080060': 'CT' }, }); - const dataset = readDicomDataset(bytes); - expect(dicomMetadataForDisplay(dataset)).toEqual( - dicomDatasetToTags(dataset) - ); + const tags = new Map(enFaceTags(readDicomDataset(bytes))); + expect(tags.get(Tags.Modality)).toBe('CT'); + expect(tags.has(OCT_SCAN_PATTERN)).toBe(false); + expect(tags.has(OCT_GEOMETRY_ERROR)).toBe(false); }); }); @@ -99,7 +99,7 @@ describe('OCT enhanced spatial metadata', () => { 64 * 1024 ); const { dataset } = await readInstance(source, never); - const tags = new Map(dicomMetadataForDisplay(dataset)); + const tags = new Map(enFaceTags(dataset)); expect(tags.get(Tags.ImagePositionPatient)).toBe('0\\0\\0'); expect(tags.get(Tags.SpacingBetweenSlices)).toBe('0.2'); expect(stats.delivered).toBeLessThan(file.size / 2); @@ -511,3 +511,92 @@ describe('OCT enhanced spatial metadata', () => { await expect(projectFile(new Blob(['corrupt OCT']))).rejects.toThrow(); }); }); + +const positions = (values: number[]) => + values.map((z) => ({ position: `0\\0\\${z}` })); + +describe('structured OCT application metadata', () => { + it.each([ + ['regular', [0, 0.2, 0.4], undefined], + ['reversed', [0.4, 0.2, 0], /image grid/], + ['uneven', [0, 0.1, 0.4], /nonuniform/], + ] as const)( + 'retains the existing %s geometry policy without changing raw data', + async (_, z, error) => { + const file = enhancedFile(positions([...z])); + const dataset = readDicomDataset( + new Uint8Array(await file.arrayBuffer()) + ); + const before = structuredClone(dataset); + const projected = new Map(enFaceTags(dataset)); + if (error) expect(projected.get(OCT_GEOMETRY_ERROR)).toMatch(error); + else { + expect(projected.has(OCT_GEOMETRY_ERROR)).toBe(false); + expect(projected.get(Tags.ImagePositionPatient)).toBe('0\\0\\0'); + expect(projected.get(Tags.SpacingBetweenSlices)).toBe('0.2'); + } + expect(dataset).toEqual(before); + } + ); + + it.each(['128280', '128282'])( + 'retains nested B-scan pattern %s and volumetric restrictions', + async (pattern) => { + const file = enhancedFile(positions([0, 0.2]), [ + element('00221622', 'CS', 'NO'), + sequence('00221640', [ + sequence('00221618', [element('00080100', 'SH', pattern)]), + ]), + ]); + const dataset = readDicomDataset( + new Uint8Array(await file.arrayBuffer()) + ); + const projected = new Map(enFaceTags(dataset)); + + expect(projected.get(OCT_SCAN_PATTERN)).toBe(pattern); + expect(projected.get(Tags.OphthalmicVolumetricPropertiesFlag)).toBe('NO'); + expect(projected.get(OCT_GEOMETRY_ERROR)).toBeUndefined(); + } + ); + + it('preserves shared-only geometry with declared spacing without inventing frame positions', async () => { + const file = enhancedFile([], [element('00180088', 'DS', '0.2')]); + const dataset = readDicomDataset(new Uint8Array(await file.arrayBuffer())); + const count = dataset.elements.find((entry) => entry.tag === '00280008')!; + count.values = { kind: 'decimal', values: [3], text: ['3'] }; + const projected = new Map(enFaceTags(dataset)); + + expect(projected.get(Tags.PixelSpacing)).toBe('0.01\\0.02'); + expect(projected.get(Tags.SpacingBetweenSlices)).toBe('0.2'); + expect(projected.has(Tags.ImagePositionPatient)).toBe(false); + expect(projected.has(OCT_GEOMETRY_ERROR)).toBe(false); + }); + + it.each([false, true])( + 'matches file and HTTP OCT metadata after loading, deflated=%s', + async (deflated) => { + const bytes = new Uint8Array(createSyntheticOCT({ deflate: deflated })); + const file = new File([bytes], 'oct.dcm'); + const fetch = vi.fn( + async () => + new Response(bytes, { + headers: { 'Content-Length': String(bytes.length) }, + }) + ); + const instances = await Promise.all( + [ + fromBlob(file), + fromUrl('https://example.test/oct.dcm', { fetch }), + ].map((source) => readInstance(source, never)) + ); + const projected = instances.map( + ({ dataset }) => new Map(enFaceTags(dataset)) + ); + expect(projected[0]).toEqual(projected[1]); + expect(projected[0].get(OCT_SCAN_PATTERN)).toBe('128280'); + expect(projected[0].has(OCT_GEOMETRY_ERROR)).toBe(false); + expect(projected[0].get(Tags.PixelSpacing)).toBe('0.0104\\0.046875'); + expect(fetch).toHaveBeenCalledTimes(1); + } + ); +}); diff --git a/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts b/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts deleted file mode 100644 index 77d4ef37c..000000000 --- a/src/core/streaming/dicom/__tests__/octStructuredMetadata.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, expect, it, vi } from 'vitest'; -import { - fromBlob, - fromUrl, - readDicomDataset, - readInstance, - Tags, -} from '@/packages/dicom/core'; -import { dicomMetadataForDisplay } from '../octMetadata'; -import { OCT_GEOMETRY_ERROR, OCT_SCAN_PATTERN } from '../octMetadataTags'; -import { - createSyntheticOCT, - element, - enhancedFile, - sequence, -} from '@/tests/fixtures/oct/dicom'; - -const positions = (values: number[]) => - values.map((z) => ({ position: `0\\0\\${z}` })); - -describe('structured OCT application metadata', () => { - it.each([ - ['regular', [0, 0.2, 0.4], undefined], - ['reversed', [0.4, 0.2, 0], /image grid/], - ['uneven', [0, 0.1, 0.4], /nonuniform/], - ] as const)( - 'retains the existing %s geometry policy without changing raw data', - async (_, z, error) => { - const file = enhancedFile(positions([...z])); - const dataset = readDicomDataset( - new Uint8Array(await file.arrayBuffer()) - ); - const before = structuredClone(dataset); - const projected = new Map(dicomMetadataForDisplay(dataset)); - if (error) expect(projected.get(OCT_GEOMETRY_ERROR)).toMatch(error); - else { - expect(projected.has(OCT_GEOMETRY_ERROR)).toBe(false); - expect(projected.get(Tags.ImagePositionPatient)).toBe('0\\0\\0'); - expect(projected.get(Tags.SpacingBetweenSlices)).toBe('0.2'); - } - expect(dataset).toEqual(before); - } - ); - - it.each(['128280', '128282'])( - 'retains nested B-scan pattern %s and volumetric restrictions', - async (pattern) => { - const file = enhancedFile(positions([0, 0.2]), [ - element('00221622', 'CS', 'NO'), - sequence('00221640', [ - sequence('00221618', [element('00080100', 'SH', pattern)]), - ]), - ]); - const dataset = readDicomDataset( - new Uint8Array(await file.arrayBuffer()) - ); - const projected = new Map(dicomMetadataForDisplay(dataset)); - - expect(projected.get(OCT_SCAN_PATTERN)).toBe(pattern); - expect(projected.get(Tags.OphthalmicVolumetricPropertiesFlag)).toBe('NO'); - expect(projected.get(OCT_GEOMETRY_ERROR)).toBeUndefined(); - } - ); - - it('preserves shared-only geometry with declared spacing without inventing frame positions', async () => { - const file = enhancedFile([], [element('00180088', 'DS', '0.2')]); - const dataset = readDicomDataset(new Uint8Array(await file.arrayBuffer())); - const count = dataset.elements.find((entry) => entry.tag === '00280008')!; - count.values = { kind: 'decimal', values: [3], text: ['3'] }; - const projected = new Map(dicomMetadataForDisplay(dataset)); - - expect(projected.get(Tags.PixelSpacing)).toBe('0.01\\0.02'); - expect(projected.get(Tags.SpacingBetweenSlices)).toBe('0.2'); - expect(projected.has(Tags.ImagePositionPatient)).toBe(false); - expect(projected.has(OCT_GEOMETRY_ERROR)).toBe(false); - }); - - it.each([false, true])( - 'matches file and HTTP OCT metadata after loading, deflated=%s', - async (deflated) => { - const bytes = new Uint8Array(createSyntheticOCT({ deflate: deflated })); - const file = new File([bytes], 'oct.dcm'); - const fetch = vi.fn( - async () => - new Response(bytes, { - headers: { 'Content-Length': String(bytes.length) }, - }) - ); - const never = new AbortController().signal; - const instances = await Promise.all( - [ - fromBlob(file), - fromUrl('https://example.test/oct.dcm', { fetch }), - ].map((source) => readInstance(source, never)) - ); - const projected = instances.map( - ({ dataset }) => new Map(dicomMetadataForDisplay(dataset)) - ); - expect(projected[0]).toEqual(projected[1]); - expect(projected[0].get(OCT_SCAN_PATTERN)).toBe('128280'); - expect(projected[0].has(OCT_GEOMETRY_ERROR)).toBe(false); - expect(projected[0].get(Tags.PixelSpacing)).toBe('0.0104\\0.046875'); - expect(fetch).toHaveBeenCalledTimes(1); - } - ); -}); diff --git a/src/core/streaming/dicom/octDataset.ts b/src/core/streaming/dicom/octDataset.ts deleted file mode 100644 index d28b88b9d..000000000 --- a/src/core/streaming/dicom/octDataset.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { - getDatasetTag, - sequenceItems, - trimDicomPadding, - type DicomDataset, -} from '@/packages/dicom/core'; - -/** The OCT policy reads attributes and their explicit sequence paths only. */ -export type OCTDataset = { - value: (tag: string) => string | undefined; - items: (tag: string) => OCTDataset[]; -}; - -/** Adapts already loaded metadata without reparsing or retaining source bytes. */ -export const structuredOCTDataset = (dataset: DicomDataset): OCTDataset => ({ - value: (tag) => { - const value = getDatasetTag(dataset, tag); - return value === undefined ? undefined : trimDicomPadding(value); - }, - items: (tag) => sequenceItems(dataset, tag).map(structuredOCTDataset), -}); diff --git a/src/core/streaming/dicom/octMetadata.ts b/src/core/streaming/dicom/octMetadata.ts index d6a34444c..46a35a91f 100644 --- a/src/core/streaming/dicom/octMetadata.ts +++ b/src/core/streaming/dicom/octMetadata.ts @@ -1,6 +1,10 @@ -import { Tags, type DicomDataset } from '@/packages/dicom/core'; -import { dicomDatasetToTags } from '@/src/io/readDicomTags'; -import { type OCTDataset, structuredOCTDataset } from './octDataset'; +import { + getDatasetTag, + sequenceItems, + Tags, + trimDicomPadding, + type DicomDataset, +} from '@/packages/dicom/core'; import { areEquals } from '@kitware/vtk.js/Common/Core/Math'; import { frameGridGeometry, @@ -31,22 +35,31 @@ const PIXEL_SPACING = Tags.PixelSpacing; const SLICE_SPACING = Tags.SpacingBetweenSlices; const IMAGE_ORIENTATION = Tags.ImageOrientationPatient; const IMAGE_POSITION = Tags.ImagePositionPatient; -const firstItem = (data: OCTDataset | undefined, tag: string) => - data?.items(tag)[0]; -const sequenceItems = (data: OCTDataset, tag: string) => data.items(tag); -const stringValue = (data: OCTDataset | undefined, tag: string) => - data?.value(tag)?.trim() || undefined; +// The attributes en face reads off an instance, beside the ones derived below. +const EN_FACE_TAGS = [ + Tags.Modality, + Tags.SOPClassUID, + Tags.PixelSpacing, + Tags.ImageOrientationPatient, + Tags.ImagePositionPatient, + Tags.SpacingBetweenSlices, + Tags.OphthalmicVolumetricPropertiesFlag, +]; +const firstItem = (data: DicomDataset | undefined, tag: string) => + data && sequenceItems(data, tag)[0]; +const stringValue = (data: DicomDataset | undefined, tag: string) => + trimDicomPadding(getDatasetTag(data, tag) ?? '') || undefined; const vector = (value: string | undefined) => value?.split('\\').map(Number); function frameAttribute( - data: OCTDataset | undefined, + data: DicomDataset | undefined, sequence: string, attribute: string ) { return stringValue(firstItem(data, sequence), attribute); } -function frameGeometry(data: OCTDataset) { +function frameGeometry(data: DicomDataset) { const shared = firstItem(data, SHARED); const frames = sequenceItems(data, PER_FRAME); // Shared groups take precedence over the first frame, then the top level. @@ -140,7 +153,7 @@ function geometryError(geometry: ReturnType) { return positionError(geometry); } -function scanPattern(data: OCTDataset) { +function scanPattern(data: DicomDataset) { const acquisitions = sequenceItems(data, ACQUISITION_PARAMETERS); const patterns = [data, ...acquisitions].flatMap((dataset) => sequenceItems(dataset, SCAN_PATTERN).flatMap( @@ -152,7 +165,7 @@ function scanPattern(data: OCTDataset) { : patterns[0]; } -function promoteOCTGeometry(data: OCTDataset, tags: Map) { +function promoteOCTGeometry(data: DicomDataset, tags: Map) { const geometry = frameGeometry(data); const set = (tag: string, value: Maybe) => { if (value) tags.set(tag, value); @@ -179,11 +192,14 @@ function promoteOCTGeometry(data: OCTDataset, tags: Map) { set(Tags.SpacingBetweenSlices, sliceSpacing); } -/** Application-only OCT eligibility and measurement metadata; raw core data stays unchanged. */ -export function dicomMetadataForDisplay(dataset: DicomDataset) { - const metadata = dicomDatasetToTags(dataset); +/** The tags en face decides on, with OCT geometry promoted out of its functional groups. */ +export function enFaceTags(dataset: DicomDataset) { + const metadata = EN_FACE_TAGS.flatMap((tag): [string, string][] => { + const value = getDatasetTag(dataset, tag); + return value === undefined ? [] : [[tag, value]]; + }); if (!isOCTMetadata(metadata)) return metadata; const tags = new Map(metadata); - promoteOCTGeometry(structuredOCTDataset(dataset), tags); + promoteOCTGeometry(dataset, tags); return [...tags]; } diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 323128b31..980783c3d 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -32,7 +32,7 @@ import { convertItkToVtkImage } from '@/src/io/convertItkToVtkImage'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; import { abortError, ensureError } from '@/src/utils'; -export type DicomVolumeImageEvents = ProgressiveImageEvents & { +type DicomVolumeImageEvents = ProgressiveImageEvents & { /** A decoded region of the current image, as an inclusive extent. */ extentLoaded: Extent; }; @@ -254,12 +254,16 @@ export default class DicomVolumeImage extends BaseProgressiveImage { private replaceContent(content: Content) { this.stopLoad(); this.content = content; - // A pending thumbnail settles from the new content instead. - if (!this.settleThumbnail) this.thumbnail = null; + this.forgetSettledThumbnail(); this.segBuildInfo = null; this.updateStatus(); } + // A pending thumbnail settles from what loads next instead. + private forgetSettledThumbnail() { + if (!this.settleThumbnail) this.thumbnail = null; + } + private replaceImage(image: vtkImageData) { const previous = this.vtkImageData.value; this.vtkImageData.value = image; @@ -327,6 +331,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { const { volume } = content; const image = this.vtkImageData.value; content.failed.clear(); + this.forgetSettledThumbnail(); const updates = loadVolume(volume, { runtime: this.init.runtime, signal, @@ -344,6 +349,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { signal: AbortSignal ) { content.failed = false; + this.forgetSettledThumbnail(); try { await this.readSegmentationContent(content, signal); } catch (error) { diff --git a/src/core/streaming/httpCodes.ts b/src/core/streaming/httpCodes.ts index 4a70c9eae..6e45e0c9a 100644 --- a/src/core/streaming/httpCodes.ts +++ b/src/core/streaming/httpCodes.ts @@ -1,6 +1,4 @@ export const HTTP_STATUS_OK = 200; -export const HTTP_STATUS_PARTIAL_CONTENT = 206; -export const HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416; export class HttpNotFound extends Error { constructor(url: string) { diff --git a/src/core/streaming/types.ts b/src/core/streaming/types.ts index 863594a74..c2641e707 100644 --- a/src/core/streaming/types.ts +++ b/src/core/streaming/types.ts @@ -1,10 +1,3 @@ -/** - * Init options for a Fetcher. - */ -export type FetcherInit = { - abortController?: AbortController; -}; - /** * A source of bytes that can be streamed from the start or taken whole. */ @@ -14,7 +7,5 @@ export type Fetcher = { blob(): Promise; close(): void; connected: boolean; - size: number; contentType?: string; - abortSignal?: AbortSignal; }; diff --git a/src/enface/__tests__/seriesGeometry.spec.ts b/src/enface/__tests__/seriesGeometry.spec.ts index 9bd5b0ad2..de9d6c0c5 100644 --- a/src/enface/__tests__/seriesGeometry.spec.ts +++ b/src/enface/__tests__/seriesGeometry.spec.ts @@ -12,7 +12,7 @@ import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { buildSyntheticDicom } from '@/tests/specs/syntheticDicom'; import { getEnFaceUnavailableReason } from '@/src/enface/availability'; import { getOccupiedDepthSupport } from '@/src/enface/occupiedDepthSupport'; -import { dicomMetadataForDisplay } from '@/src/core/streaming/dicom/octMetadata'; +import { enFaceTags } from '@/src/core/streaming/dicom/octMetadata'; import { dicomSeriesGeometry } from '@/src/core/streaming/dicom/seriesGeometry'; import { measureOccupiedDepth } from '@/src/segmentation/measurements/occupiedDepth'; import { datasetFromTags } from '@/tests/dicomDataset'; @@ -23,7 +23,7 @@ import { } from './dicomMetadataFixture'; const displayMetadata = (instance: Instance) => - new Map(dicomMetadataForDisplay(instance.dataset)); + new Map(enFaceTags(instance.dataset)); describe('assembled OCT series through real header and file collaborators', () => { beforeEach(() => setActivePinia(createPinia())); diff --git a/src/enface/availability.ts b/src/enface/availability.ts index 9ecbc624f..9ef665e7b 100644 --- a/src/enface/availability.ts +++ b/src/enface/availability.ts @@ -1,4 +1,4 @@ -import { dicomMetadataForDisplay } from '@/src/core/streaming/dicom/octMetadata'; +import { enFaceTags } from '@/src/core/streaming/dicom/octMetadata'; import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; @@ -53,7 +53,7 @@ function acquisitionReason(image: ProgressiveImage) { for (const { dataset: metadata } of image.getInstances()) { let reason = metadataReasons.get(metadata); if (reason === undefined) { - reason = acquisitionMetadataReason(dicomMetadataForDisplay(metadata)); + reason = acquisitionMetadataReason(enFaceTags(metadata)); metadataReasons.set(metadata, reason); } if (reason !== null) return reason; diff --git a/src/enface/occupiedDepthSupport.ts b/src/enface/occupiedDepthSupport.ts index b1a246e30..bc055a817 100644 --- a/src/enface/occupiedDepthSupport.ts +++ b/src/enface/occupiedDepthSupport.ts @@ -1,4 +1,4 @@ -import { dicomMetadataForDisplay } from '@/src/core/streaming/dicom/octMetadata'; +import { enFaceTags } from '@/src/core/streaming/dicom/octMetadata'; import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; @@ -7,7 +7,7 @@ import { Tags, unitToMm, type Instance } from '@/packages/dicom/core'; import { dicomSeriesGeometry } from '@/src/core/streaming/dicom/seriesGeometry'; function measurementMetadata(instance: Instance) { - const tags = new Map(dicomMetadataForDisplay(instance.dataset)); + const tags = new Map(enFaceTags(instance.dataset)); const regions = instance.ultrasoundRegions; if ( tags.get(Tags.Modality)?.trim() !== 'US' || diff --git a/src/io/__tests__/readDicomTags.differential.spec.ts b/src/io/__tests__/readDicomTags.differential.spec.ts deleted file mode 100644 index 65236cac6..000000000 --- a/src/io/__tests__/readDicomTags.differential.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * `readDicomTagsNode` runs the itk-wasm pipeline over a file path, with no - * worker and no browser, so the JS reader can be compared against it here. - * - * @vitest-environment node - */ -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { readDicomTagsNode } from '@itk-wasm/dicom'; -import { readDicomTags } from './readDicomTagsFixtures'; -import { tagReaderCorpus } from '@/tests/specs/dicomElementFixtures'; - -let workDir = ''; - -beforeAll(() => { - workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'volview-dicom-tags-')); -}); - -afterAll(() => { - fs.rmSync(workDir, { recursive: true, force: true }); -}); - -const itkTags = async (name: string, bytes: Uint8Array) => { - const file = path.join(workDir, `${name.replace(/[^a-z0-9]+/gi, '-')}.dcm`); - fs.writeFileSync(file, bytes); - const { tags } = await readDicomTagsNode(file); - return tags; -}; - -describe('readDicomTags against the itk-wasm reader', () => { - it.each(tagReaderCorpus())( - 'reads $name the same way', - async ({ name, bytes, itkDivergence = {} }) => { - const expected = await itkTags(name, bytes); - expect(expected.length).toBeGreaterThan(0); - // A divergence that no longer holds would silently weaken the comparison. - const stale = Object.keys(itkDivergence).filter((tag) => { - const itkValue = expected.find(([key]) => key === tag)?.[1]; - return itkValue === undefined || itkValue === itkDivergence[tag]; - }); - expect(stale).toEqual([]); - - expect(await readDicomTags(bytes)).toEqual( - expected.map(([tag, value]) => [tag, itkDivergence[tag] ?? value]) - ); - }, - 60000 - ); -}); diff --git a/src/io/__tests__/readDicomTags.spec.ts b/src/io/__tests__/readDicomTags.spec.ts deleted file mode 100644 index 932d26327..000000000 --- a/src/io/__tests__/readDicomTags.spec.ts +++ /dev/null @@ -1,469 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core'; -import { readDicomTags } from './readDicomTagsFixtures'; -import { - buildSlice, - CHINESE_NAME_BYTES, - CHINESE_NAME_PADDED, - GB18030_NAME_BYTES, - GB18030_NAME_PADDED, - JAPANESE_NAME, - KATAKANA_NAME, - KATAKANA_NAME_BYTES, - MIXED_JIS_NAME, - MIXED_JIS_NAME_BYTES, - MIXED_VR_ELEMENTS, - JAPANESE_NAME_BYTES, - KOREAN_NAME, - KOREAN_NAME_BYTES, - LATIN1_NAME_BYTES, - LATIN1_NAME_PADDED, - UTF8_NAME, - UTF8_NAME_BYTES, -} from '@/tests/specs/dicomElementFixtures'; -import { - buildSyntheticCineDicom, - rawElement, - stripFileMeta, - stripPreamble, -} from '@/tests/specs/syntheticDicom'; - -type TagPairs = ReadonlyArray; - -const valueOf = (tags: TagPairs, tag: string) => - tags.find(([name]) => name === tag)?.[1]; - -const keysOf = (tags: TagPairs) => tags.map(([name]) => name); - -const SPECIFIC_CHARACTER_SET = '0008|0005'; -const ICC_PROFILE = '0028|2000'; -const FRAME_INCREMENT_POINTER = '0028|0009'; -const FRAME_DIMENSION_POINTER = '0028|000a'; -const DIFFUSION_B_VALUE = '0018|9087'; -const DIFFUSION_GRADIENT_ORIENTATION = '0018|9089'; -const LUT_FRAME_RANGE = '0028|9459'; -const PIXEL_DATA = '7fe0|0010'; -const SEQUENCE_ITEM = 'fffe|e000'; -const CURRENT_PATIENT_LOCATION = '0038|0300'; -const STUDY_COMMENTS = '0032|4000'; - -const encodeUtf8 = (text: string) => new TextEncoder().encode(text); - -const bytes = (...values: number[]) => new Uint8Array(values); - -// A backslash inside an LT is a literal character, not a value delimiter, so it -// is the one place a JIS X 0201 file can show the yen sign. -const studyComments = (value: Uint8Array) => - rawElement(0x0032, 0x4000, 'LT', value); - -// (0038,0300) is LO, whose value multiplicity is 1-n. -const patientLocation = (value: Uint8Array) => - rawElement(0x0038, 0x0300, 'LO', value); - -const nameFromCharacterSet = async ( - specificCharacterSet: string, - patientNameBytes: Uint8Array -) => - valueOf( - await readDicomTags(buildSlice({ specificCharacterSet, patientNameBytes })), - Tags.PatientName - ); - -describe('readDicomTags', () => { - it('keys every pair with a lowercase group|element tag', async () => { - const tags = await readDicomTags(buildSlice()); - - expect(keysOf(tags).length).toBeGreaterThan(0); - expect( - keysOf(tags).filter((tag) => !/^[0-9a-f]{4}\|[0-9a-f]{4}$/.test(tag)) - ).toEqual([]); - expect(keysOf(tags)).toContain(Tags.SOPInstanceUID); - }); - - it('stringifies binary numeric VRs as plain decimals', async () => { - const tags = await readDicomTags( - buildSlice({ - rows: 3, - cols: 5, - bitsAllocated: 8, - bitsStored: 8, - highBit: 7, - }) - ); - - expect(valueOf(tags, Tags.Rows)).toBe('3'); - expect(valueOf(tags, Tags.Columns)).toBe('5'); - expect(valueOf(tags, Tags.BitsAllocated)).toBe('8'); - expect(valueOf(tags, Tags.BitsStored)).toBe('8'); - expect(valueOf(tags, Tags.SamplesPerPixel)).toBe('1'); - expect(valueOf(tags, Tags.PixelRepresentation)).toBe('0'); - }); - - it("joins multiple values with DICOM's own backslash", async () => { - const tags = await readDicomTags( - buildSlice({ - imageOrientationPatient: [1, 0, 0, 0, -1, 0], - imagePositionPatient: [1.5, -2, 3], - pixelSpacing: [0.5, 0.75], - }) - ); - - expect(valueOf(tags, Tags.ImagePositionPatient)).toBe('1.5\\-2\\3'); - expect(valueOf(tags, Tags.ImageOrientationPatient)).toBe( - '1\\0\\0\\0\\-1\\0' - ); - expect(valueOf(tags, Tags.PixelSpacing)).toBe('0.5\\0.75'); - }); - - it('keeps the trailing space padding of a text VR', async () => { - const tags = await readDicomTags( - buildSlice({ patientId: 'TEST001', seriesNumber: 1 }) - ); - - expect(valueOf(tags, Tags.PatientID)).toBe('TEST001 '); - expect(valueOf(tags, Tags.SeriesNumber)).toBe('1 '); - expect(valueOf(tags, Tags.ImagePositionPatient)).toBe('0\\0\\0 '); - }); - - it('strips the null padding of a UI value', async () => { - const tags = await readDicomTags( - buildSlice({ studyUid: '1.2.3', seriesUid: '1.2.4', sopUid: '1.2.5' }) - ); - - expect(valueOf(tags, Tags.StudyInstanceUID)).toBe('1.2.3'); - expect(valueOf(tags, Tags.SeriesInstanceUID)).toBe('1.2.4'); - expect(valueOf(tags, Tags.SOPInstanceUID)).toBe('1.2.5'); - }); - - it('passes a person name through unchanged', async () => { - const tags = await readDicomTags(buildSlice({ patientName: 'DOE^JOHN' })); - - expect(valueOf(tags, Tags.PatientName)).toBe('DOE^JOHN'); - }); - - it('reports a zero length element as an empty value', async () => { - const tags = await readDicomTags( - buildSlice({ patientNameBytes: new Uint8Array(0) }) - ); - - expect(keysOf(tags)).toContain(Tags.PatientName); - expect(valueOf(tags, Tags.PatientName)).toBe(''); - }); - - it('reports an empty character set when the file declares none', async () => { - const tags = await readDicomTags(buildSlice()); - - expect(keysOf(tags)).toContain(SPECIFIC_CHARACTER_SET); - expect(valueOf(tags, SPECIFIC_CHARACTER_SET)).toBe(''); - }); - - it('omits the file meta group', async () => { - const tags = await readDicomTags(buildSlice()); - - expect(keysOf(tags).filter((tag) => tag.startsWith('0002|'))).toEqual([]); - }); - - it('omits pixel data', async () => { - const tags = await readDicomTags(buildSlice()); - - expect(keysOf(tags)).not.toContain(PIXEL_DATA); - }); - - it('reads the header of a file truncated inside pixel data', async () => { - const whole = buildSlice({ rows: 4, cols: 4, bitsAllocated: 16 }); - // Drops all 32 pixel bytes and keeps the element header, so only a reader - // that stops at the pixel data tag can still return the header. - const truncated = whole.slice(0, whole.length - 4 * 4 * 2); - - expect(await readDicomTags(truncated)).toEqual(await readDicomTags(whole)); - }); - - it('omits sequences and the elements nested in them', async () => { - const tags = await readDicomTags( - buildSlice({ - ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, - }) - ); - - expect(keysOf(tags)).not.toContain(Tags.SequenceOfUltrasoundRegions); - expect(keysOf(tags)).not.toContain(Tags.PhysicalDeltaX); - expect(keysOf(tags)).not.toContain(SEQUENCE_ITEM); - expect(tags).toEqual(await readDicomTags(buildSlice())); - }); - - it('reads an implicit VR dataset the same as an explicit VR one', async () => { - expect(await readDicomTags(buildSlice({ implicitVr: true }))).toEqual( - await readDicomTags(buildSlice()) - ); - }); - - it('orders the pairs by tag', async () => { - // The cine fixture writes SeriesDescription after the 0028 group. - const tags = await readDicomTags( - buildSyntheticCineDicom({ - studyUid: '1.2.826.0.1.3680043.10.999.4', - seriesUid: '1.2.826.0.1.3680043.10.999.5', - sopUid: '1.2.826.0.1.3680043.10.999.6', - }) - ); - - expect(keysOf(tags)).toContain(Tags.SeriesDescription); - expect(keysOf(tags)).toEqual([...keysOf(tags)].sort()); - }); - - it('base64 encodes a binary buffer VR', async () => { - const tags = await readDicomTags( - buildSlice({ extraElements: MIXED_VR_ELEMENTS }) - ); - - expect(valueOf(tags, ICC_PROFILE)).toBe('f39/f39/f38='); - }); - - it('writes an attribute tag value as a parenthesised tag', async () => { - const tags = await readDicomTags( - buildSlice({ extraElements: MIXED_VR_ELEMENTS }) - ); - - expect(valueOf(tags, FRAME_INCREMENT_POINTER)).toBe('(0018,10ab)'); - expect(valueOf(tags, FRAME_DIMENSION_POINTER)).toBe( - '(0018,1063)\\(0028,00ff)' - ); - }); - - it('prints a binary float to six significant digits', async () => { - const tags = await readDicomTags( - buildSlice({ extraElements: MIXED_VR_ELEMENTS }) - ); - - expect(valueOf(tags, DIFFUSION_B_VALUE)).toBe('1.23457e+06'); - expect(valueOf(tags, DIFFUSION_GRADIENT_ORIENTATION)).toBe( - '3\\1.23457e-05\\-0.3' - ); - expect(valueOf(tags, LUT_FRAME_RANGE)).toBe('-2.5\\1e-30'); - }); - - it('omits private elements', async () => { - const tags = await readDicomTags( - buildSlice({ extraElements: MIXED_VR_ELEMENTS }) - ); - - expect( - keysOf(tags).filter( - (tag) => (Number.parseInt(tag.slice(0, 4), 16) & 1) === 1 - ) - ).toEqual([]); - }); - - it('reads a view that does not start at the head of its buffer', async () => { - const whole = buildSlice(); - const padded = new Uint8Array(whole.length + 3); - padded.set(whole, 3); - - expect(await readDicomTags(padded.subarray(3))).toEqual( - await readDicomTags(whole) - ); - }); - - it('rejects a buffer that is not a DICOM file', async () => { - const notDicom = new Uint8Array(256).fill(0x41); - - await expect( - Promise.resolve().then(() => readDicomTags(notDicom)) - ).rejects.toThrow(); - }); -}); - -describe('readDicomTags specific character set', () => { - it('keeps the declared character set as its own padded value', async () => { - const tags = await readDicomTags( - buildSlice({ - specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 149', - patientNameBytes: KOREAN_NAME_BYTES, - }) - ); - - expect(valueOf(tags, SPECIFIC_CHARACTER_SET)).toBe( - 'ISO 2022 IR 6\\ISO 2022 IR 149 ' - ); - }); - - it('decodes ISO 2022 IR 87', async () => { - expect( - await nameFromCharacterSet( - 'ISO 2022 IR 6\\ISO 2022 IR 87', - JAPANESE_NAME_BYTES - ) - ).toBe(JAPANESE_NAME); - }); - - it('decodes ISO 2022 IR 149', async () => { - expect( - await nameFromCharacterSet( - 'ISO 2022 IR 6\\ISO 2022 IR 149', - KOREAN_NAME_BYTES - ) - ).toBe(KOREAN_NAME); - }); - - it('decodes ISO 2022 IR 58', async () => { - expect( - await nameFromCharacterSet( - 'ISO 2022 IR 6\\ISO 2022 IR 58', - CHINESE_NAME_BYTES - ) - ).toBe(CHINESE_NAME_PADDED); - }); - - it('decodes GB18030, four byte code points included', async () => { - expect(await nameFromCharacterSet('GB18030', GB18030_NAME_BYTES)).toBe( - GB18030_NAME_PADDED - ); - }); - - it('decodes ISO_IR 192', async () => { - expect(await nameFromCharacterSet('ISO_IR 192', UTF8_NAME_BYTES)).toBe( - UTF8_NAME - ); - }); - - it('decodes ISO 2022 IR 13 half width katakana', async () => { - expect( - await nameFromCharacterSet( - 'ISO 2022 IR 13\\ISO 2022 IR 87', - KATAKANA_NAME_BYTES - ) - ).toBe(KATAKANA_NAME); - }); - - it('decodes a value that switches between IR 13 and IR 87', async () => { - expect( - await nameFromCharacterSet( - 'ISO 2022 IR 13\\ISO 2022 IR 87', - MIXED_JIS_NAME_BYTES - ) - ).toBe(MIXED_JIS_NAME); - }); - - it('renders 0x5c as a yen sign inside an LT when JIS X 0201 is declared', async () => { - const tags = await readDicomTags( - buildSlice({ - specificCharacterSet: 'ISO 2022 IR 13\\ISO 2022 IR 87', - extraElements: [studyComments(encodeUtf8('C:\\DICOM'))], - }) - ); - - expect(valueOf(tags, STUDY_COMMENTS)).toBe('C:\u00a5DICOM'); - }); - - it('keeps a numeric VR out of the character set conversion', async () => { - const tags = await readDicomTags( - buildSlice({ - specificCharacterSet: 'ISO 2022 IR 13\\ISO 2022 IR 87', - patientNameBytes: MIXED_JIS_NAME_BYTES, - imageOrientationPatient: [1, 0, 0, 0, -1, 0], - imagePositionPatient: [1.5, -2, 3], - pixelSpacing: [0.5, 0.75], - }) - ); - - expect(valueOf(tags, Tags.PatientName)).toBe(MIXED_JIS_NAME); - expect(valueOf(tags, Tags.ImageOrientationPatient)).toBe( - '1\\0\\0\\0\\-1\\0' - ); - expect(valueOf(tags, Tags.ImagePositionPatient)).toBe('1.5\\-2\\3'); - expect(valueOf(tags, Tags.PixelSpacing)).toBe('0.5\\0.75'); - }); - - it('decodes each value of a multi valued LO on its own', async () => { - const latin1 = await readDicomTags( - buildSlice({ - specificCharacterSet: 'ISO_IR 100', - extraElements: [ - patientLocation( - bytes( - 0x42, - 0xe4, - 0x63, - 0x6b, - 0x65, - 0x72, - 0x5c, - 0x4a, - 0xf6, - 0x72, - 0x67, - 0x20 - ) - ), - ], - }) - ); - const utf8 = await readDicomTags( - buildSlice({ - specificCharacterSet: 'ISO_IR 192', - extraElements: [patientLocation(encodeUtf8('\u738b\\\u5c0f\u660e'))], - }) - ); - - expect(valueOf(latin1, CURRENT_PATIENT_LOCATION)).toBe( - 'B\u00e4cker\\J\u00f6rg ' - ); - expect(valueOf(latin1, CURRENT_PATIENT_LOCATION)?.split('\\')).toEqual([ - 'B\u00e4cker', - 'J\u00f6rg ', - ]); - expect(valueOf(utf8, CURRENT_PATIENT_LOCATION)).toBe( - '\u738b\\\u5c0f\u660e' - ); - expect(valueOf(utf8, CURRENT_PATIENT_LOCATION)?.split('\\')).toEqual([ - '\u738b', - '\u5c0f\u660e', - ]); - }); - - it('keeps a multibyte character whose trailing byte delimits values', async () => { - const tags = await readDicomTags( - buildSlice({ - specificCharacterSet: 'GB18030', - extraElements: [patientLocation(bytes(0x81, 0x5c, 0x5c, 0x81, 0x40))], - }) - ); - - // GB18030 writes 0x5c as the second byte of a character, so only the lone - // one between the two characters separates values. - expect(valueOf(tags, CURRENT_PATIENT_LOCATION)).toBe('\u4e57\\\u4e02 '); - }); - - it('decodes ISO_IR 100', async () => { - expect(await nameFromCharacterSet('ISO_IR 100', LATIN1_NAME_BYTES)).toBe( - LATIN1_NAME_PADDED - ); - }); -}); - -describe('readDicomTags without a Part 10 header', () => { - it('reads a file with no preamble as the Part 10 file it came from', () => { - const file = buildSlice({ patientName: 'DOE^JOHN' }); - - expect(readDicomTags(stripPreamble(file))).toEqual(readDicomTags(file)); - }); - - it.each([ - ['explicit', false], - ['implicit', true], - ])( - 'reads a bare %s VR data set as the Part 10 file it came from', - (_kind, implicitVr) => { - const file = buildSlice({ patientName: 'DOE^JOHN', implicitVr }); - - const tags = readDicomTags(stripFileMeta(file)); - - expect(tags).toEqual(readDicomTags(file)); - expect(valueOf(tags, Tags.PatientName)).toBe('DOE^JOHN'); - } - ); - - it('rejects bytes that open with no element at all', () => { - expect(() => readDicomTags(new Uint8Array(512))).toThrow(/Not DICOM/); - }); -}); diff --git a/src/io/__tests__/readDicomTagsFixtures.ts b/src/io/__tests__/readDicomTagsFixtures.ts deleted file mode 100644 index d1a11ce24..000000000 --- a/src/io/__tests__/readDicomTagsFixtures.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { readDicomDataset } from '@/packages/dicom/core'; -import { dicomDatasetToTags } from '../readDicomTags'; - -export const readDicomTags = (bytes: Uint8Array) => - dicomDatasetToTags(readDicomDataset(bytes)); diff --git a/src/io/import/__tests__/dicomImportResults.spec.ts b/src/io/import/__tests__/dicomImportResults.spec.ts deleted file mode 100644 index 9efe8af31..000000000 --- a/src/io/import/__tests__/dicomImportResults.spec.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { beforeEach, expect, it } from 'vitest'; -import { createPinia, setActivePinia } from 'pinia'; -import { - buildStateIDToStoreID, - importDicomInstanceSources, - PartialDicomImportError, -} from '@/src/io/import/importDataSources'; -import { useDICOMStore } from '@/src/store/datasets-dicom'; -import { useDatasetStore } from '@/src/store/datasets'; -import type { - DicomInstanceSource, - DataSource, -} from '@/src/io/import/dataSource'; -import { - imageFactory, - sopOf, - unallocatableFor, -} from '@/src/store/__tests__/dicomImportFixtures'; - -const source = ( - sop: string, - stateID = sop, - series?: string -): DicomInstanceSource & DataSource => ({ - type: 'dicom', - instance: unallocatableFor({ sop, series }), - stateFileLeaf: { stateID }, -}); - -beforeEach(() => setActivePinia(createPinia())); - -it('returns a stable order regardless of series commit order', () => { - const sources = [source('a'), source('b')]; - const loadables = importDicomInstanceSources(sources, () => ({ - volumes: { b: [sources[1].instance], a: [sources[0].instance] }, - dissolved: [], - })); - expect(loadables.map(({ dataID }) => dataID)).toEqual(['a', 'b']); -}); - -it('maps only leaves supplied by this restore while saving full membership', () => { - const previous = source('previous', '1'); - importDicomInstanceSources([previous], (instances) => ({ - volumes: { existing: instances }, - dissolved: [], - })); - const current = source('current', '2'); - const other = source('other', '1'); - const loadables = importDicomInstanceSources([current, other], () => ({ - volumes: { - existing: [previous.instance, current.instance], - other: [other.instance], - }, - dissolved: [], - })); - expect(buildStateIDToStoreID(loadables)).toEqual({ - 1: 'other', - 2: 'existing', - }); - const saved = useDatasetStore().getDataSource('existing'); - expect(saved?.type === 'collection' && saved.sources).toEqual([ - previous, - current, - ]); -}); - -it('preserves the failure of every rejected series and blames its own sources', () => { - const first = source('first'); - const second = source('second', 'second', '2'); - const { createImage } = imageFactory(); - const failure = (() => { - try { - importDicomInstanceSources([first, second], (instances, hooks) => - useDICOMStore().importInstances(instances, { ...hooks, createImage }) - ); - return null; - } catch (error) { - return error; - } - })(); - if (!(failure instanceof PartialDicomImportError)) - throw new Error('Expected failed import'); - expect( - failure.failures.map(({ error, sources }) => [ - error.message, - sources.map(({ instance }) => sopOf(instance)), - ]) - ).toEqual([ - [expect.stringMatching(/rescale range/), ['first']], - [expect.stringMatching(/rescale range/), ['second']], - ]); -}); diff --git a/src/io/import/__tests__/dicomInstanceProvenance.spec.ts b/src/io/import/__tests__/dicomInstanceProvenance.spec.ts deleted file mode 100644 index b8769765f..000000000 --- a/src/io/import/__tests__/dicomInstanceProvenance.spec.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; -import { getDatasetTag, Tags } from '@/packages/dicom/core'; -import { beforeEach, describe, expect, it } from 'vitest'; -import { createPinia, setActivePinia } from 'pinia'; - -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; -import type { - DicomInstanceSource, - DataSource, -} from '@/src/io/import/dataSource'; -import { uriToDataSource } from '@/src/io/import/dataSource'; -import { importDicomInstanceSources } from '@/src/io/import/importDataSources'; -import { useDatasetStore } from '@/src/store/datasets'; -import type { ImportInstancesResult } from '@/src/store/datasets-dicom'; - -// A replan can fold one collection into another. The dataset the dissolved id -// owned has to go, and the survivor has to name the member it inherited, or a -// later save writes a dangling dataset and loses that instance. - -const instanceSourceFor = (sop: string) => { - const source: DataSource = { - type: 'dicom', - instance: instanceFor(datasetFromTags([[Tags.SOPInstanceUID, sop]])), - parent: uriToDataSource( - `https://ex/series/${sop}.dcm`, - `${sop}.dcm`, - FILE_EXT_TO_MIME.dcm - ), - }; - return source as DataSource & DicomInstanceSource; -}; - -const collectedSops = (dataSource: DataSource | undefined) => { - if (dataSource?.type !== 'collection') throw new Error('Expected collection'); - return dataSource.sources.map((src) => { - if (src.type !== 'dicom') throw new Error('Expected a DICOM source'); - return getDatasetTag(src.instance.dataset, Tags.SOPInstanceUID); - }); -}; - -describe('importDicomInstanceSources', () => { - beforeEach(() => { - setActivePinia(createPinia()); - }); - - it('inherits a moved member and drops the dissolved dataset', () => { - const datasetStore = useDatasetStore(); - const [a, b, c] = ['sop-a', 'sop-b', 'sop-c'].map(instanceSourceFor); - - // Stands in for the store: a dissolved id is removed during the commit. - const load = ( - sources: DicomInstanceSource[], - result: ImportInstancesResult - ) => - importDicomInstanceSources(sources, (_instances, { removeDissolved }) => { - result.dissolved.forEach(removeDissolved); - return result; - }); - - load([a, b], { - volumes: { 'vol-1': [a.instance], 'vol-2': [b.instance] }, - dissolved: [], - }); - expect(datasetStore.getDataSource('vol-2')).toBeDefined(); - - load([c], { - volumes: { 'vol-1': [a.instance, b.instance, c.instance] }, - dissolved: ['vol-2'], - }); - - expect(datasetStore.getDataSource('vol-2')).toBeUndefined(); - expect(collectedSops(datasetStore.getDataSource('vol-1'))).toEqual([ - 'sop-a', - 'sop-b', - 'sop-c', - ]); - }); -}); diff --git a/src/io/import/__tests__/importDicomInstanceSources.spec.ts b/src/io/import/__tests__/importDicomInstanceSources.spec.ts new file mode 100644 index 000000000..57f3dc38d --- /dev/null +++ b/src/io/import/__tests__/importDicomInstanceSources.spec.ts @@ -0,0 +1,233 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import { Tags, type Instance } from '@/packages/dicom/core'; +import { + buildStateIDToStoreID, + importDicomInstanceSources, +} from '@/src/io/import/importDataSources'; +import type { DicomInstanceSource } from '@/src/io/import/dataSource'; +import { useDICOMStore } from '@/src/store/datasets-dicom'; +import { useDatasetStore } from '@/src/store/datasets'; +import { useImageCacheStore } from '@/src/store/image-cache'; +import { + ALLOCATION_FAILURE, + imageFactory, + OTHER_SERIES_UID, + sliceFor, + sopOf, + sopsOfDataset, + sourceFor, + splitting, + unallocatableFor, +} from '@/src/store/__tests__/dicomImportFixtures'; + +beforeEach(() => setActivePinia(createPinia())); + +/** A source tied to a saved dataset, as a session restore supplies it. */ +const restored = (instance: Instance, stateID: string) => ({ + ...sourceFor(instance), + stateFileLeaf: { stateID }, +}); + +const idsOf = (loadables: { dataID: string }[]) => + loadables.map(({ dataID }) => dataID); + +describe('importDicomInstanceSources with a given commit', () => { + const sources = (...sops: string[]) => + sops.map((sop) => sourceFor(sliceFor({ sop }))); + + it('returns a stable order regardless of series commit order', () => { + const [a, b] = sources('a', 'b'); + const { loadables } = importDicomInstanceSources([a, b], () => ({ + volumes: { b: [b.instance], a: [a.instance] }, + failures: [], + })); + expect(idsOf(loadables)).toEqual(['a', 'b']); + }); + + it('maps only leaves supplied by this restore while saving full membership', () => { + const previous = restored(sliceFor({ sop: 'previous' }), '1'); + importDicomInstanceSources([previous], (instances) => ({ + volumes: { existing: instances }, + failures: [], + })); + const current = restored(sliceFor({ sop: 'current' }), '2'); + const other = restored(sliceFor({ sop: 'other' }), '1'); + const { loadables } = importDicomInstanceSources([current, other], () => ({ + volumes: { + existing: [previous.instance, current.instance], + other: [other.instance], + }, + failures: [], + })); + expect(buildStateIDToStoreID(loadables)).toEqual({ + 1: 'other', + 2: 'existing', + }); + expect(sopsOfDataset(useDatasetStore().getDataSource('existing'))).toEqual([ + 'previous', + 'current', + ]); + }); + + // A dissolved id is removed during the commit, as the store does it. + it('inherits a moved member and drops the dissolved dataset', () => { + const datasetStore = useDatasetStore(); + const [a, b, c] = sources('sop-a', 'sop-b', 'sop-c'); + const load = ( + supplied: DicomInstanceSource[], + volumes: Record, + dissolved: string[] = [] + ) => + importDicomInstanceSources( + supplied, + (_instances, { removeDissolved }) => { + dissolved.forEach(removeDissolved); + return { volumes, failures: [] }; + } + ); + + load([a, b], { 'vol-1': [a.instance], 'vol-2': [b.instance] }); + expect(datasetStore.getDataSource('vol-2')).toBeDefined(); + + load([c], { 'vol-1': [a.instance, b.instance, c.instance] }, ['vol-2']); + + expect(datasetStore.getDataSource('vol-2')).toBeUndefined(); + expect(sopsOfDataset(datasetStore.getDataSource('vol-1'))).toEqual([ + 'sop-a', + 'sop-b', + 'sop-c', + ]); + }); +}); + +describe('importDicomInstanceSources through the DICOM store', () => { + const load = (instances: Instance[]) => { + const { createImage } = imageFactory(); + return importDicomInstanceSources( + instances.map(sourceFor), + (batch, hooks) => + useDICOMStore().importInstances(batch, { createImage, ...hooks }) + ); + }; + + const failedSops = ({ failures }: ReturnType) => + failures.map(({ error, sources }) => [ + error.message, + sources.map(({ instance }) => sopOf(instance)), + ]); + + it('blames each rejected series on its own sources', () => { + const result = load([ + unallocatableFor({ sop: 'first' }), + unallocatableFor({ sop: 'second', series: OTHER_SERIES_UID }), + ]); + + expect(result.loadables).toEqual([]); + expect(failedSops(result)).toEqual([ + [expect.stringMatching(ALLOCATION_FAILURE), ['first']], + [expect.stringMatching(ALLOCATION_FAILURE), ['second']], + ]); + }); + + it('leaves the dataset list and its provenance unchanged when a commit fails', () => { + const { zero, one, two, three } = splitting(); + const datasetStore = useDatasetStore(); + const [id] = idsOf(load([one, three]).loadables); + + const result = load([zero, two, unallocatableFor({ sop: 'scout' })]); + + expect(result.loadables).toEqual([]); + expect(failedSops(result)).toEqual([ + [expect.stringMatching(ALLOCATION_FAILURE), ['sop-0', 'sop-2', 'scout']], + ]); + expect(datasetStore.idsAsSelections).toEqual([id]); + expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ + 'sop-1', + 'sop-3', + ]); + expect(Object.keys(useImageCacheStore().imageById)).toEqual([id]); + }); + + it('reports what a committed series landed beside the one that failed', () => { + const { zero, one, two, three } = splitting(); + const datasetStore = useDatasetStore(); + const [dissolvedId] = idsOf(load([one, three]).loadables); + + const result = load([ + zero, + two, + unallocatableFor({ sop: 'other', series: OTHER_SERIES_UID }), + ]); + + // A committed series must not be reported as loaded and failed at once. + expect(failedSops(result)).toEqual([ + [expect.stringMatching(ALLOCATION_FAILURE), ['other']], + ]); + // The committed series dissolved this collection, so its dataset went. + const ids = idsOf(result.loadables); + expect(ids).toHaveLength(2); + expect(ids).not.toContain(dissolvedId); + expect([...datasetStore.idsAsSelections].sort()).toEqual([...ids].sort()); + expect( + ids.map((id) => sopsOfDataset(datasetStore.getDataSource(id))) + ).toContainEqual(['sop-0', 'sop-1']); + }); + + it('grows a volume after the user removed its sibling', () => { + const datasetStore = useDatasetStore(); + const loaded = idsOf( + load([ + sliceFor({ sop: 'scout', rows: '8' }), + sliceFor({ sop: 'a', z: 0 }), + sliceFor({ sop: 'b', z: 1 }), + ]).loadables + ); + const idOf = (sops: string[]) => + loaded.find( + (id) => + sopsOfDataset(datasetStore.getDataSource(id)).join() === sops.join() + )!; + const scoutId = idOf(['scout']); + const id = idOf(['a', 'b']); + + datasetStore.remove(scoutId); + load([sliceFor({ sop: 'c', z: 2 })]); + + expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ + 'a', + 'b', + 'c', + ]); + expect(datasetStore.idsAsSelections).toEqual([id]); + }); + + it('repartitions saved provenance when a later import splits the series', () => { + const datasetStore = useDatasetStore(); + const pass = (number: string, zs: number[]) => + zs.map((z, i) => + sliceFor({ + sop: `acq${number}-${i}`, + z, + tags: { [Tags.AcquisitionNumber]: number }, + }) + ); + const first = pass('1', [0, 2.5, 5]); + const second = pass('2', [0.75, 3.25, 5.75]); + + const [firstId] = idsOf(load(first).loadables); + // The first pass is relabelled, which is not a volume this import loaded. + const [secondId, ...others] = idsOf(load(second).loadables); + + expect(others).toEqual([]); + expect(secondId).not.toBe(firstId); + // Each dataset saves exactly its own pass, so a restore replans them the + // same way and binds saved state to the right volume. + expect(sopsOfDataset(datasetStore.getDataSource(firstId))).toEqual( + first.map(sopOf) + ); + expect(sopsOfDataset(datasetStore.getDataSource(secondId))).toEqual( + second.map(sopOf) + ); + }); +}); diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 9d93deb93..85291a9dc 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -21,7 +21,6 @@ import { } from '@/src/io/import/dataSource'; import handleDicom from '@/src/io/import/processors/handleDicom'; import extractArchive from '@/src/io/import/processors/extractArchive'; -import extractArchiveTarget from '@/src/io/import/processors/extractArchiveTarget'; import handleAmazonS3 from '@/src/io/import/processors/handleAmazonS3'; import handleGoogleCloudStorage from '@/src/io/import/processors/handleGoogleCloudStorage'; import importSingleFile from '@/src/io/import/processors/importSingleFile'; @@ -45,10 +44,8 @@ import { ensureError } from '@/src/utils'; import type { Instance } from '@/packages/dicom/core'; import { useDatasetStore } from '@/src/store/datasets'; import { - PartialImportError, useDICOMStore, type ImportInstancesDeps, - type ImportInstancesResult, } from '@/src/store/datasets-dicom'; import { useMessageStore } from '@/src/store/messages'; import { shouldSkipImportSource } from '@/src/io/import/shouldSkipImportSource'; @@ -146,28 +143,6 @@ const sourcesOf = (instances: Instance[]) => .map((instance) => instanceToDataSource.get(instance)) .filter((src): src is DicomInstanceSource => src !== undefined); -/** - * A DICOM import where at least one series failed. The loadables the series - * that did commit produced ride along, because their datasets exist whether or - * not a sibling series threw. - */ -export class PartialDicomImportError extends Error { - readonly loadables: LoadableResult[]; - - readonly failures: { error: Error; sources: DicomInstanceSource[] }[]; - - constructor( - loadables: LoadableResult[], - failures: { error: Error; sources: DicomInstanceSource[] }[] - ) { - super(failures[0].error.message); - this.name = 'PartialDicomImportError'; - this.cause = failures[0].error; - this.loadables = loadables; - this.failures = failures; - } -} - /** What the import needs of its caller: how to remove a dissolved dataset. */ export type ImportInstancesHooks = Required< Pick @@ -176,85 +151,69 @@ export type ImportInstancesHooks = Required< const loadableOf = (id: string, sources: DicomInstanceSource[]) => asLoadableResult(id, { type: 'collection', sources }, 'image'); +/** + * Commits the instances series by series. The series that committed are + * loaded, so their datasets are reported beside the failures of the others. + */ export function importDicomInstanceSources( sources: DicomInstanceSource[], importInstances = (instances: Instance[], hooks: ImportInstancesHooks) => useDICOMStore().importInstances(instances, hooks) ) { - if (sources.length === 0) return []; + if (sources.length === 0) return { loadables: [], failures: [] }; sources.forEach((src) => instanceToDataSource.set(src.instance, src)); const supplied = new Set(sources); const datasetStore = useDatasetStore(); - // Every member reports back, so a collection that gained a member from a - // dissolved one saves its provenance too; the result names only this - // import's own sources. - const publish = ({ volumes }: ImportInstancesResult) => { - const entries = Object.entries(volumes); - datasetStore.addDataSources( - entries.map(([id, instances]) => loadableOf(id, sourcesOf(instances))) - ); - return entries - .sort(([a], [b]) => (a < b ? -1 : Number(a > b))) - .map(([id, instances]) => - loadableOf( - id, - sourcesOf(instances).filter((source) => supplied.has(source)) - ) - ); - }; // The dataset store's removal clears every store that names a dissolved // dataset, in the order eviction needs. - const hooks = { removeDissolved: (id: string) => datasetStore.remove(id) }; - - try { - return publish( - importInstances( - sources.map((src) => src.instance), - hooks + const { volumes, failures } = importInstances( + sources.map((src) => src.instance), + { removeDissolved: (id: string) => datasetStore.remove(id) } + ); + const entries = Object.entries(volumes); + // Every member reports back, so a collection that gained a member from a + // dissolved one saves its provenance too. The result names only this + // import's own sources, and no volume it brought none for. + datasetStore.addDataSources( + entries.map(([id, instances]) => loadableOf(id, sourcesOf(instances))) + ); + return { + loadables: entries + .map( + ([id, instances]) => + [ + id, + sourcesOf(instances).filter((source) => supplied.has(source)), + ] as const ) - ); - } catch (err) { - if (!(err instanceof PartialImportError)) throw err; - // The series that committed are reported beside the failure. - throw new PartialDicomImportError( - publish(err.committed), - err.failures.map(({ error, instances }) => ({ - error, - sources: sourcesOf(instances), - })) - ); - } + .filter(([, own]) => own.length > 0) + .sort(([a], [b]) => (a < b ? -1 : Number(a > b))) + .map(([id, own]) => loadableOf(id, own)), + failures: failures.map(({ error, instances }) => ({ + error, + sources: sourcesOf(instances), + })), + }; } -/** - * Imports a drained queue's DICOM instances. The series that committed are - * loaded, so their datasets are reported beside a failure rather than lost - * with it, and only the sources of the series that failed are blamed for it. - */ +/** Only the sources of a series that failed are blamed for its failure. */ function importDicomResults( sources: DicomInstanceSource[] ): ImportDataSourcesResult[] { - try { - return importDicomInstanceSources(sources); - } catch (err) { - const partial = err instanceof PartialDicomImportError ? err : null; - const failures = partial?.failures ?? [ - { error: ensureError(err), sources }, - ]; - return [ - ...(partial?.loadables ?? []), - ...failures.map(({ error, sources: failed }) => - asErrorResult( - error, - failed.length === 1 - ? failed[0] - : { type: 'collection', sources: failed.length ? failed : sources } - ) - ), - ]; - } + const { loadables, failures } = importDicomInstanceSources(sources); + return [ + ...loadables, + ...failures.map(({ error, sources: failed }) => + asErrorResult( + error, + failed.length === 1 + ? failed[0] + : { type: 'collection', sources: failed } + ) + ), + ]; } type ImportPolicy = 'application' | 'volume-data'; @@ -384,7 +343,6 @@ async function importDataSourcesWithPolicy( downloadStream, extractArchive, - extractArchiveTarget, importSingleFile, // catch any unhandled resource unhandledResource, diff --git a/src/io/import/processors/__tests__/handleDicom.spec.ts b/src/io/import/processors/__tests__/handleDicom.spec.ts index 08c181076..1d3163c59 100644 --- a/src/io/import/processors/__tests__/handleDicom.spec.ts +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -21,12 +21,8 @@ import type { Fetcher } from '@/src/core/streaming/types'; export const dicomFile = (bytes: Uint8Array, name = 'slice.dcm') => new File([bytes as BlobPart], name, { type: FILE_EXT_TO_MIME.dcm }); -/** - * A byte source that hands out its bytes a chunk at a time as the reader pulls - * them, so what a loader left undelivered says where it stopped. - */ -export const bytesFetcher = (bytes: Uint8Array, chunkSize = bytes.length) => { - let delivered = 0; +/** A fetcher over bytes held in memory. */ +export const bytesFetcher = (bytes: Uint8Array) => { let abortController: AbortController | null = null; const fetcher: Fetcher = { @@ -34,17 +30,15 @@ export const bytesFetcher = (bytes: Uint8Array, chunkSize = bytes.length) => { abortController ??= new AbortController(); }, getStream: () => { - let offset = 0; + let done = false; return new ReadableStream({ pull: (controller) => { - if (offset >= bytes.length) { + if (done) { controller.close(); return; } - const chunk = bytes.slice(offset, offset + chunkSize); - offset += chunk.length; - delivered += chunk.length; - controller.enqueue(chunk); + done = true; + controller.enqueue(bytes); }, }); }, @@ -56,13 +50,7 @@ export const bytesFetcher = (bytes: Uint8Array, chunkSize = bytes.length) => { get connected() { return !!abortController; }, - get size() { - return delivered; - }, contentType: FILE_EXT_TO_MIME.dcm, - get abortSignal() { - return abortController?.signal; - }, }; return fetcher; }; diff --git a/src/io/import/processors/extractArchiveTarget.ts b/src/io/import/processors/extractArchiveTarget.ts deleted file mode 100644 index 03eefe7ca..000000000 --- a/src/io/import/processors/extractArchiveTarget.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - asIntermediateResult, - ImportHandler, - isArchive, -} from '@/src/io/import/common'; -import { extractFileFromZip } from '@/src/io/zip'; -import { Skip } from '@/src/utils/evaluateChain'; - -/** - * Extracts a single target file from an archive. - * - * If the fileSrc already exists, nothing is done. Otherwise, attempt to - * extract the file from the parent archive. - * - * Input data source must be of the following form: - * { archiveSrc, parent: DataSource with a fileSrc } - * @param dataSource - * @returns - */ -const extractArchiveTarget: ImportHandler = async (dataSource) => { - if (dataSource.type !== 'archive') return Skip; - - if (!isArchive(dataSource.parent)) { - throw new Error('Parent is not a supported archive file'); - } - - const targetFile = await extractFileFromZip( - dataSource.parent.file, - dataSource.path - ); - - return asIntermediateResult([ - { - type: 'file', - file: targetFile, - fileType: '', - parent: dataSource, - }, - ]); -}; - -export default extractArchiveTarget; diff --git a/src/io/itk/worker.ts b/src/io/itk/worker.ts index a0ee451e5..e59c5e944 100644 --- a/src/io/itk/worker.ts +++ b/src/io/itk/worker.ts @@ -1,38 +1,13 @@ -import { readImageDicomFileSeriesWorkerFunction } from '@itk-wasm/dicom'; -import { WorkerPool, createWebWorker, setDefaultWebWorker } from 'itk-wasm'; +import { createWebWorker, setDefaultWebWorker } from 'itk-wasm'; -const DEFAULT_NUM_WORKERS = 4; - -let readDicomSeriesWorkerPool: WorkerPool | null = null; let webWorker: Worker | null = null; -export async function ensureWorker() { +export async function initItkWorker() { if (webWorker) return; webWorker = await createWebWorker(null); setDefaultWebWorker(webWorker); } -export function ensureDicomSeriesWorkerPool() { - if (readDicomSeriesWorkerPool) return; - // copied from read-image-dicom-file-series.ts - const numberOfWorkers = - typeof globalThis.navigator?.hardwareConcurrency === 'number' - ? globalThis.navigator.hardwareConcurrency - : DEFAULT_NUM_WORKERS; - readDicomSeriesWorkerPool = new WorkerPool( - numberOfWorkers, - readImageDicomFileSeriesWorkerFunction - ); -} - export function getWorker() { return webWorker; } - -export function getDicomSeriesWorkerPool() { - return readDicomSeriesWorkerPool; -} - -export async function initItkWorker() { - await Promise.all([ensureWorker(), ensureDicomSeriesWorkerPool()]); -} diff --git a/src/io/readDicomTags.ts b/src/io/readDicomTags.ts deleted file mode 100644 index 142702e71..000000000 --- a/src/io/readDicomTags.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { - isPrivateElement, - type DicomDataset, - type DicomElement, -} from '@/packages/dicom/core'; - -const SPECIFIC_CHARACTER_SET = '00080005'; - -const VALUE_DELIMITER = '\\'; - -/** VRs whose values are binary floats rather than text. */ -const FLOAT_VRS = new Set(['FD', 'FL', 'OD', 'OF']); - -/** Significant digits of a C++ `ostream`, which is what GDCM printed with. */ -const FLOAT_PRECISION = 6; - -const binaryString = (bytes: Uint8Array) => - Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''); - -const hexTag = (value: number) => value.toString(16).padStart(4, '0'); - -/** An AT value is a packed tag, which GDCM printed as `(gggg,eeee)`. */ -const attributeTagText = ({ - group, - element, -}: { - group: number; - element: number; -}) => `(${hexTag(group)},${hexTag(element)})`; - -/** C++ `ostream` default formatting, which is `%g` with six significant digits. */ -const floatText = (value: number) => { - if (!Number.isFinite(value)) return String(value); - const trim = (text: string) => - text.includes('.') ? text.replace(/0+$/, '').replace(/\.$/, '') : text; - const [mantissa, exponent] = value - .toExponential(FLOAT_PRECISION - 1) - .split('e'); - const power = Number(exponent); - return power < -4 || power >= FLOAT_PRECISION - ? `${trim(mantissa)}e${power < 0 ? '-' : '+'}${String(Math.abs(power)).padStart(2, '0')}` - : trim(value.toFixed(Math.max(0, FLOAT_PRECISION - 1 - power))); -}; - -const numberText = (vr: string, value: number) => - FLOAT_VRS.has(vr) || !Number.isInteger(value) - ? floatText(value) - : String(value); - -const byTag = (a: [string, string], b: [string, string]) => - Number(a[0] > b[0]) - Number(a[0] < b[0]); - -const itkTag = (tag: string) => - `${tag.slice(0, 4)}|${tag.slice(4)}`.toLowerCase(); - -const itkValue = ({ vr, values }: DicomElement) => { - switch (values.kind) { - case 'text': - return values.values.join(VALUE_DELIMITER); - case 'decimal': - return values.text.join(VALUE_DELIMITER); - case 'number': - return values.values - .map((value) => numberText(vr, value)) - .join(VALUE_DELIMITER); - case 'attributeTag': - return values.values.map(attributeTagText).join(VALUE_DELIMITER); - case 'bytes': - return values.values - .map((bytes) => btoa(binaryString(bytes))) - .join(VALUE_DELIMITER); - default: - return ''; - } -}; - -// GDCM reported no sequence and no private element, and an element it could not -// read did not reach its output either. -const reportedByItk = (element: DicomElement) => - !isPrivateElement(element) && - element.values.kind !== 'sequence' && - element.values.kind !== 'unread'; - -/** Projects structured metadata for VolView consumers of GDCM-shaped strings. */ -export function dicomDatasetToTags( - dataset: DicomDataset -): Array<[string, string]> { - const pairs = dataset.elements - .filter(reportedByItk) - .map((element): [string, string] => [ - itkTag(element.tag), - itkValue(element), - ]); - - // GDCM reported an empty Specific Character Set for a file that declares none. - const withCharset: Array<[string, string]> = - dataset.specificCharacterSet === null - ? [...pairs, [itkTag(SPECIFIC_CHARACTER_SET), '']] - : pairs; - - return withCharset.sort(byTag); -} diff --git a/src/io/zip.ts b/src/io/zip.ts index a72011468..d710ab0f4 100644 --- a/src/io/zip.ts +++ b/src/io/zip.ts @@ -30,19 +30,3 @@ export async function extractFilesFromZip(zipFile: File): Promise { }); }); } - -export async function extractFileFromZip( - zipFile: File, - filePath: string -): Promise { - const zip = await JSZip.loadAsync(zipFile); - const zippedFile = - zip.file(filePath) ?? zip.file(filePath.replace(/^\/+/, '')); - - if (!zippedFile) - throw new Error(`File ${filePath} does not exist in the zip file`); - if (zippedFile.dir) throw new Error(`Given file path is a directory`); - - const blob = await zippedFile.async('blob'); - return new File([blob], basename(zippedFile.name)); -} diff --git a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts index b1445ae29..f5972d567 100644 --- a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts +++ b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts @@ -1,12 +1,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags, type Instance } from '@/packages/dicom/core'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; -import { uriToDataSource, type DataSource } from '@/src/io/import/dataSource'; -import type { DicomInstanceSource } from '@/src/io/import/dataSource'; -import { importDicomInstanceSources } from '@/src/io/import/importDataSources'; -import { useDatasetStore } from '@/src/store/datasets'; +import { Tags } from '@/packages/dicom/core'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useMessageStore } from '@/src/store/messages'; import { @@ -16,8 +11,9 @@ import { } from '@/src/store/datasets-dicom'; import { imageFactory, + OTHER_SERIES_UID, + SERIES_UID, sliceFor, - sopOf, } from '@/src/store/__tests__/dicomImportFixtures'; // Slices of one acquisition, interleaved with a second acquisition's slices @@ -43,27 +39,6 @@ const labelsOf = (store: ReturnType) => .map((info) => info.splitLabel) .sort(); -const instanceSource = (instance: Instance) => { - const source: DataSource = { - type: 'dicom', - instance, - parent: uriToDataSource( - `https://example.test/${sopOf(instance)}.dcm`, - `${sopOf(instance)}.dcm`, - FILE_EXT_TO_MIME.dcm - ), - }; - return source as DataSource & DicomInstanceSource; -}; - -const sopsOf = (source: DataSource | undefined) => { - if (source?.type !== 'collection') throw new Error('Expected collection'); - return source.sources.map((member) => { - if (member.type !== 'dicom') throw new Error('Expected a DICOM source'); - return sopOf(member.instance); - }); -}; - describe('DICOM store acquisition split across imports', () => { beforeEach(() => { setActivePinia(createPinia()); @@ -105,7 +80,6 @@ describe('DICOM store acquisition split across imports', () => { // pass gets a fresh id. Nothing dissolves. expect(volumeIds(second)).toContain(firstId); expect(volumeIds(second)).toHaveLength(2); - expect(second.dissolved).toEqual([]); expect(store.volumeInfo[firstId].splitLabel).toBe('acquisition 1'); expect(labelsOf(store)).toEqual(['acquisition 1', 'acquisition 2']); expect(Object.keys(useImageCacheStore().imageById).sort()).toEqual( @@ -116,24 +90,6 @@ describe('DICOM store acquisition split across imports', () => { expect(created[0].getInstances()).toEqual(first); }); - it('does not duplicate a subset re-imported after the full series', () => { - const { createImage } = imageFactory(); - const store = useDICOMStore(); - - store.importInstances([...acquisitionOne(), ...acquisitionTwo()], { - createImage, - }); - const again = store.importInstances(acquisitionOne(), { - createImage, - }); - - expect(Object.keys(store.volumeInfo)).toHaveLength(2); - expect(again.dissolved).toEqual([]); - Object.values(again.volumes).forEach((members) => { - expect(members).toHaveLength(3); - }); - }); - it('keeps an established split when a later slice lacks the discriminator', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); @@ -142,10 +98,9 @@ describe('DICOM store acquisition split across imports', () => { createImage, }); const untagged = sliceFor({ sop: 'untagged', z: 1.5 }); - const result = store.importInstances([untagged], { createImage }); + store.importInstances([untagged], { createImage }); // The slice no axis can place forms its own volume; the two passes stay. - expect(result.dissolved).toEqual([]); expect(labelsOf(store)).toEqual([ 'acquisition 1', 'acquisition 2', @@ -212,6 +167,49 @@ describe('DICOM store acquisition split across imports', () => { ); }); + it('warns about each unsound volume, however alike their names', () => { + const { createImage } = imageFactory(); + const doubled = (series: string) => + [0, 2.5, 2.5, 5].map((z, i) => + sliceFor({ sop: `${series}-${i}`, series, z }) + ); + + useDICOMStore().importInstances(doubled(SERIES_UID), { createImage }); + useDICOMStore().importInstances(doubled(OTHER_SERIES_UID), { + createImage, + }); + + const details = useMessageStore().messages.map( + ({ options }) => options.details + ); + expect(details).toHaveLength(2); + expect(details[0]).toBe(details[1]); + }); + + it('warns about a volume a later import of its series leaves unsound', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + const unplaced = sliceFor({ + sop: 'unplaced', + tags: { [Tags.ImagePositionPatient]: '' }, + }); + + store.importInstances([unplaced], { createImage }); + expect(useMessageStore().messages).toHaveLength(0); + + store.importInstances(acquisitionOne(), { createImage }); + + const details = useMessageStore().messages.map( + ({ options }) => options.details + ); + expect(details).toEqual([ + expect.stringMatching( + /^Imported series \(position unknown\) holds slices whose position could not be read/ + ), + ]); + expect(labelsOf(store)).toEqual(['position unknown', undefined]); + }); + it('tells the user when a later import regroups a dataset away', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); @@ -223,9 +221,9 @@ describe('DICOM store acquisition split across imports', () => { const second = [tagged('c', 2, '1'), tagged('d', 0, '2')]; const [id] = volumeIds(store.importInstances(first, { createImage })); - const result = store.importInstances(second, { createImage }); + store.importInstances(second, { createImage }); - expect(result.dissolved).toEqual([id]); + expect(store.volumeInfo[id]).toBeUndefined(); const regrouped = useMessageStore().messages.filter((message) => /regrouped/.test(message.title) ); @@ -234,33 +232,4 @@ describe('DICOM store acquisition split across imports', () => { /^Imported series was regrouped/ ); }); - - it('repartitions saved provenance when a later import splits the series', () => { - const { createImage } = imageFactory(); - const datasetStore = useDatasetStore(); - const store = useDICOMStore(); - const first = acquisitionOne().map(instanceSource); - const second = acquisitionTwo().map(instanceSource); - const load = (sources: DicomInstanceSource[]) => { - const loadables = importDicomInstanceSources( - sources, - (instances, hooks) => - store.importInstances(instances, { createImage, ...hooks }) - ); - return loadables.map(({ dataID }) => dataID); - }; - - const [firstId] = load(first); - const ids = load(second); - const secondId = ids.find((id) => id !== firstId)!; - - // Each dataset saves exactly its own pass, so a restore replans them the - // same way and binds saved state to the right volume. - expect(sopsOf(datasetStore.getDataSource(firstId))).toEqual( - first.map((src) => sopOf(src.instance)) - ); - expect(sopsOf(datasetStore.getDataSource(secondId))).toEqual( - second.map((src) => sopOf(src.instance)) - ); - }); }); diff --git a/src/store/__tests__/datasets-dicom-cine.spec.ts b/src/store/__tests__/datasets-dicom-cine.spec.ts index c072abb5e..741a09d2b 100644 --- a/src/store/__tests__/datasets-dicom-cine.spec.ts +++ b/src/store/__tests__/datasets-dicom-cine.spec.ts @@ -1,14 +1,19 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags, type Instance } from '@/packages/dicom/core'; +import { Tags } from '@/packages/dicom/core'; import { cineInstance, TS_JPEG_BASELINE, } from '@/src/core/cine/__tests__/cineFixtures'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; import { useImageCacheStore } from '@/src/store/image-cache'; -import { imageFactory } from '@/src/store/__tests__/dicomImportFixtures'; +import { + imageFactory, + onlyId, + sliceFor, + STUDY_UID, +} from '@/src/store/__tests__/dicomImportFixtures'; import { useDICOMStore } from '@/src/store/datasets-dicom'; const SERIES = { @@ -23,12 +28,6 @@ const unsupported = () => [Tags.PhotometricInterpretation]: 'MONOCHROME1', }); -const onlyId = (volumes: Record) => { - const ids = Object.keys(volumes); - expect(ids).toHaveLength(1); - return ids[0]; -}; - describe('DICOM store cine routing', () => { beforeEach(() => { setActivePinia(createPinia()); @@ -44,7 +43,7 @@ describe('DICOM store cine routing', () => { expect(created).toHaveLength(1); expect(created[0].getInstances()).toEqual([clip]); - const id = onlyId(result.volumes); + const id = onlyId(result); expect(result.volumes[id]).toEqual([clip]); expect(useImageCacheStore().imageById[id]).toBe(created[0]); expect(store.volumeInfo[id]).toMatchObject({ @@ -66,9 +65,7 @@ describe('DICOM store cine routing', () => { ); const store = useDICOMStore(); - const id = onlyId( - store.importInstances([malformed], { createImage }).volumes - ); + const id = onlyId(store.importInstances([malformed], { createImage })); expect(created).toHaveLength(0); expect(store.volumeInfo[id].kind).toBe('cine'); @@ -83,32 +80,6 @@ describe('DICOM store cine routing', () => { expect(Object.keys(repeated.volumes)).toEqual(Object.keys(first.volumes)); expect(created).toHaveLength(1); }); - - it('refuses to reuse a cached image that is not a DICOM volume', () => { - const normalClip = () => - cineInstance({ - [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2', - [Tags.NumberOfFrames]: '1', - }); - - const learner = imageFactory(); - const learned = useDICOMStore().importInstances([normalClip()], { - createImage: learner.createImage, - }); - const id = onlyId(learned.volumes); - - // A fresh session plans the same id, but the cache holds a foreign image. - setActivePinia(createPinia()); - const imageCacheStore = useImageCacheStore(); - imageCacheStore.imageById[id] = - {} as (typeof imageCacheStore.imageById)[string]; - - const { created, createImage } = imageFactory(); - expect(() => - useDICOMStore().importInstances([normalClip()], { createImage }) - ).toThrow(/non-DICOM/); - expect(created).toHaveLength(0); - }); }); it('imports two same-shaped ultrasound clips as separate playable cine volumes', () => { @@ -133,3 +104,22 @@ it('imports two same-shaped ultrasound clips as separate playable cine volumes', ).toEqual([true, true]); expect(created).toHaveLength(0); }); + +it('files a clip and a volume of one study under one patient', () => { + setActivePinia(createPinia()); + const { createImage } = imageFactory(); + const store = useDICOMStore(); + // An odd-length value is padded with a space, which the reader keeps. + const padded = { + [Tags.PatientID]: 'patient-1 ', + [Tags.StudyInstanceUID]: STUDY_UID, + }; + + store.importInstances([sliceFor({ sop: 'still', tags: padded })], { + createImage, + }); + store.importInstances([cineInstance(padded)], { createImage }); + + expect(store.patientStudies).toEqual({ 'patient-1': [STUDY_UID] }); + expect(store.studyVolumes[STUDY_UID]).toHaveLength(2); +}); diff --git a/src/store/__tests__/datasets-dicom-geometry.spec.ts b/src/store/__tests__/datasets-dicom-geometry.spec.ts index ebdf64bb4..c42dd7bf3 100644 --- a/src/store/__tests__/datasets-dicom-geometry.spec.ts +++ b/src/store/__tests__/datasets-dicom-geometry.spec.ts @@ -6,6 +6,7 @@ import { useMessageStore } from '@/src/store/messages'; import { ALLOCATION_FAILURE, imageFactory, + onlyFailure, sliceFor, unallocatableFor, } from './dicomImportFixtures'; @@ -76,11 +77,13 @@ describe('planned DICOM geometry in the image cache', () => { const rest = slices(121).slice(1); // A sibling collection of the series cannot be allocated. - expect(() => - store.importInstances([...rest, unallocatableFor({ sop: 'scout' })], { - createImage, - }) - ).toThrow(ALLOCATION_FAILURE); + expect( + onlyFailure( + store.importInstances([...rest, unallocatableFor({ sop: 'scout' })], { + createImage, + }) + ) + ).toMatch(ALLOCATION_FAILURE); expect(image.getInstances()).toEqual([first]); expect(direction()).toEqual(TILTED); diff --git a/src/store/__tests__/datasets-dicom-reimport.spec.ts b/src/store/__tests__/datasets-dicom-reimport.spec.ts index 60e3fa785..6b93d442d 100644 --- a/src/store/__tests__/datasets-dicom-reimport.spec.ts +++ b/src/store/__tests__/datasets-dicom-reimport.spec.ts @@ -3,16 +3,15 @@ import { createPinia, setActivePinia } from 'pinia'; import type DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { useImageCacheStore } from '@/src/store/image-cache'; -import { - useDICOMStore, - type ImportInstancesResult, -} from '@/src/store/datasets-dicom'; +import { useDICOMStore } from '@/src/store/datasets-dicom'; import { untilLoaded } from '@/src/composables/untilLoaded'; import { mergingInstances } from '@/tests/dicomOrientationFixtures'; import { ALLOCATION_FAILURE, imageFactory, membersOf, + onlyFailure, + onlyId, OTHER_SERIES_UID, SERIES_UID, sliceFor, @@ -20,12 +19,6 @@ import { unallocatableFor, } from '@/src/store/__tests__/dicomImportFixtures'; -const onlyId = ({ volumes }: ImportInstancesResult) => { - const ids = Object.keys(volumes); - expect(ids).toHaveLength(1); - return ids[0]; -}; - const sliceValues = (image: DicomVolumeImage) => { const data = image.getVtkImageData(); const [columns, rows, slices] = data.getDimensions(); @@ -206,18 +199,18 @@ describe('DICOM store incremental import', () => { expect(imageCacheStore.imageById[dissolved]).toBeUndefined(); expect(store.studyVolumes[STUDY_UID]).toEqual([survivor]); expect(store.volumeInfo[survivor].NumberOfSlices).toBe(3); - // The caller has to drop the dataset the dissolved id owned, and the - // survivor has to carry the provenance of the member it inherited. - expect(merged.dissolved).toEqual([dissolved]); + // The survivor carries the provenance of the member it inherited. expect(merged.volumes[survivor]).toEqual([straight, tilted, between]); }); it('lets a corrected re-import replace the instance a failed import brought', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); - expect(() => - store.importInstances([unallocatableFor({ sop: 'a' })], { createImage }) - ).toThrow(ALLOCATION_FAILURE); + expect( + onlyFailure( + store.importInstances([unallocatableFor({ sop: 'a' })], { createImage }) + ) + ).toMatch(ALLOCATION_FAILURE); const corrected = sliceFor({ sop: 'a', rows: '8' }); store.importInstances([corrected], { createImage }); diff --git a/src/store/__tests__/datasets-dicom-transaction.spec.ts b/src/store/__tests__/datasets-dicom-transaction.spec.ts index 02def5b4c..08cd54148 100644 --- a/src/store/__tests__/datasets-dicom-transaction.spec.ts +++ b/src/store/__tests__/datasets-dicom-transaction.spec.ts @@ -1,70 +1,24 @@ -import { Tags, type Instance } from '@/packages/dicom/core'; +import { Tags } from '@/packages/dicom/core'; import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { nextTick } from 'vue'; -import type { - DicomInstanceSource, - DataSource, -} from '@/src/io/import/dataSource'; -import { uriToDataSource } from '@/src/io/import/dataSource'; -import { - importDicomInstanceSources, - PartialDicomImportError, -} from '@/src/io/import/importDataSources'; -import { useDatasetStore } from '@/src/store/datasets'; import { useImageCacheStore } from '@/src/store/image-cache'; import { untilLoaded } from '@/src/composables/untilLoaded'; -import { - useDICOMStore, - getDisplayName, - type ImportInstancesResult, -} from '@/src/store/datasets-dicom'; -import { tilt } from '@/tests/dicomOrientationFixtures'; +import { useDICOMStore, getDisplayName } from '@/src/store/datasets-dicom'; import { ALLOCATION_FAILURE, cineFor, imageFactory, membersOf, - OTHER_SERIES_UID, + onlyFailure, + onlyId, SERIES_UID, sliceFor, - sopOf, + splitting, STUDY_UID, unallocatableFor, } from '@/src/store/__tests__/dicomImportFixtures'; -const onlyId = ({ volumes }: ImportInstancesResult) => { - const ids = Object.keys(volumes); - expect(ids).toHaveLength(1); - return ids[0]; -}; - -/** The error a call throws, or null when it returns. */ -const failureOf = (run: () => unknown) => { - try { - run(); - return null; - } catch (error) { - return error; - } -}; - -/** - * Orientation agreement is a tolerance, so a bucket depends on which instance - * the walk meets first. `one` and `three` agree with each other and plan as a - * single collection; once `zero` and `two` arrive the walk starts from `zero`, - * and the pair splits into {zero, one} and {two, three}. Neither half holds a - * plurality of the committed collection, so both mint fresh IDs and the - * committed ID dissolves. - */ -const splitting = () => ({ - zero: sliceFor({ sop: 'sop-0', z: 0, orientation: tilt(0) }), - one: sliceFor({ sop: 'sop-1', z: 1, orientation: tilt(0.013) }), - two: sliceFor({ sop: 'sop-2', z: 2, orientation: tilt(0.039) }), - three: sliceFor({ sop: 'sop-3', z: 3, orientation: tilt(0.026) }), -}); - const cachedIds = () => Object.keys(useImageCacheStore().imageById); /** Loads the pair a later batch splits into two fresh collections. */ @@ -89,12 +43,14 @@ const growAndFail = async () => { await untilLoaded(id); const shown = created[0].getVtkImageData(); - expect(() => - store.importInstances( - [sliceFor({ sop: 'b', z: 1 }), unallocatableFor({ sop: 'scout' })], - { createImage } + expect( + onlyFailure( + store.importInstances( + [sliceFor({ sop: 'b', z: 1 }), unallocatableFor({ sop: 'scout' })], + { createImage } + ) ) - ).toThrow(ALLOCATION_FAILURE); + ).toMatch(ALLOCATION_FAILURE); return { store, id, first, created, shown }; }; @@ -108,16 +64,17 @@ describe('DICOM store atomic series commit', () => { const { created, createImage } = imageFactory(); const store = useDICOMStore(); - expect(() => - store.importInstances( - [ - unallocatableFor({ sop: 'scout' }), - sliceFor({ sop: 'a', z: 0 }), - sliceFor({ sop: 'b', z: 1 }), - ], - { createImage } - ) - ).toThrow(ALLOCATION_FAILURE); + const result = store.importInstances( + [ + unallocatableFor({ sop: 'scout' }), + sliceFor({ sop: 'a', z: 0 }), + sliceFor({ sop: 'b', z: 1 }), + ], + { createImage } + ); + + expect(onlyFailure(result)).toMatch(ALLOCATION_FAILURE); + expect(result.volumes).toEqual({}); expect(created).toEqual([]); expect(cachedIds()).toEqual([]); @@ -174,11 +131,13 @@ describe('DICOM store atomic series commit', () => { const { store, id, zero, two, loaded } = loadSplittablePair(); const failing = imageFactory(); - expect(() => - store.importInstances([zero, two, unallocatableFor({ sop: 'scout' })], { - createImage: failing.createImage, - }) - ).toThrow(ALLOCATION_FAILURE); + expect( + onlyFailure( + store.importInstances([zero, two, unallocatableFor({ sop: 'scout' })], { + createImage: failing.createImage, + }) + ) + ).toMatch(ALLOCATION_FAILURE); expect(cachedIds()).toEqual([id]); expect(store.volumeInfo[id].NumberOfSlices).toBe(2); @@ -191,13 +150,12 @@ describe('DICOM store atomic series commit', () => { const { store, id, zero, two } = loadSplittablePair(); const removed: string[] = []; - const result = store.importInstances([zero, two], { + store.importInstances([zero, two], { createImage: imageFactory().createImage, removeDissolved: (dissolved) => removed.push(dissolved), }); expect(removed).toEqual([id]); - expect(result.dissolved).toEqual([id]); // The removal is the caller's whole, so the store evicted nothing itself. expect(cachedIds()).toContain(id); expect(store.volumeInfo[id]).toBeDefined(); @@ -210,7 +168,6 @@ describe('DICOM store atomic series commit', () => { createImage: imageFactory().createImage, }); - expect(result.dissolved).toEqual([id]); const ids = Object.keys(result.volumes); expect(ids).toHaveLength(2); expect(ids).not.toContain(id); @@ -225,218 +182,24 @@ describe('DICOM store atomic series commit', () => { expect(Object.values(result.volumes)).toContainEqual([two, three]); }); - it('converges on the one-shot plan when one series arrives in two imports', () => { - const state = (created: ReturnType['created']) => { - const store = useDICOMStore(); - return { - volumes: Object.fromEntries( - Object.entries(store.volumeInfo).map(([id, info]) => [ - id, - info.NumberOfSlices, - ]) - ), - members: created.map(membersOf), - }; - }; - - const oneShot = () => { - setActivePinia(createPinia()); - const { created, createImage } = imageFactory(); - useDICOMStore().importInstances( - [sliceFor({ sop: 'a', z: 0 }), sliceFor({ sop: 'b', z: 1 })], - { createImage } - ); - return state(created); - }; - - const twice = () => { - setActivePinia(createPinia()); - const { created, createImage } = imageFactory(); - const store = useDICOMStore(); - store.importInstances([sliceFor({ sop: 'a', z: 0 })], { createImage }); - store.importInstances([sliceFor({ sop: 'b', z: 1 })], { createImage }); - return state(created); - }; - - expect(twice()).toEqual(oneShot()); - }); - it('registers no cine image when a sibling collection fails', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); - expect(() => - store.importInstances( - [cineFor('cine'), unallocatableFor({ sop: 'scout' })], - { createImage } + expect( + onlyFailure( + store.importInstances( + [cineFor('cine'), unallocatableFor({ sop: 'scout' })], + { createImage } + ) ) - ).toThrow(ALLOCATION_FAILURE); + ).toMatch(ALLOCATION_FAILURE); // A cine clip is planned like any other collection: it reaches no store alone. expect(cachedIds()).toEqual([]); expect(store.volumeInfo).toEqual({}); expect(store.studyVolumes).toEqual({}); }); - - it('releases the instances of a volume the user removed', async () => { - const store = useDICOMStore(); - let scoutRef!: WeakRef; - - // The series keeps its other collection, so nothing that outlives the - // import is emptied out from under the removed one. - await (async () => { - const scout = sliceFor({ sop: 'scout', rows: '8' }); - scoutRef = new WeakRef(scout); - const { createImage } = imageFactory(); - const { volumes } = store.importInstances( - [scout, sliceFor({ sop: 'a', z: 0 }), sliceFor({ sop: 'b', z: 1 })], - { createImage } - ); - const removed = Object.entries(volumes).find( - ([, instances]) => instances[0] === scout - )![0]; - await untilLoaded(removed); - useDatasetStore().remove(removed); - })(); - // Cache eviction disposes the image after the next flush. - await nextTick(); - // A WeakRef keeps its target until the current job ends, deterministically. - await new Promise((resolve) => { - setTimeout(resolve, 0); - }); - const { gc } = globalThis as { gc?: () => void }; - if (!gc) throw new Error('run vitest with --expose-gc'); - gc(); - - // Whatever the store and the registry still hold would pin the header. - expect(scoutRef.deref()).toBeUndefined(); - }); -}); - -const sourceFor = (instance: Instance) => { - const name = `${sopOf(instance)}.dcm`; - const source: DataSource = { - type: 'dicom', - instance, - parent: uriToDataSource(`https://ex/${name}`, name, 'application/dicom'), - }; - return source as DataSource & DicomInstanceSource; -}; - -const sopsOfDataset = (dataSource: DataSource | undefined) => { - if (dataSource?.type !== 'collection') throw new Error('Expected collection'); - return dataSource.sources.map((src) => { - if (src.type !== 'dicom') throw new Error('Expected a DICOM source'); - return sopOf(src.instance); - }); -}; - -/** The pipeline's own shape: committed series reach the dataset store. */ -const load = ( - instances: Instance[], - createImage = imageFactory().createImage -) => - importDicomInstanceSources(instances.map(sourceFor), (batch, hooks) => - useDICOMStore().importInstances(batch, { createImage, ...hooks }) - ); - -describe('importDicomInstanceSources atomic series commit', () => { - beforeEach(() => { - setActivePinia(createPinia()); - }); - - it('leaves the dataset list and its provenance unchanged when a commit fails', () => { - const { zero, one, two, three } = splitting(); - const store = useDICOMStore(); - const datasetStore = useDatasetStore(); - - const [loadable] = load([one, three]); - const id = loadable.dataID; - expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ - 'sop-1', - 'sop-3', - ]); - - expect(() => load([zero, two, unallocatableFor({ sop: 'scout' })])).toThrow( - ALLOCATION_FAILURE - ); - - expect(datasetStore.idsAsSelections).toEqual([id]); - expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ - 'sop-1', - 'sop-3', - ]); - expect(cachedIds()).toEqual([id]); - expect(store.volumeInfo[id].NumberOfSlices).toBe(2); - }); - - it('grows a volume after the user removed its sibling', () => { - const store = useDICOMStore(); - const datasetStore = useDatasetStore(); - - const loaded = load([ - sliceFor({ sop: 'scout', rows: '8' }), - sliceFor({ sop: 'a', z: 0 }), - sliceFor({ sop: 'b', z: 1 }), - ]); - const idOf = (sops: string[]) => - loaded.find( - ({ dataID }) => - sopsOfDataset(datasetStore.getDataSource(dataID)).join() === - sops.join() - )!.dataID; - const scoutId = idOf(['scout']); - const id = idOf(['a', 'b']); - - datasetStore.remove(scoutId); - load([sliceFor({ sop: 'c', z: 2 })]); - - expect(sopsOfDataset(datasetStore.getDataSource(id))).toEqual([ - 'a', - 'b', - 'c', - ]); - expect(store.volumeInfo[id].NumberOfSlices).toBe(3); - expect(datasetStore.getDataSource(scoutId)).toBeUndefined(); - expect(store.volumeInfo[scoutId]).toBeUndefined(); - }); - - it('reports what a committed series landed and blames only what failed', () => { - const { zero, one, two, three } = splitting(); - const store = useDICOMStore(); - const datasetStore = useDatasetStore(); - - const [loadable] = load([one, three]); - const dissolvedId = loadable.dataID; - - const failure = failureOf(() => - load([ - zero, - two, - unallocatableFor({ sop: 'other', series: OTHER_SERIES_UID }), - ]) - ); - - expect(failure).toBeInstanceOf(PartialDicomImportError); - expect((failure as Error).message).toMatch(ALLOCATION_FAILURE); - - // A committed series must not be reported as loaded and failed at once. - expect( - (failure as PartialDicomImportError).failures.flatMap(({ sources }) => - sources.map((src) => sopOf(src.instance)) - ) - ).toEqual(['other']); - - // The committed series dissolved this collection, so its dataset goes with it. - const landed = (failure as PartialDicomImportError).loadables; - const ids = landed.map(({ dataID }) => dataID); - expect(ids).toHaveLength(2); - expect(datasetStore.idsAsSelections.sort()).toEqual([...ids].sort()); - expect(store.volumeInfo[dissolvedId]).toBeUndefined(); - expect( - ids.map((id) => sopsOfDataset(datasetStore.getDataSource(id))) - ).toContainEqual(['sop-0', 'sop-1']); - }); }); describe('DICOM record naming', () => { diff --git a/src/store/__tests__/dicomImportFixtures.ts b/src/store/__tests__/dicomImportFixtures.ts index 2c8695edc..ef8c6ed76 100644 --- a/src/store/__tests__/dicomImportFixtures.ts +++ b/src/store/__tests__/dicomImportFixtures.ts @@ -8,9 +8,18 @@ import { type Instance, type WholeInstanceDecode, } from '@/packages/dicom/core'; +import { onTestFinished, expect } from 'vitest'; import { decodingWith } from '@/tests/dicomVolumeFixtures'; +import { tilt } from '@/tests/dicomOrientationFixtures'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { cineInstance } from '@/src/core/cine/__tests__/cineFixtures'; +import { + uriToDataSource, + type DataSource, + type DicomInstanceSource, +} from '@/src/io/import/dataSource'; +import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; +import type { ImportInstancesResult } from '@/src/store/datasets-dicom'; export const SERIES_UID = '1.2.826.0.1.3680043.9.7'; export const OTHER_SERIES_UID = '1.2.826.0.1.3680043.9.8'; @@ -70,6 +79,21 @@ export function sliceFor({ return instanceFor(datasetFromTags(merged), source); } +/** + * Orientation agreement is a tolerance, so a bucket depends on which instance + * the walk meets first. `one` and `three` agree with each other and plan as a + * single collection; once `zero` and `two` arrive the walk starts from `zero`, + * and the pair splits into {zero, one} and {two, three}. Neither half holds a + * plurality of the committed collection, so both mint fresh IDs and the + * committed ID dissolves. + */ +export const splitting = () => ({ + zero: sliceFor({ sop: 'sop-0', z: 0, orientation: tilt(0) }), + one: sliceFor({ sop: 'sop-1', z: 1, orientation: tilt(0.013) }), + two: sliceFor({ sop: 'sop-2', z: 2, orientation: tilt(0.039) }), + three: sliceFor({ sop: 'sop-3', z: 3, orientation: tilt(0.026) }), +}); + /** A header no buffer type can be chosen for, so allocating its volume fails. */ export const unallocatableFor = (options: SliceOptions) => sliceFor({ rows: '8', ...options, tags: { [Tags.BitsStored]: '' } }); @@ -79,6 +103,45 @@ export const ALLOCATION_FAILURE = /finite modality rescale range/; export const sopOf = (instance: Instance) => getDatasetTag(instance.dataset, Tags.SOPInstanceUID); +/** The one volume an import landed. */ +export const onlyId = ({ volumes }: Pick) => { + const ids = Object.keys(volumes); + expect(ids).toHaveLength(1); + return ids[0]; +}; + +/** The message of the one series an import could not commit. */ +export const onlyFailure = ({ + failures, +}: Pick) => { + expect(failures).toHaveLength(1); + return failures[0].error.message; +}; + +/** An instance as the import pipeline hands it on, read from a URL. */ +export const sourceFor = (instance: Instance) => { + const name = `${sopOf(instance)}.dcm`; + const source: DataSource = { + type: 'dicom', + instance, + parent: uriToDataSource( + `https://example.test/${name}`, + name, + FILE_EXT_TO_MIME.dcm + ), + }; + return source as DataSource & DicomInstanceSource; +}; + +/** The SOP Instance UIDs a dataset's saved provenance names, in order. */ +export const sopsOfDataset = (dataSource: DataSource | undefined) => { + if (dataSource?.type !== 'collection') throw new Error('Expected collection'); + return dataSource.sources.map((src) => { + if (src.type !== 'dicom') throw new Error('Expected a DICOM source'); + return sopOf(src.instance); + }); +}; + const numberTag = (instance: Instance, tag: string) => Number(getDatasetTag(instance.dataset, tag)); @@ -109,6 +172,9 @@ export function imageFactory( ...decodingWith(decoder), decodeConcurrency: 1, }); + // A load that outlives its test calls store actions later, and an action + // makes its own pinia the active one under whichever test runs then. + onTestFinished(() => runtime.dispose()); const created: DicomVolumeImage[] = []; const createImage = () => { const image = new DicomVolumeImage({ diff --git a/src/store/__tests__/image-cache.spec.ts b/src/store/__tests__/image-cache.spec.ts index 8e61ca589..f5a183655 100644 --- a/src/store/__tests__/image-cache.spec.ts +++ b/src/store/__tests__/image-cache.spec.ts @@ -4,6 +4,7 @@ import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { useImageCacheStore } from '@/src/store/image-cache'; +import { useMessageStore } from '@/src/store/messages'; import { LoadedVtkImage, type ProgressiveImage, @@ -50,7 +51,8 @@ describe('image cache lifecycle', () => { expect(store.getVtkImageData('img-1')).toBeNull(); }); - it('enables En face after a failed volume finishes a successful retry', () => { + // An image whose events the test fires, seated under 'retry'. + const seatLoading = () => { const store = seatImage(); const data = store.getVtkImageData('img-1')!; const image: ProgressiveImage = new LoadedVtkImage(data, 'Retry'); @@ -58,6 +60,30 @@ describe('image cache lifecycle', () => { image.addEventListener = events.on; image.removeEventListener = events.off; store.addProgressiveImage(image, { id: 'retry' }); + return events; + }; + + it('tells the user once per load which image lost slices', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const events = seatLoading(); + const titles = () => + useMessageStore().messages.map((message) => message.title); + + events.emit('loading', true); + ['slice 1', 'slice 2', 'slice 3'].forEach((slice) => + events.emit('error', new Error(slice)) + ); + events.emit('loading', false); + expect(titles()).toEqual(['Error loading Retry']); + expect(useImageCacheStore().imageErrors.retry).toHaveLength(3); + + events.emit('loading', true); + events.emit('error', new Error('slice 2')); + expect(titles()).toEqual(['Error loading Retry', 'Error loading Retry']); + }); + + it('enables En face after a failed volume finishes a successful retry', () => { + const events = seatLoading(); events.emit('error', new Error('decode failed')); expect(getEnFaceUnavailableReason('retry')).toBe( 'The volume failed to load completely.' diff --git a/src/store/datasets-dicom.ts b/src/store/datasets-dicom.ts index 7498cf43b..a42bb877d 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -1,13 +1,14 @@ -import { dicomDatasetToTags } from '@/src/io/readDicomTags'; import { defineStore } from 'pinia'; import { allocateVolume, emptyRegistry, forgetCollection, - getDatasetModality, + getDatasetTag, registerInstances, seriesKeyOf, Tags, + trimDicomPadding, + type DicomDataset, type Instance, type InstanceCollectionUpdate, type RegistryState, @@ -17,11 +18,7 @@ import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { ProgressiveImage } from '@/src/core/progressiveImage'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; -import { - isCineInstance, - readCineHeader, - type CineHeader, -} from '@/src/core/cine/cineInstance'; +import { isCineInstance, readCineHeader } from '@/src/core/cine/cineInstance'; import { surfaceWarning, useMessageStore } from '@/src/store/messages'; import { viewedSlice } from '@/src/store/dicom-viewed-slice'; import { ensureError, groupBy, removeFromArray } from '../utils'; @@ -102,7 +99,7 @@ export const getDisplayName = (info: VolumeInfo) => { const name = cleanupName(info.SeriesDescription || info.SeriesNumber) || info.SeriesInstanceUID || - info.VolumeID; + 'Unnamed series'; return info.splitLabel ? `${name} (${info.splitLabel})` : name; }; @@ -148,33 +145,11 @@ export type ImportInstancesResult = { // Collection ID to every instance whose provenance the collection now // covers, not just the ones this batch brought. volumes: Record; - // Collection IDs a replan dissolved. Their datasets must be removed. - dissolved: string[]; + // Each series commits on its own; these are the ones that did not. + failures: { error: Error; instances: Instance[] }[]; }; -/** - * A batch whose series did not all commit. Each series commits on its own, so - * `committed` holds what the series that did commit landed. - */ -export class PartialImportError extends Error { - readonly failures: { error: Error; instances: Instance[] }[]; - - readonly committed: ImportInstancesResult; - - constructor( - failures: { error: Error; instances: Instance[] }[], - committed: ImportInstancesResult - ) { - super(failures[0].error.message); - this.name = 'PartialImportError'; - this.cause = failures[0].error; - this.failures = failures; - this.committed = committed; - } -} - type DatabaseRecord = { - name: string; patient: PatientInfo; study: StudyInfo; volume: VolumeInfo; @@ -190,14 +165,38 @@ type DatabaseRecord = { type Candidate = { id: string; record: DatabaseRecord } & ( | { kind: 'keep' } | { kind: 'cine'; image: DicomCineImage } - | { kind: 'dicom'; fill: (image: DicomVolumeImage) => void } + | { + kind: 'dicom'; + shown: DicomVolumeImage | undefined; + fill: (image: DicomVolumeImage) => void; + } ); -const withDisplayName = ( - record: Omit -): DatabaseRecord => ({ - ...record, - name: getDisplayName(record.volume), +const text = (dataset: DicomDataset, tag: string) => + trimDicomPadding(getDatasetTag(dataset, tag) ?? ''); + +// Trimmed, so a clip and a volume of one study share their patient key. +const describeSeries = (dataset: DicomDataset) => ({ + patient: { + PatientID: text(dataset, Tags.PatientID), + PatientName: text(dataset, Tags.PatientName), + PatientBirthDate: text(dataset, Tags.PatientBirthDate), + PatientSex: text(dataset, Tags.PatientSex), + }, + study: { + StudyID: text(dataset, Tags.StudyID), + StudyInstanceUID: text(dataset, Tags.StudyInstanceUID), + StudyDate: text(dataset, Tags.StudyDate), + StudyTime: text(dataset, Tags.StudyTime), + AccessionNumber: text(dataset, Tags.AccessionNumber), + StudyDescription: text(dataset, Tags.StudyDescription), + }, + series: { + Modality: text(dataset, Tags.Modality), + SeriesInstanceUID: text(dataset, Tags.SeriesInstanceUID), + SeriesNumber: text(dataset, Tags.SeriesNumber), + SeriesDescription: text(dataset, Tags.SeriesDescription), + }, }); const volumeRecord = ({ @@ -206,57 +205,45 @@ const volumeRecord = ({ collection, }: InstanceCollectionUpdate): DatabaseRecord => { const { dataset } = members[0]; - const metadata = Object.fromEntries(dicomDatasetToTags(dataset)); - const frames = parseInt(metadata[Tags.NumberOfFrames] ?? '1', 10); - return withDisplayName({ - patient: { - PatientID: metadata[Tags.PatientID], - PatientName: metadata[Tags.PatientName], - PatientBirthDate: metadata[Tags.PatientBirthDate], - PatientSex: metadata[Tags.PatientSex], - }, - study: { - StudyID: metadata[Tags.StudyID], - StudyInstanceUID: metadata[Tags.StudyInstanceUID], - StudyDate: metadata[Tags.StudyDate], - StudyTime: metadata[Tags.StudyTime], - AccessionNumber: metadata[Tags.AccessionNumber], - StudyDescription: metadata[Tags.StudyDescription], - }, + const { patient, study, series } = describeSeries(dataset); + const frames = parseInt(text(dataset, Tags.NumberOfFrames) || '1', 10); + return { + patient, + study, volume: { NumberOfSlices: members.length === 1 && frames > 1 ? frames : members.length, VolumeID: id, - Modality: getDatasetModality(dataset) ?? '', - SeriesInstanceUID: metadata[Tags.SeriesInstanceUID], - SeriesNumber: metadata[Tags.SeriesNumber], - SeriesDescription: metadata[Tags.SeriesDescription], - WindowLevel: metadata[Tags.WindowLevel], - WindowWidth: metadata[Tags.WindowWidth], + ...series, + WindowLevel: text(dataset, Tags.WindowLevel), + WindowWidth: text(dataset, Tags.WindowWidth), ...(collection.label === null ? {} : { splitLabel: collection.label }), kind: 'volume', }, warnings: collection.warnings, - }); + }; }; -const cineRecord = (id: string, header: CineHeader): DatabaseRecord => - withDisplayName({ - patient: header.patient, - study: header.study, +const cineRecord = ( + id: string, + clip: Instance, + numberOfFrames: number +): DatabaseRecord => { + const { patient, study, series } = describeSeries(clip.dataset); + return { + patient, + study, volume: { - NumberOfSlices: header.numberOfFrames, + NumberOfSlices: numberOfFrames, VolumeID: id, - Modality: header.series.Modality, - SeriesInstanceUID: header.series.SeriesInstanceUID, - SeriesNumber: header.series.SeriesNumber, - SeriesDescription: header.series.SeriesDescription, + ...series, WindowLevel: '', WindowWidth: '', kind: 'cine', }, warnings: [], - }); + }; +}; const cineMember = ({ kind, members }: InstanceCollectionUpdate) => kind === 'image' && members.length === 1 && isCineInstance(members[0]) @@ -269,7 +256,7 @@ function cineCandidate( cached: ProgressiveImage | undefined ): Candidate { const header = readCineHeader(clip); - const record = cineRecord(id, header); + const record = cineRecord(id, clip, header.numberOfFrames); return cached ? { kind: 'keep', id, record } : { kind: 'cine', id, record, image: new DicomCineImage(clip, header) }; @@ -278,7 +265,7 @@ function cineCandidate( function fillFor(update: InstanceCollectionUpdate, previous?: Volume) { if (update.kind === 'segmentation') return (image: DicomVolumeImage) => image.setSegmentation(update.members); - const volume = allocateVolume(update, {}, previous); + const volume = allocateVolume(update, previous); return (image: DicomVolumeImage) => { image.setVolume(volume); volume.warnings.forEach(([title, details]) => @@ -297,15 +284,13 @@ function planCandidate(update: InstanceCollectionUpdate): Candidate { // A re-import retries whatever failed to load. if (cached && update.change === 'unchanged') return { kind: 'keep', id, record }; - if (cached && !(cached instanceof DicomVolumeImage)) - throw new Error( - `Volume ${id} is already loaded as a non-DICOM progressive image; cannot re-import it as a DICOM volume.` - ); + const shown = cached instanceof DicomVolumeImage ? cached : undefined; return { kind: 'dicom', id, record, - fill: fillFor(update, cached?.getVolume() ?? undefined), + shown, + fill: fillFor(update, shown?.getVolume() ?? undefined), }; } @@ -318,13 +303,28 @@ type CommitTarget = { volumeInfo: Record; }; -const warnUnsound = (name: string, warnings: string[]) => - warnings.forEach((warning) => - useMessageStore().addWarning( - 'A DICOM series did not load as one sound volume', - `${name} ${warning}` - ) - ); +const UNSOUND_TITLE = 'A DICOM series did not load as one sound volume'; + +// What each volume was last warned about, kept outside reactive state like +// the registry below, so a re-import raises only what is new. +const warned = new WeakMap>>(); + +function warnUnsound( + store: object, + id: string, + name: string, + warnings: string[] +) { + const byVolume = warned.get(store) ?? new Map>(); + warned.set(store, byVolume); + const before = byVolume.get(id); + warnings + .filter((warning) => !before?.has(warning)) + .forEach((warning) => + useMessageStore().addWarning(UNSOUND_TITLE, `${name} ${warning}`) + ); + byVolume.set(id, new Set(warnings)); +} /** Puts a candidate's image in the cache, reusing the one it replaces. */ function showCandidate( @@ -337,10 +337,9 @@ function showCandidate( cache.addProgressiveImage(candidate.image, { id }); return candidate.image; } - const cached = cache.imageById[id] as DicomVolumeImage | undefined; - const image = cached ?? createImage(id); + const image = candidate.shown ?? createImage(id); candidate.fill(image); - if (cached) image.startLoad(); + if (candidate.shown) image.startLoad(); else cache.addProgressiveImage(image, { id }); return image; } @@ -350,8 +349,10 @@ function commitCandidate( candidate: Candidate, createImage: (id: string) => DicomVolumeImage ) { - const { patient, study, volume, warnings, name } = candidate.record; + const { patient, study, volume, warnings } = candidate.record; + const name = getDisplayName(volume); store._updateDatabase(patient, study, volume); + warnUnsound(store, candidate.id, name, warnings); if (candidate.kind === 'keep') { const image = useImageCacheStore().imageById[candidate.id]; image?.setName(name); @@ -359,7 +360,6 @@ function commitCandidate( return; } showCandidate(candidate, createImage).setName(name); - warnUnsound(name, warnings); } function reportDissolved( @@ -425,25 +425,20 @@ export const useDICOMStore = defineStore('dicom', { this.deleteVolume(id); useImageCacheStore().removeImage(id); }); - const failures: PartialImportError['failures'] = []; - const results = [ + const failures: ImportInstancesResult['failures'] = []; + const committed = [ ...groupBy(instances, (instance) => seriesKeyOf(instance.dataset)), ].flatMap(([, batch]) => { try { - return [this._commitSeries(batch, { createImage, removeDissolved })]; + return Object.entries( + this._commitSeries(batch, { createImage, removeDissolved }) + ); } catch (error) { failures.push({ error: ensureError(error), instances: batch }); return []; } }); - const committed = { - volumes: Object.fromEntries( - results.flatMap(({ volumes }) => Object.entries(volumes)) - ), - dissolved: results.flatMap(({ dissolved }) => dissolved), - }; - if (failures.length) throw new PartialImportError(failures, committed); - return committed; + return { volumes: Object.fromEntries(committed), failures }; }, _commitSeries( @@ -452,7 +447,7 @@ export const useDICOMStore = defineStore('dicom', { createImage: (id: string) => DicomVolumeImage; removeDissolved: (id: string) => void; } - ): ImportInstancesResult { + ): ImportInstancesResult['volumes'] { const { state, updates, removed, conflictingInstanceUids } = registerInstances(registryOf(this), batch); const candidates = updates.map(planCandidate); @@ -463,12 +458,9 @@ export const useDICOMStore = defineStore('dicom', { ); reportDissolved(this, removed, context.removeDissolved); reportConflicts(conflictingInstanceUids); - return { - volumes: Object.fromEntries( - updates.map(({ id, provenance }) => [id, provenance]) - ), - dissolved: removed, - }; + return Object.fromEntries( + updates.map(({ id, provenance }) => [id, provenance]) + ); }, _updateDatabase( @@ -504,6 +496,7 @@ export const useDICOMStore = defineStore('dicom', { // remove files/images/layers associated with the volume deleteVolume(volumeKey: string) { registries.set(this, forgetCollection(registryOf(this), volumeKey)); + warned.get(this)?.delete(volumeKey); if (volumeKey in this.volumeInfo) { const studyKey = this.volumeStudy[volumeKey]; diff --git a/src/store/datasets-layers.ts b/src/store/datasets-layers.ts index c5dd53f5f..48978d733 100644 --- a/src/store/datasets-layers.ts +++ b/src/store/datasets-layers.ts @@ -25,7 +25,7 @@ export const useLayersStore = defineStore('layer', () => { async function buildLayerImage(parent: DataSelection, layer: Layer) { const { selection: source, id } = layer; - // ensureSameSpace need final image array to resample, so wait for all chunks + // ensureSameSpace need final image array to resample, so wait for all slices await untilLoaded(source); const [parentImage, sourceImage] = await Promise.all( diff --git a/src/store/image-cache.ts b/src/store/image-cache.ts index 2f6dd11c1..6d6dff169 100644 --- a/src/store/image-cache.ts +++ b/src/store/image-cache.ts @@ -58,12 +58,14 @@ export const useImageCacheStore = defineStore('image-cache', () => { if (loading && !imageLoading[id]) delete imageErrors[id]; imageLoading[id] = loading; }; + // One notice per load: a failed series reports every slice it lost. const onError = (error: Error) => { imageErrors[id] ??= []; imageErrors[id].push(error); - - const messageStore = useMessageStore(); - messageStore.addError('Error loading DICOM data', { error }); + if (imageErrors[id].length === 1) + useMessageStore().addError(`Error loading ${data.getName()}`, { + error, + }); }; imageListenerCleanup[id] = () => { diff --git a/src/utils/parseContentRangeHeader.ts b/src/utils/parseContentRangeHeader.ts deleted file mode 100644 index 4e798f127..000000000 --- a/src/utils/parseContentRangeHeader.ts +++ /dev/null @@ -1,40 +0,0 @@ -const CONTENT_RANGE_REGEXP = - /^bytes (?(?\d+)-(?\d+)|\*)\/(?\d+|\*)$/; - -export type ContentRange = - | { type: 'empty-range' } - | { type: 'invalid-range' } - | { type: 'unsatisfied-range'; length: number } - | { type: 'range'; start: number; end: number; length: number | null }; - -/** - * Parses a Content-Range header. - * - * Only supports bytes ranges. - * @param headerValue - * @returns - */ -export function parseContentRangeHeader( - headerValue: string | null -): ContentRange { - if (headerValue == null) return { type: 'empty-range' }; - - const match = CONTENT_RANGE_REGEXP.exec(headerValue); - const groups = match?.groups; - if (!groups) return { type: 'invalid-range' }; - - const length = groups.length === '*' ? null : parseInt(groups.length, 10); - - if (groups.range === '*') { - if (length === null) return { type: 'invalid-range' }; - return { type: 'unsatisfied-range', length }; - } - - const start = parseInt(groups.start, 10); - const end = parseInt(groups.end, 10); - - if (end < start || (length !== null && length <= end)) - return { type: 'invalid-range' }; - - return { type: 'range', start, end, length }; -} diff --git a/tests/datasets.ts b/tests/datasets.ts index 613f74269..f044a7749 100644 --- a/tests/datasets.ts +++ b/tests/datasets.ts @@ -1,6 +1,7 @@ // Every file the suite fetches from the internet. The runner downloads them // into the dataset cache before any spec starts, and specs read them from the -// local server at `/tmp/`. CI keys its dataset cache on this file. +// local server at `/tmp/`. CI keys its dataset cache on this file and the +// two corpus manifests it imports. // // Release fixtures and original public DICOM instances are pinned by SHA-256. import dicomVolumeCorpus from './dicomVolumeCorpus.json' with { type: 'json' }; @@ -136,7 +137,7 @@ export const PET_CT_DICOM_DATASETS = compositionCorpus.datasets.filter( export const TEST_DATASETS = [ ...Object.values(DATASETS), ...compositionCorpus.datasets, - ...dicomVolumeCorpus, + ...dicomVolumeCorpus.datasets, ]; export type TestDataset = (typeof TEST_DATASETS)[number]; diff --git a/tests/dicomCompositionCorpus.json b/tests/dicomCompositionCorpus.json index 8aa00004d..afb8e95d9 100644 --- a/tests/dicomCompositionCorpus.json +++ b/tests/dicomCompositionCorpus.json @@ -619,90 +619,24 @@ "1.3.6.1.4.1.14519.5.2.1.6655.2359.243468898389109491372438016818" ], "expected": { - "dimensions": [ - 512, - 512, - 10 - ], - "spacing": [ - 0.9765625, - 0.9765625, - 1.0 - ], - "origin": [ - -249.51171875, - -429.51171875, - -373.0 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ], - "range": [ - -1024.0, - 1310.0 - ], + "dimensions": [512, 512, 10], + "spacing": [0.9765625, 0.9765625, 1.0], + "origin": [-249.51171875, -429.51171875, -373.0], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], + "range": [-1024.0, 1310.0], "pixelHash": "2ad22501d69427486583b99b0950b18db4deadccdde5910e5e54214eaed06474", - "firstPlanePosition": [ - -249.51171875, - -429.51171875, - -373.0 - ], - "lastPlanePosition": [ - -249.51171875, - -429.51171875, - -364.0 - ] + "firstPlanePosition": [-249.51171875, -429.51171875, -373.0], + "lastPlanePosition": [-249.51171875, -429.51171875, -364.0] }, "initial": { - "dimensions": [ - 512, - 512, - 5 - ], - "spacing": [ - 0.9765625, - 0.9765625, - 2.0 - ], - "origin": [ - -249.51171875, - -429.51171875, - -373.0 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ], - "range": [ - -1024.0, - 1310.0 - ], + "dimensions": [512, 512, 5], + "spacing": [0.9765625, 0.9765625, 2.0], + "origin": [-249.51171875, -429.51171875, -373.0], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], + "range": [-1024.0, 1310.0], "pixelHash": "cba4f6107835fa368f6c260f1ed19dd0168afebac0efe03219f9bcc7342c8a77", - "firstPlanePosition": [ - -249.51171875, - -429.51171875, - -373.0 - ], - "lastPlanePosition": [ - -249.51171875, - -429.51171875, - -365.0 - ] + "firstPlanePosition": [-249.51171875, -429.51171875, -373.0], + "lastPlanePosition": [-249.51171875, -429.51171875, -365.0] }, "provenance": { "collection": "lung_pet_ct_dx", @@ -739,90 +673,24 @@ "1.3.6.1.4.1.14519.5.2.1.6655.2359.190211187176681563808826571096" ], "expected": { - "dimensions": [ - 200, - 200, - 10 - ], - "spacing": [ - 4.07283, - 4.07283, - 3.0 - ], - "origin": [ - -407.316, - -586.743, - -383.0 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ], - "range": [ - 0.0, - 21397.83203125 - ], + "dimensions": [200, 200, 10], + "spacing": [4.07283, 4.07283, 3.0], + "origin": [-407.316, -586.743, -383.0], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], + "range": [0.0, 21397.83203125], "pixelHash": "5d594a7f8eba4fadb4a6e013f29783bed9595f8577b04fb184772463bf0bc8b0", - "firstPlanePosition": [ - -407.316, - -586.743, - -383.0 - ], - "lastPlanePosition": [ - -407.316, - -586.743, - -356.0 - ] + "firstPlanePosition": [-407.316, -586.743, -383.0], + "lastPlanePosition": [-407.316, -586.743, -356.0] }, "initial": { - "dimensions": [ - 200, - 200, - 5 - ], - "spacing": [ - 4.07283, - 4.07283, - 6.0 - ], - "origin": [ - -407.316, - -586.743, - -383.0 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ], - "range": [ - 0.0, - 21397.83203125 - ], + "dimensions": [200, 200, 5], + "spacing": [4.07283, 4.07283, 6.0], + "origin": [-407.316, -586.743, -383.0], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], + "range": [0.0, 21397.83203125], "pixelHash": "cdd3a5fe2695d8baabc9726dd74cef785fb73660ad5cea5550d8613d79776486", - "firstPlanePosition": [ - -407.316, - -586.743, - -383.0 - ], - "lastPlanePosition": [ - -407.316, - -586.743, - -359.0 - ] + "firstPlanePosition": [-407.316, -586.743, -383.0], + "lastPlanePosition": [-407.316, -586.743, -359.0] }, "provenance": { "collection": "lung_pet_ct_dx", @@ -884,90 +752,24 @@ "1.3.6.1.4.1.14519.5.2.1.9823821695062948400149786107754402093" ], "expected": { - "dimensions": [ - 128, - 128, - 20 - ], - "spacing": [ - 1.71875, - 1.71875, - 3.0 - ], - "origin": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "direction": [ - 0.9999984769621674, - -0.0017453003596999955, - 0.0, - 0.0017453003596599956, - 0.9999984769621676, - 0.0, - -0.0, - 0.0, - 1.0 - ], - "range": [ - 0.0, - 1634.0 - ], + "dimensions": [128, 128, 20], + "spacing": [1.71875, 1.71875, 3.0], + "origin": [-105.23245681323, -147.49348022462, -33.429649353027], + "direction": [0.9999984769621674, -0.0017453003596999955, 0.0, 0.0017453003596599956, 0.9999984769621676, 0.0, -0.0, 0.0, 1.0], + "range": [0.0, 1634.0], "pixelHash": "551354c80e038874f8f5f95eaf3840911836ebd3893b40974650064c3b9e0cdd", - "firstPlanePosition": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "lastPlanePosition": [ - -105.23245681323, - -147.49348022462, - 23.570348739624 - ] + "firstPlanePosition": [-105.23245681323, -147.49348022462, -33.429649353027], + "lastPlanePosition": [-105.23245681323, -147.49348022462, 23.570348739624] }, "initial": { - "dimensions": [ - 128, - 128, - 10 - ], - "spacing": [ - 1.71875, - 1.71875, - 6.0 - ], - "origin": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "direction": [ - 0.9999984769621674, - -0.0017453003596999955, - 0.0, - 0.0017453003596599956, - 0.9999984769621676, - 0.0, - -0.0, - 0.0, - 1.0 - ], - "range": [ - 0.0, - 1634.0 - ], + "dimensions": [128, 128, 10], + "spacing": [1.71875, 1.71875, 6.0], + "origin": [-105.23245681323, -147.49348022462, -33.429649353027], + "direction": [0.9999984769621674, -0.0017453003596999955, 0.0, 0.0017453003596599956, 0.9999984769621676, 0.0, -0.0, 0.0, 1.0], + "range": [0.0, 1634.0], "pixelHash": "5101bcfd36da0f11b3f07c6d77a6dedb6473130339566112edbab228393ad489", - "firstPlanePosition": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "lastPlanePosition": [ - -105.23245681323, - -147.49348022462, - 20.570348739624 - ] + "firstPlanePosition": [-105.23245681323, -147.49348022462, -33.429649353027], + "lastPlanePosition": [-105.23245681323, -147.49348022462, 20.570348739624] }, "provenance": { "collection": "upenn_gbm", @@ -1027,90 +829,24 @@ "1.3.6.1.4.1.14519.5.2.1.306307086227517891627472362958678830947" ], "expected": { - "dimensions": [ - 128, - 128, - 20 - ], - "spacing": [ - 1.71875, - 1.71875, - 3.0 - ], - "origin": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "direction": [ - 0.9999984769621674, - -0.0017453003596999955, - 0.0, - 0.0017453003596599956, - 0.9999984769621676, - 0.0, - -0.0, - 0.0, - 1.0 - ], - "range": [ - 0.0, - 1789.0 - ], + "dimensions": [128, 128, 20], + "spacing": [1.71875, 1.71875, 3.0], + "origin": [-105.23245681323, -147.49348022462, -33.429649353027], + "direction": [0.9999984769621674, -0.0017453003596999955, 0.0, 0.0017453003596599956, 0.9999984769621676, 0.0, -0.0, 0.0, 1.0], + "range": [0.0, 1789.0], "pixelHash": "3ce6cc25b707b832b0a86832964c58cffea295e99b0fdf56f02b243b7d3de1ad", - "firstPlanePosition": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "lastPlanePosition": [ - -105.23245681323, - -147.49348022462, - 23.570348739624 - ] + "firstPlanePosition": [-105.23245681323, -147.49348022462, -33.429649353027], + "lastPlanePosition": [-105.23245681323, -147.49348022462, 23.570348739624] }, "initial": { - "dimensions": [ - 128, - 128, - 10 - ], - "spacing": [ - 1.71875, - 1.71875, - 6.0 - ], - "origin": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "direction": [ - 0.9999984769621674, - -0.0017453003596999955, - 0.0, - 0.0017453003596599956, - 0.9999984769621676, - 0.0, - -0.0, - 0.0, - 1.0 - ], - "range": [ - 0.0, - 1789.0 - ], + "dimensions": [128, 128, 10], + "spacing": [1.71875, 1.71875, 6.0], + "origin": [-105.23245681323, -147.49348022462, -33.429649353027], + "direction": [0.9999984769621674, -0.0017453003596999955, 0.0, 0.0017453003596599956, 0.9999984769621676, 0.0, -0.0, 0.0, 1.0], + "range": [0.0, 1789.0], "pixelHash": "ed41b3a8545d61f6598b40efb5d7d090eb12a75f24e561e9eff63c2b914e300b", - "firstPlanePosition": [ - -105.23245681323, - -147.49348022462, - -33.429649353027 - ], - "lastPlanePosition": [ - -105.23245681323, - -147.49348022462, - 20.570348739624 - ] + "firstPlanePosition": [-105.23245681323, -147.49348022462, -33.429649353027], + "lastPlanePosition": [-105.23245681323, -147.49348022462, 20.570348739624] }, "provenance": { "collection": "upenn_gbm", diff --git a/tests/dicomPages.ts b/tests/dicomPages.ts index 646f71297..890c066cd 100644 --- a/tests/dicomPages.ts +++ b/tests/dicomPages.ts @@ -1,3 +1,5 @@ +import { DOWNLOAD_TIMEOUT } from '../wdio.shared.conf'; + export async function openDicomPage(url: string, expectedError?: string) { await browser.url(url); await waitForDicomPage(expectedError); @@ -11,7 +13,8 @@ export async function waitForDicomPage( async () => (await $('#error').isExisting()) || ((await $('#status').isExisting()) && - (await $('#status').getText()) === status) + (await $('#status').getText()) === status), + { timeout: DOWNLOAD_TIMEOUT } ); if (expectedError) { await expect($('#error')).toHaveText(expectedError); diff --git a/tests/dicomVolumeCorpus.json b/tests/dicomVolumeCorpus.json index 6d1d87435..8d74f75e3 100644 --- a/tests/dicomVolumeCorpus.json +++ b/tests/dicomVolumeCorpus.json @@ -1,853 +1,436 @@ -[ - { - "id": "pydicom-CT_small", - "name": "dicom-corpus-CT_small.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/CT_small.dcm", - "sha256": "3dd31e5cc835b3f2cdd46c9da1982f59251e78518fefa8163d914631c66437d6", - "bytes": 39206, - "modality": "CT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "expected": { - "dimensions": [ - 128, - 128, - 1 - ], - "range": [ - -896.0, - 1167.0 - ], - "pixelHash": "ca969f2f193f5325ebbb4e75ed69a9968253f41a43f2498eefb612bb237ffb48", - "origin": [ - -158.135803, - -179.035797, - -75.699997 - ], - "spacing": [ - 0.661468, - 0.661468, - 5 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] +{ + "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", + "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major", + "datasets": [ + { + "id": "pydicom-CT_small", + "name": "dicom-corpus-CT_small.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/CT_small.dcm", + "sha256": "3dd31e5cc835b3f2cdd46c9da1982f59251e78518fefa8163d914631c66437d6", + "bytes": 39206, + "modality": "CT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "expected": { + "dimensions": [128, 128, 1], + "range": [-896.0, 1167.0], + "pixelHash": "ca969f2f193f5325ebbb4e75ed69a9968253f41a43f2498eefb612bb237ffb48", + "origin": [-158.135803, -179.035797, -75.699997], + "spacing": [0.661468, 0.661468, 5], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-MR_small", - "name": "dicom-corpus-MR_small.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small.dcm", - "sha256": "3f27d1c22f1a66e80d7bb7c911e8610fd0bb70325a76746a7adb1c0ddefcf2bb", - "bytes": 9830, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "expected": { - "dimensions": [ - 64, - 64, - 1 - ], - "range": [ - 127.0, - 2145.0 - ], - "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", - "origin": [ - -83.9063, - -91.2, - 6.6406 - ], - "spacing": [ - 0.3125, - 0.3125 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-MR_small", + "name": "dicom-corpus-MR_small.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small.dcm", + "sha256": "3f27d1c22f1a66e80d7bb7c911e8610fd0bb70325a76746a7adb1c0ddefcf2bb", + "bytes": 9830, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "expected": { + "dimensions": [64, 64, 1], + "range": [127.0, 2145.0], + "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", + "origin": [-83.9063, -91.2, 6.6406], + "spacing": [0.3125, 0.3125], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-MR_small_implicit", - "name": "dicom-corpus-MR_small_implicit.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_implicit.dcm", - "sha256": "6077442c42a56fc7fcc7db8411a657dded9fc109e6d3275765c4de358292b299", - "bytes": 9702, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", - "transferSyntaxUID": "1.2.840.10008.1.2", - "expected": { - "dimensions": [ - 64, - 64, - 1 - ], - "range": [ - 127.0, - 2145.0 - ], - "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", - "origin": [ - -83.9063, - -91.2, - 6.6406 - ], - "spacing": [ - 0.3125, - 0.3125 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-MR_small_implicit", + "name": "dicom-corpus-MR_small_implicit.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_implicit.dcm", + "sha256": "6077442c42a56fc7fcc7db8411a657dded9fc109e6d3275765c4de358292b299", + "bytes": 9702, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", + "transferSyntaxUID": "1.2.840.10008.1.2", + "expected": { + "dimensions": [64, 64, 1], + "range": [127.0, 2145.0], + "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", + "origin": [-83.9063, -91.2, 6.6406], + "spacing": [0.3125, 0.3125], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-MR_small_bigendian", - "name": "dicom-corpus-MR_small_bigendian.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_bigendian.dcm", - "sha256": "3e4c8c9fe70de4f3be149bbd673fa56f211c8e8e2ff9bac63f70f9dc31b5d108", - "bytes": 9708, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", - "transferSyntaxUID": "1.2.840.10008.1.2.2", - "expected": { - "dimensions": [ - 64, - 64, - 1 - ], - "range": [ - 127.0, - 2145.0 - ], - "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", - "origin": [ - -83.9063, - -91.2, - 6.6406 - ], - "spacing": [ - 0.3125, - 0.3125 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-MR_small_bigendian", + "name": "dicom-corpus-MR_small_bigendian.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_bigendian.dcm", + "sha256": "3e4c8c9fe70de4f3be149bbd673fa56f211c8e8e2ff9bac63f70f9dc31b5d108", + "bytes": 9708, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", + "transferSyntaxUID": "1.2.840.10008.1.2.2", + "expected": { + "dimensions": [64, 64, 1], + "range": [127.0, 2145.0], + "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", + "origin": [-83.9063, -91.2, 6.6406], + "spacing": [0.3125, 0.3125], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-MR_small_RLE", - "name": "dicom-corpus-MR_small_RLE.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_RLE.dcm", - "sha256": "2e5cb60878dc0acc494298ccdad28fce2cf14c51096e5d8cedab40248ea02e6c", - "bytes": 7790, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", - "transferSyntaxUID": "1.2.840.10008.1.2.5", - "expected": { - "dimensions": [ - 64, - 64, - 1 - ], - "range": [ - 127.0, - 2145.0 - ], - "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", - "origin": [ - -83.9063, - -91.2, - 6.6406 - ], - "spacing": [ - 0.3125, - 0.3125 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-MR_small_RLE", + "name": "dicom-corpus-MR_small_RLE.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_RLE.dcm", + "sha256": "2e5cb60878dc0acc494298ccdad28fce2cf14c51096e5d8cedab40248ea02e6c", + "bytes": 7790, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", + "transferSyntaxUID": "1.2.840.10008.1.2.5", + "expected": { + "dimensions": [64, 64, 1], + "range": [127.0, 2145.0], + "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", + "origin": [-83.9063, -91.2, 6.6406], + "spacing": [0.3125, 0.3125], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-MR_small_jp2klossless", - "name": "dicom-corpus-MR_small_jp2klossless.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_jp2klossless.dcm", - "sha256": "4c0049e0355b560c8c846538d827afbdae5311b20fc5e5a93a3892e109bb140d", - "bytes": 6008, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", - "transferSyntaxUID": "1.2.840.10008.1.2.4.90", - "expected": { - "dimensions": [ - 64, - 64, - 1 - ], - "range": [ - 127.0, - 2145.0 - ], - "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", - "origin": [ - -83.9063, - -91.2, - 6.6406 - ], - "spacing": [ - 0.3125, - 0.3125 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-MR_small_jp2klossless", + "name": "dicom-corpus-MR_small_jp2klossless.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_jp2klossless.dcm", + "sha256": "4c0049e0355b560c8c846538d827afbdae5311b20fc5e5a93a3892e109bb140d", + "bytes": 6008, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", + "transferSyntaxUID": "1.2.840.10008.1.2.4.90", + "expected": { + "dimensions": [64, 64, 1], + "range": [127.0, 2145.0], + "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", + "origin": [-83.9063, -91.2, 6.6406], + "spacing": [0.3125, 0.3125], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-MR_small_jpeg_ls_lossless", - "name": "dicom-corpus-MR_small_jpeg_ls_lossless.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm", - "sha256": "b2b69dd2ae854bf7dfada6745709cd5d8a4573ea12387adbbdc56e8be6056206", - "bytes": 6124, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", - "transferSyntaxUID": "1.2.840.10008.1.2.4.80", - "expected": { - "dimensions": [ - 64, - 64, - 1 - ], - "range": [ - 127.0, - 2145.0 - ], - "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", - "origin": [ - -83.9063, - -91.2, - 6.6406 - ], - "spacing": [ - 0.3125, - 0.3125 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-MR_small_jpeg_ls_lossless", + "name": "dicom-corpus-MR_small_jpeg_ls_lossless.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/MR_small_jpeg_ls_lossless.dcm", + "sha256": "b2b69dd2ae854bf7dfada6745709cd5d8a4573ea12387adbbdc56e8be6056206", + "bytes": 6124, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4", + "transferSyntaxUID": "1.2.840.10008.1.2.4.80", + "expected": { + "dimensions": [64, 64, 1], + "range": [127.0, 2145.0], + "pixelHash": "e37cddda6b3ad9195a203bf7534360c3688e5516529de975406ba2482bb622c0", + "origin": [-83.9063, -91.2, 6.6406], + "spacing": [0.3125, 0.3125], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-693_J2KR", - "name": "dicom-corpus-693_J2KR.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/693_J2KR.dcm", - "sha256": "c392d8bd1f952ed2d9387d5143d34c5a29ac9d74566688169731a50ac6a82aa2", - "bytes": 107060, - "modality": "CT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", - "transferSyntaxUID": "1.2.840.10008.1.2.4.90", - "expected": { - "dimensions": [ - 512, - 512, - 1 - ], - "range": [ - -3024.0, - 1468.0 - ], - "pixelHash": "4d67876ea09570a5be1de299c66fc45935661a176cb5ec97be05e86b722564e9", - "origin": [ - -122.5, - -112.4, - 47.0 - ], - "spacing": [ - 0.478516, - 0.478516 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-693_J2KR", + "name": "dicom-corpus-693_J2KR.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/693_J2KR.dcm", + "sha256": "c392d8bd1f952ed2d9387d5143d34c5a29ac9d74566688169731a50ac6a82aa2", + "bytes": 107060, + "modality": "CT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", + "transferSyntaxUID": "1.2.840.10008.1.2.4.90", + "expected": { + "dimensions": [512, 512, 1], + "range": [-3024.0, 1468.0], + "pixelHash": "4d67876ea09570a5be1de299c66fc45935661a176cb5ec97be05e86b722564e9", + "origin": [-122.5, -112.4, 47.0], + "spacing": [0.478516, 0.478516], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-693_UNCI", - "name": "dicom-corpus-693_UNCI.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/693_UNCI.dcm", - "sha256": "42d6c33d6666bf569a53951211be6fca2ab04956db43c3f75a9720d976ab128c", - "bytes": 526324, - "modality": "CT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "expected": { - "dimensions": [ - 512, - 512, - 1 - ], - "range": [ - -3995.0, - 1812.0 - ], - "pixelHash": "86c60cefb8036e6090840b06ab0960e5a3ef9938c1639ec87c8a89f607f497bb", - "origin": [ - -122.5, - -112.4, - 47.0 - ], - "spacing": [ - 0.478516, - 0.478516 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-693_UNCI", + "name": "dicom-corpus-693_UNCI.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/693_UNCI.dcm", + "sha256": "42d6c33d6666bf569a53951211be6fca2ab04956db43c3f75a9720d976ab128c", + "bytes": 526324, + "modality": "CT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "expected": { + "dimensions": [512, 512, 1], + "range": [-3995.0, 1812.0], + "pixelHash": "86c60cefb8036e6090840b06ab0960e5a3ef9938c1639ec87c8a89f607f497bb", + "origin": [-122.5, -112.4, 47.0], + "spacing": [0.478516, 0.478516], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-693_UNCR", - "name": "dicom-corpus-693_UNCR.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/693_UNCR.dcm", - "sha256": "cc4cdd599231922ecf63de2ddacf03d51c4588805c9154c2eef1ff49c23b32be", - "bytes": 525986, - "modality": "CT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "expected": { - "dimensions": [ - 512, - 512, - 1 - ], - "range": [ - -3024.0, - 1468.0 - ], - "pixelHash": "4d67876ea09570a5be1de299c66fc45935661a176cb5ec97be05e86b722564e9", - "origin": [ - -122.5, - -112.4, - 47.0 - ], - "spacing": [ - 0.478516, - 0.478516 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-693_UNCR", + "name": "dicom-corpus-693_UNCR.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/693_UNCR.dcm", + "sha256": "cc4cdd599231922ecf63de2ddacf03d51c4588805c9154c2eef1ff49c23b32be", + "bytes": 525986, + "modality": "CT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "expected": { + "dimensions": [512, 512, 1], + "range": [-3024.0, 1468.0], + "pixelHash": "4d67876ea09570a5be1de299c66fc45935661a176cb5ec97be05e86b722564e9", + "origin": [-122.5, -112.4, 47.0], + "spacing": [0.478516, 0.478516], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-eCT_Supplemental", - "name": "dicom-corpus-eCT_Supplemental.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/eCT_Supplemental.dcm", - "sha256": "0a4c3aa02d1b0b4826daa5ffe85ef13be83c1433842a9a98b901e075136dd86f", - "bytes": 1052902, - "modality": "CT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.2.1", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "expected": { - "dimensions": [ - 512, - 512, - 2 - ], - "range": [ - -1024.0, - 172.0 - ], - "pixelHash": "da30f5ab3d1573dc246f3968679f0fbdffde1f9158c6dabebf6d467d76d4b31e", - "origin": [ - 99.5, - -301.5, - -159.0 - ], - "spacing": [ - 0.388672, - 0.388672, - 10.0 - ], - "direction": [ - -1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-eCT_Supplemental", + "name": "dicom-corpus-eCT_Supplemental.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/eCT_Supplemental.dcm", + "sha256": "0a4c3aa02d1b0b4826daa5ffe85ef13be83c1433842a9a98b901e075136dd86f", + "bytes": 1052902, + "modality": "CT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.2.1", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "expected": { + "dimensions": [512, 512, 2], + "range": [-1024.0, 172.0], + "pixelHash": "da30f5ab3d1573dc246f3968679f0fbdffde1f9158c6dabebf6d467d76d4b31e", + "origin": [99.5, -301.5, -159.0], + "spacing": [0.388672, 0.388672, 10.0], + "direction": [-1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-emri_small", - "name": "dicom-corpus-emri_small.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small.dcm", - "sha256": "151233ec63f64ebb63b979df51aa827cd612a53422c073f6ef341770c7bc9a56", - "bytes": 84256, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "expected": { - "dimensions": [ - 64, - 64, - 10 - ], - "range": [ - 0.0, - 467.0 - ], - "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + { + "id": "pydicom-emri_small", + "name": "dicom-corpus-emri_small.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small.dcm", + "sha256": "151233ec63f64ebb63b979df51aa827cd612a53422c073f6ef341770c7bc9a56", + "bytes": 84256, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "expected": { + "dimensions": [64, 64, 10], + "range": [0.0, 467.0], + "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-emri_small_big_endian", - "name": "dicom-corpus-emri_small_big_endian.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_big_endian.dcm", - "sha256": "8e18ed3542bc4df70dc6acda87eab5095b19e2b4c1b7fb72ba457e7c217b1ab7", - "bytes": 84256, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", - "transferSyntaxUID": "1.2.840.10008.1.2.2", - "expected": { - "dimensions": [ - 64, - 64, - 10 - ], - "range": [ - 0.0, - 467.0 - ], - "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + { + "id": "pydicom-emri_small_big_endian", + "name": "dicom-corpus-emri_small_big_endian.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_big_endian.dcm", + "sha256": "8e18ed3542bc4df70dc6acda87eab5095b19e2b4c1b7fb72ba457e7c217b1ab7", + "bytes": 84256, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", + "transferSyntaxUID": "1.2.840.10008.1.2.2", + "expected": { + "dimensions": [64, 64, 10], + "range": [0.0, 467.0], + "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-emri_small_RLE", - "name": "dicom-corpus-emri_small_RLE.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_RLE.dcm", - "sha256": "93c19bca3fb6b7202dcd067de8d16cb6b3f7c6e9a0632e474aab81175ee45266", - "bytes": 49022, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", - "transferSyntaxUID": "1.2.840.10008.1.2.5", - "expected": { - "dimensions": [ - 64, - 64, - 10 - ], - "range": [ - 0.0, - 467.0 - ], - "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + { + "id": "pydicom-emri_small_RLE", + "name": "dicom-corpus-emri_small_RLE.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_RLE.dcm", + "sha256": "93c19bca3fb6b7202dcd067de8d16cb6b3f7c6e9a0632e474aab81175ee45266", + "bytes": 49022, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", + "transferSyntaxUID": "1.2.840.10008.1.2.5", + "expected": { + "dimensions": [64, 64, 10], + "range": [0.0, 467.0], + "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-emri_small_jpeg_2k_lossless", - "name": "dicom-corpus-emri_small_jpeg_2k_lossless.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_jpeg_2k_lossless.dcm", - "sha256": "b2b4063359a08ed3b0afa9f4e4f72f84af79e5116515b446d9a30da9dc7f1888", - "bytes": 40324, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", - "transferSyntaxUID": "1.2.840.10008.1.2.4.90", - "expected": { - "dimensions": [ - 64, - 64, - 10 - ], - "range": [ - 0.0, - 467.0 - ], - "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" - }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-emri_small_jpeg_ls_lossless", - "name": "dicom-corpus-emri_small_jpeg_ls_lossless.dcm", - "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_jpeg_ls_lossless.dcm", - "sha256": "24de03c9c0f8b5aa75d7fbcc894f94e612b66702175b4936589a0849ec9f87b4", - "bytes": 42834, - "modality": "MR", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", - "transferSyntaxUID": "1.2.840.10008.1.2.4.80", - "expected": { - "dimensions": [ - 64, - 64, - 10 - ], - "range": [ - 0.0, - 467.0 - ], - "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + { + "id": "pydicom-emri_small_jpeg_2k_lossless", + "name": "dicom-corpus-emri_small_jpeg_2k_lossless.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_jpeg_2k_lossless.dcm", + "sha256": "b2b4063359a08ed3b0afa9f4e4f72f84af79e5116515b446d9a30da9dc7f1888", + "bytes": 40324, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", + "transferSyntaxUID": "1.2.840.10008.1.2.4.90", + "expected": { + "dimensions": [64, 64, 10], + "range": [0.0, 467.0], + "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "pydicom-image_dfl", - "name": "dicom-corpus-image_dfl.dcm", - "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/image_dfl.dcm", - "sha256": "0029ebbba17e7c6f081408d433cd28b5d1cfee0eeb4cff509b4d972ffa9daf27", - "bytes": 4637, - "modality": "OT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.7", - "transferSyntaxUID": "1.2.840.10008.1.2.1.99", - "expected": { - "dimensions": [ - 512, - 512, - 1 - ], - "range": [ - 0.0, - 255.0 - ], - "pixelHash": "4b3989b8545f28dfaa64c94789b06710a8574af593a8a4caf87fb2bf2a13ab2d" + { + "id": "pydicom-emri_small_jpeg_ls_lossless", + "name": "dicom-corpus-emri_small_jpeg_ls_lossless.dcm", + "url": "https://github.com/pydicom/pydicom-data/raw/39a2eb31815eec435dc26c322c27aec5cfcbddb6/data/emri_small_jpeg_ls_lossless.dcm", + "sha256": "24de03c9c0f8b5aa75d7fbcc894f94e612b66702175b4936589a0849ec9f87b4", + "bytes": 42834, + "modality": "MR", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.4.1", + "transferSyntaxUID": "1.2.840.10008.1.2.4.80", + "expected": { + "dimensions": [64, 64, 10], + "range": [0.0, 467.0], + "pixelHash": "abe3500fe9a168a59c82e063060ca7ee6ec47ff13c5acf697507c9adb8660dea" + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom-data/blob/master/LICENSE" + } }, - "provenance": { - "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "idc-ct-jpeg-lossless-slice", - "name": "dicom-corpus-16c331c4-6242-44e7-88c5-54e991d140f4.dcm", - "url": "https://idc-open-data.s3.amazonaws.com/578233f9-537b-411b-b742-403fdab164a5/16c331c4-6242-44e7-88c5-54e991d140f4.dcm", - "sha256": "a491cb2a944277b44b97feeb9deea0853e39cf0562c0fcb557cf6573989be930", - "bytes": 233204, - "modality": "CT", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", - "transferSyntaxUID": "1.2.840.10008.1.2.4.70", - "expected": { - "dimensions": [ - 512, - 512, - 1 - ], - "range": [ - -1024.0, - 2602.0 - ], - "pixelHash": "522ca4beec01da2abc9c379b641a6166f017c4e0b173f600a7b21d647000ccdd", - "origin": [ - -189.62890625, - -336.12890625, - -121.578 - ], - "spacing": [ - 0.7421875, - 0.7421875 - ], - "direction": [ - 1.0, - 0.0, - 0.0, - 0.0, - 1.0, - 0.0, - 0.0, - 0.0, - 1.0 - ] + { + "id": "pydicom-image_dfl", + "name": "dicom-corpus-image_dfl.dcm", + "url": "https://raw.githubusercontent.com/pydicom/pydicom/v3.0.2/src/pydicom/data/test_files/image_dfl.dcm", + "sha256": "0029ebbba17e7c6f081408d433cd28b5d1cfee0eeb4cff509b4d972ffa9daf27", + "bytes": 4637, + "modality": "OT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.7", + "transferSyntaxUID": "1.2.840.10008.1.2.1.99", + "expected": { + "dimensions": [512, 512, 1], + "range": [0.0, 255.0], + "pixelHash": "4b3989b8545f28dfaa64c94789b06710a8574af593a8a4caf87fb2bf2a13ab2d" + }, + "provenance": { + "source": "https://github.com/pydicom/pydicom/blob/v3.0.2/LICENSE" + } }, - "provenance": { - "source": "https://doi.org/10.7937/k9/tcia.2016.gkj0zwac", - "reference": "pydicom 3.0.2; pylibjpeg-libjpeg 2.5.0; pylibjpeg-openjpeg 2.6.0", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" - } - }, - { - "id": "idc-nm-3e915859-015b-4c8f-9a67-f17db1bef1e1", - "name": "dicom-corpus-3e915859-015b-4c8f-9a67-f17db1bef1e1.dcm", - "url": "https://idc-open-data.s3.amazonaws.com/3e915859-015b-4c8f-9a67-f17db1bef1e1/e3577f45-0b62-46e0-9b4a-983fc811a403.dcm", - "sha256": "abc77c4e6239f4b0a605d4f4ad77e730e3c67d6057dea0265b591d7180b62de5", - "bytes": 1284048, - "modality": "NM", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.20", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "provenance": { - "source": "https://doi.org/10.7937/ghkn-md15", - "license": "CC BY 4.0", - "collection": "varepop_apollo", - "reference": "pydicom3.0.2, NumPy2.4.6", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" + { + "id": "idc-ct-jpeg-lossless-slice", + "name": "dicom-corpus-16c331c4-6242-44e7-88c5-54e991d140f4.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/578233f9-537b-411b-b742-403fdab164a5/16c331c4-6242-44e7-88c5-54e991d140f4.dcm", + "sha256": "a491cb2a944277b44b97feeb9deea0853e39cf0562c0fcb557cf6573989be930", + "bytes": 233204, + "modality": "CT", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.2", + "transferSyntaxUID": "1.2.840.10008.1.2.4.70", + "expected": { + "dimensions": [512, 512, 1], + "range": [-1024.0, 2602.0], + "pixelHash": "522ca4beec01da2abc9c379b641a6166f017c4e0b173f600a7b21d647000ccdd", + "origin": [-189.62890625, -336.12890625, -121.578], + "spacing": [0.7421875, 0.7421875], + "direction": [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + }, + "provenance": { + "source": "https://doi.org/10.7937/k9/tcia.2016.gkj0zwac" + } }, - "expected": { - "dimensions": [ - 128, - 128, - 39 - ], - "spacing": [ - 4.7951998710632, - 4.7951998710632, - 4.7951998710632 - ], - "origin": [ - -84.307189228102, - -560.03891452932, - 1820.9574316383 - ], - "direction": [ - 0.7969600011737011, - 0.6040291437013309, - -0.0018841678936000028, - -0.18433537197109837, - 0.24024041366395787, - -0.9530503734235916, - -0.5752175476891148, - 0.7598903455117845, - 0.30280593724116717 - ], - "range": [ - 0.0, - 8786.0 - ], - "pixelHash": "67c8ffa6707cc36c649cae4d7ae3fe0240f40855cca87f18f4a148873cbaf5f1" - } - }, - { - "id": "idc-nm-e518f6eb-c3ad-432c-933b-7676d3bdc752", - "name": "dicom-corpus-e518f6eb-c3ad-432c-933b-7676d3bdc752.dcm", - "url": "https://idc-open-data.s3.amazonaws.com/e518f6eb-c3ad-432c-933b-7676d3bdc752/64cbffec-caa9-4ee8-bc67-5586d24265c3.dcm", - "sha256": "2180e2ad8262907cf5c3baea36663b59d8f02250ab5768303ea81eae3aa000eb", - "bytes": 1445730, - "modality": "NM", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.20", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "provenance": { - "source": "https://doi.org/10.7937/tcia.bbag-2923", - "license": "CC BY 4.0", - "collection": "covid_19_ny_sbu", - "reference": "pydicom3.0.2, NumPy2.4.6", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" + { + "id": "idc-nm-3e915859-015b-4c8f-9a67-f17db1bef1e1", + "name": "dicom-corpus-3e915859-015b-4c8f-9a67-f17db1bef1e1.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/3e915859-015b-4c8f-9a67-f17db1bef1e1/e3577f45-0b62-46e0-9b4a-983fc811a403.dcm", + "sha256": "abc77c4e6239f4b0a605d4f4ad77e730e3c67d6057dea0265b591d7180b62de5", + "bytes": 1284048, + "modality": "NM", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.20", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "provenance": { + "source": "https://doi.org/10.7937/ghkn-md15", + "license": "CC BY 4.0", + "collection": "varepop_apollo", + "reference": "pydicom3.0.2, NumPy2.4.6" + }, + "expected": { + "dimensions": [128, 128, 39], + "spacing": [4.7951998710632, 4.7951998710632, 4.7951998710632], + "origin": [-84.307189228102, -560.03891452932, 1820.9574316383], + "direction": [0.7969600011737011, 0.6040291437013309, -0.0018841678936000028, -0.18433537197109837, 0.24024041366395787, -0.9530503734235916, -0.5752175476891148, 0.7598903455117845, 0.30280593724116717], + "range": [0.0, 8786.0], + "pixelHash": "67c8ffa6707cc36c649cae4d7ae3fe0240f40855cca87f18f4a148873cbaf5f1" + } }, - "expected": { - "dimensions": [ - 128, - 128, - 44 - ], - "spacing": [ - 4.7951998710632, - 4.7951998710632, - 4.7951998710632 - ], - "origin": [ - -303.6479406672, - -462.85804050024, - 1549.5870552885 - ], - "direction": [ - 0.9999849232635268, - 0.0003446298565199989, - -0.005480371876099983, - -0.00024031414620000066, - 0.9998190041416026, - 0.01902370117525005, - -0.005485936086894437, - 0.019022097349032426, - -0.9998040129533861 - ], - "range": [ - 0.0, - 27893.0 - ], - "pixelHash": "c959b2920236be466698716cc1ff46531bb3b59eebbaf777ccb80251cbf67c87" - } - }, - { - "id": "idc-nm-f2827355-24e5-4d43-aa43-20534de8f631", - "name": "dicom-corpus-f2827355-24e5-4d43-aa43-20534de8f631.dcm", - "url": "https://idc-open-data.s3.amazonaws.com/f2827355-24e5-4d43-aa43-20534de8f631/f336328e-f7be-42f6-a549-3c3601987bb3.dcm", - "sha256": "70ee4d0ba4b4abed6a13245a97173a994771dc7d8c80b3d793169d40196daf17", - "bytes": 8658576, - "modality": "NM", - "sopClassUID": "1.2.840.10008.5.1.4.1.1.20", - "transferSyntaxUID": "1.2.840.10008.1.2.1", - "provenance": { - "source": "https://doi.org/10.7937/ghkn-md15", - "license": "CC BY 4.0", - "collection": "varepop_apollo", - "reference": "pydicom3.0.2, NumPy2.4.6", - "pixelHashEncoding": "SHA256 of modality-rescaled samples in original DICOM frame order, Float64 little-endian, C row-major" + { + "id": "idc-nm-e518f6eb-c3ad-432c-933b-7676d3bdc752", + "name": "dicom-corpus-e518f6eb-c3ad-432c-933b-7676d3bdc752.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/e518f6eb-c3ad-432c-933b-7676d3bdc752/64cbffec-caa9-4ee8-bc67-5586d24265c3.dcm", + "sha256": "2180e2ad8262907cf5c3baea36663b59d8f02250ab5768303ea81eae3aa000eb", + "bytes": 1445730, + "modality": "NM", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.20", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "provenance": { + "source": "https://doi.org/10.7937/tcia.bbag-2923", + "license": "CC BY 4.0", + "collection": "covid_19_ny_sbu", + "reference": "pydicom3.0.2, NumPy2.4.6" + }, + "expected": { + "dimensions": [128, 128, 44], + "spacing": [4.7951998710632, 4.7951998710632, 4.7951998710632], + "origin": [-303.6479406672, -462.85804050024, 1549.5870552885], + "direction": [0.9999849232635268, 0.0003446298565199989, -0.005480371876099983, -0.00024031414620000066, 0.9998190041416026, 0.01902370117525005, -0.005485936086894437, 0.019022097349032426, -0.9998040129533861], + "range": [0.0, 27893.0], + "pixelHash": "c959b2920236be466698716cc1ff46531bb3b59eebbaf777ccb80251cbf67c87" + } }, - "expectedError": "Unsupported NM volume with multiple spatial/time dimensions", - "frameTopology": { - "slices": 33, - "timeSlots": 8, - "storedFrames": 264 + { + "id": "idc-nm-f2827355-24e5-4d43-aa43-20534de8f631", + "name": "dicom-corpus-f2827355-24e5-4d43-aa43-20534de8f631.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/f2827355-24e5-4d43-aa43-20534de8f631/f336328e-f7be-42f6-a549-3c3601987bb3.dcm", + "sha256": "70ee4d0ba4b4abed6a13245a97173a994771dc7d8c80b3d793169d40196daf17", + "bytes": 8658576, + "modality": "NM", + "sopClassUID": "1.2.840.10008.5.1.4.1.1.20", + "transferSyntaxUID": "1.2.840.10008.1.2.1", + "provenance": { + "source": "https://doi.org/10.7937/ghkn-md15", + "license": "CC BY 4.0", + "collection": "varepop_apollo", + "reference": "pydicom3.0.2, NumPy2.4.6" + }, + "expectedError": "Unsupported NM volume with multiple spatial/time dimensions", + "frameTopology": { + "slices": 33, + "timeSlots": 8, + "storedFrames": 264 + } } - } -] + ] +} diff --git a/tests/fixtures/dicom-pages/composition.ts b/tests/fixtures/dicom-pages/composition.ts index 3141c7b5b..ad4866627 100644 --- a/tests/fixtures/dicom-pages/composition.ts +++ b/tests/fixtures/dicom-pages/composition.ts @@ -59,10 +59,7 @@ async function register(instances: Instance[], status: string) { }); for (const update of updates) { const previous = loaded.get(update.id); - loaded.set( - update.id, - await loadCollection(update, { previous: previous?.volume }) - ); + loaded.set(update.id, await loadCollection(update, previous?.volume)); previous?.image.delete(); } await render(status); diff --git a/tests/fixtures/dicom-pages/corpus.ts b/tests/fixtures/dicom-pages/corpus.ts index 896f419cb..2117dc2b3 100644 --- a/tests/fixtures/dicom-pages/corpus.ts +++ b/tests/fixtures/dicom-pages/corpus.ts @@ -1,40 +1,25 @@ -import { - singleDecoderTable, - wholeInstanceDecoder, -} from '@/packages/dicom/core'; -import { createRuntime, failed, never, report, sourceOf } from './shared'; +import { failed, never, report, runtime, sourceOf } from './shared'; import { loadInstanceVolume } from './loadVolume'; import { describeVolume } from './describeVolume'; -const customDecoder = wholeInstanceDecoder('Custom', () => ({ - size: [4, 4, 2], - components: 1, - data: new Uint16Array([...Array(16).fill(2), ...Array(16).fill(4)]), -})); - async function run() { const params = new URL(location.href).searchParams; + const source = params.get('source'); const url = new URL( - `./corpus-data/${encodeURIComponent(params.get('name')!)}`, + `./${source === 'unranged' ? 'unranged-data' : 'corpus-data'}/${encodeURIComponent(params.get('name')!)}`, document.baseURI ); const input = - params.get('source') === 'file' + source === 'file' ? new File([await (await fetch(url)).blob()], 'volume.dcm') : url; - const runtime = createRuntime( - params.get('decoder') === 'custom' - ? { decoders: () => singleDecoderTable(customDecoder) } - : {} - ); const instance = await runtime.readInstance(sourceOf(input), never); - const { volume, image } = await loadInstanceVolume(instance, { - runtime, - irregularGeometry: - params.get('policy') === 'reject' ? 'reject' : 'preserve-order', - }); + const { volume, image } = await loadInstanceVolume(instance); await describeVolume(image, report); - report('reconstruction', volume.reconstruction.kind); + report( + 'reconstruction', + volume.spatialMetadata.reconstruction?.kind ?? 'unreported' + ); report('status', 'complete'); } diff --git a/tests/fixtures/dicom-pages/enhancedFixtures.ts b/tests/fixtures/dicom-pages/enhancedFixtures.ts index 3b7631f1a..81a2bcd8f 100644 --- a/tests/fixtures/dicom-pages/enhancedFixtures.ts +++ b/tests/fixtures/dicom-pages/enhancedFixtures.ts @@ -1,21 +1,10 @@ import { buildSyntheticDicom, + combine, rawElement, sequenceItem, } from '../../specs/syntheticDicom'; -const concatenate = (parts: Uint8Array[]) => { - const bytes = new Uint8Array( - parts.reduce((length, part) => length + part.length, 0) - ); - let offset = 0; - for (const part of parts) { - bytes.set(part, offset); - offset += part.length; - } - return bytes; -}; - const text = (group: number, element: number, value: readonly number[]) => { const string = value.join('\\'); return rawElement( @@ -27,17 +16,14 @@ const text = (group: number, element: number, value: readonly number[]) => { }; const sequence = (group: number, element: number, items: Uint8Array[]) => - rawElement(group, element, 'SQ', concatenate(items.map(sequenceItem))); + rawElement(group, element, 'SQ', combine(...items.map(sequenceItem))); const position = (value: readonly number[]) => sequence(0x0020, 0x9113, [text(0x0020, 0x0032, value)]); const transformation = ([slope, intercept]: readonly [number, number]) => sequence(0x0028, 0x9145, [ - concatenate([ - text(0x0028, 0x1052, [intercept]), - text(0x0028, 0x1053, [slope]), - ]), + combine(text(0x0028, 0x1052, [intercept]), text(0x0028, 0x1053, [slope])), ]); const temporalPosition = (value: number) => { @@ -46,7 +32,7 @@ const temporalPosition = (value: number) => { return sequence(0x0020, 0x9111, [rawElement(0x0020, 0x9128, 'UL', bytes)]); }; -export type EnhancedFixtureOptions = { +type EnhancedFixtureOptions = { pixelValues: number[]; positions?: number[][]; sharedPosition?: number[]; @@ -69,15 +55,15 @@ export function enhancedFixtureBytes(options: EnhancedFixtureOptions) { ]; if (sharedPosition) shared.unshift(position(sharedPosition)); const frames = pixelValues.map((_, index) => - concatenate([ + combine( ...(temporalPositions ? [temporalPosition(temporalPositions[index])] : []), ...(sharedPosition ? [] : [position(positions?.[index] ?? [10, 20, 30 + index])]), - ...(transforms ? [transformation(transforms[index])] : []), - ]) + ...(transforms ? [transformation(transforms[index])] : []) + ) ); return buildSyntheticDicom({ studyUid: '1.2.826.0.1.3680043.10.999.50', @@ -93,7 +79,7 @@ export function enhancedFixtureBytes(options: EnhancedFixtureOptions) { rootGeometry: false, framePixelValues: pixelValues, extraElements: [ - sequence(0x5200, 0x9229, [concatenate(shared)]), + sequence(0x5200, 0x9229, [combine(...shared)]), sequence(0x5200, 0x9230, frames), ], }); diff --git a/tests/fixtures/dicom-pages/loadVolume.ts b/tests/fixtures/dicom-pages/loadVolume.ts index c083e7025..2d7501adb 100644 --- a/tests/fixtures/dicom-pages/loadVolume.ts +++ b/tests/fixtures/dicom-pages/loadVolume.ts @@ -3,28 +3,21 @@ import { emptyRegistry, loadVolume, registerInstances, - type AllocateVolumeOptions, - type DicomRuntime, type Instance, type InstanceCollectionUpdate, type Volume, } from '@/packages/dicom/core'; import { applyVolumeUpdate, toVtkImageData } from '@/packages/dicom/vtk'; -import { never, runtime as defaultRuntime } from './shared'; - -type LoadOptions = AllocateVolumeOptions & { - previous?: Volume; - runtime?: DicomRuntime; -}; +import { never, runtime } from './shared'; /** Allocates a planned collection and decodes it the way a viewer would. */ export async function loadCollection( update: InstanceCollectionUpdate, - { previous, runtime = defaultRuntime, ...options }: LoadOptions = {} + previous?: Volume ) { if (update.kind !== 'image') throw new Error(`Expected a volume, got ${update.kind}`); - const volume = allocateVolume(update, options, previous); + const volume = allocateVolume(update, previous); const image = toVtkImageData(volume); for await (const loaded of loadVolume(volume, { runtime, signal: never })) { if ('error' in loaded) throw loaded.error; @@ -33,7 +26,7 @@ export async function loadCollection( return { volume, image }; } -export function loadInstanceVolume(instance: Instance, options?: LoadOptions) { +export function loadInstanceVolume(instance: Instance) { const [update] = registerInstances(emptyRegistry, [instance]).updates; - return loadCollection(update, options); + return loadCollection(update); } diff --git a/tests/fixtures/dicom-pages/parity.ts b/tests/fixtures/dicom-pages/parity.ts index 633a8e6a9..16b93ab6f 100644 --- a/tests/fixtures/dicom-pages/parity.ts +++ b/tests/fixtures/dicom-pages/parity.ts @@ -65,14 +65,12 @@ async function decodeFrames( return samples; } -async function compare(name: string, source: string) { +async function compare(name: string) { const url = new URL( `./corpus-data/${encodeURIComponent(name)}`, document.baseURI ); - const input = - source === 'file' ? new File([await (await fetch(url)).blob()], name) : url; - const instance = await runtime.readInstance(sourceOf(input), never); + const instance = await runtime.readInstance(sourceOf(url), never); const planned = planDecode(runtime.decoders, instance, Float64Array); if ('error' in planned) return { name, plan: 'unsupported', reason: planned.error.message }; @@ -101,7 +99,6 @@ async function compare(name: string, source: string) { async function run() { const params = new URL(location.href).searchParams; - const source = params.get('source') ?? 'http'; const listed: string[] = await ( await fetch(new URL('./corpus-data/parity-cases.json', document.baseURI)) ).json(); @@ -112,7 +109,7 @@ async function run() { const results = []; for (const name of names) results.push( - await compare(name, source).catch((error: Error) => ({ + await compare(name).catch((error: Error) => ({ name, error: error.message, })) diff --git a/tests/fixtures/dicom-pages/server.mjs b/tests/fixtures/dicom-pages/server.mjs index 73c0f63ca..e582f18f4 100644 --- a/tests/fixtures/dicom-pages/server.mjs +++ b/tests/fixtures/dicom-pages/server.mjs @@ -59,6 +59,7 @@ async function buildPage(kind, outDir) { build: { outDir, emptyOutDir: true, + chunkSizeWarningLimit: Infinity, rollupOptions: { input: resolve(fixture, `${kind}.html`) }, }, worker: { format: 'es' }, @@ -66,14 +67,14 @@ async function buildPage(kind, outDir) { await copyItkAssets(resolve(outDir, 'assets')); } -function serveDicom(bytes, request, response) { - const match = /^bytes=(\d+)-(\d*)/.exec(request.headers.range ?? ''); +/** Serves the byte range asked for, or the whole body when `range` is absent. */ +function serveDicom(bytes, range, response) { + const match = /^bytes=(\d+)-(\d*)/.exec(range ?? ''); const start = match ? Number(match[1]) : 0; const end = match?.[2] ? Math.min(bytes.length, Number(match[2]) + 1) : bytes.length; response.setHeader('Content-Type', 'application/dicom'); - response.setHeader('Accept-Ranges', 'bytes'); response.setHeader('Content-Length', end - start); if (match) { response.statusCode = 206; @@ -85,10 +86,24 @@ function serveDicom(bytes, request, response) { response.end(bytes.subarray(start, end)); } -export async function startDicomPages( - bytes, - { kinds = ['core', 'vtk'], fixtures = {} } = {} -) { +export async function startDicomPages({ + kinds = ['core', 'vtk'], + fixtures = {}, +} = {}) { + const serveFixture = (ranged) => (request, response) => { + const name = decodeURIComponent(request.url?.slice(1) ?? ''); + if (!Object.hasOwn(fixtures, name)) { + response.statusCode = 404; + response.end(); + return; + } + if (ranged) response.setHeader('Accept-Ranges', 'bytes'); + serveDicom( + fixtures[name], + ranged ? request.headers.range : undefined, + response + ); + }; await mkdir(resolve(root, '.tmp'), { recursive: true }); const directory = await mkdtemp(resolve(root, '.tmp/dicom-browser-')); const servers = []; @@ -124,18 +139,9 @@ export async function startDicomPages( } } ); - instance.middlewares.use('/fixture.dcm', (request, response) => { - serveDicom(bytes, request, response); - }); - instance.middlewares.use('/corpus-data', (request, response) => { - const name = decodeURIComponent(request.url?.slice(1) ?? ''); - if (!Object.hasOwn(fixtures, name)) { - response.statusCode = 404; - response.end(); - return; - } - serveDicom(fixtures[name], request, response); - }); + instance.middlewares.use('/corpus-data', serveFixture(true)); + // A server that ignores Range answers every read with the file. + instance.middlewares.use('/unranged-data', serveFixture(false)); }, }, ], diff --git a/tests/fixtures/dicom-pages/shared.ts b/tests/fixtures/dicom-pages/shared.ts index 7e60f09a6..0cda88a9a 100644 --- a/tests/fixtures/dicom-pages/shared.ts +++ b/tests/fixtures/dicom-pages/shared.ts @@ -58,7 +58,7 @@ export function report(name: string, value: string) { export async function loadInstance() { const input = new URL(location.href).searchParams.get('source') === 'http' - ? new URL('./fixture.dcm', document.baseURI) + ? new URL('./corpus-data/fixture.dcm', document.baseURI) : new File([fixtureBytes() as Uint8Array], 'fixture.dcm'); return runtime.readInstance(sourceOf(input), never); } diff --git a/tests/fixtures/dicom-pages/volumeCorpusReference.py b/tests/fixtures/dicom-pages/volumeCorpusReference.py new file mode 100644 index 000000000..ad8ec3b4b --- /dev/null +++ b/tests/fixtures/dicom-pages/volumeCorpusReference.py @@ -0,0 +1,86 @@ +"""Check the volume corpus expectations using pydicom and NumPy, independently of VolView. + +First download the fixtures with node tests/downloadDatasets.ts. This optional +reference check requires pydicom, NumPy and decoder plugins for JPEG Lossless, +JPEG-LS and JPEG 2000 such as pylibjpeg-libjpeg and pylibjpeg-openjpeg. It reads +cached inputs and never creates binary fixtures. +""" +import argparse +import hashlib +import json +from pathlib import Path + +import numpy as np +import pydicom + + +def frame_groups(ds): + shared = ds.get('SharedFunctionalGroupsSequence', [None])[0] + per_frame = ds.get('PerFrameFunctionalGroupsSequence', []) + return shared, per_frame + + +def macro(groups, sequence, keyword): + """The first value of a functional group macro attribute, or None.""" + for group in groups: + items = group.get(sequence) if group is not None else None + if items and keyword in items[0]: + return items[0][keyword].value + return None + + +def rescale(ds, frame): + """Slope and intercept of one frame: Functional Groups first, then the root.""" + shared, per_frame = frame_groups(ds) + groups = [per_frame[frame] if per_frame else None, shared] + slope = macro(groups, 'PixelValueTransformationSequence', 'RescaleSlope') + intercept = macro(groups, 'PixelValueTransformationSequence', 'RescaleIntercept') + return ( + float(slope if slope is not None else ds.get('RescaleSlope', 1)), + float(intercept if intercept is not None else ds.get('RescaleIntercept', 0)), + ) + + +def calibrated(ds): + """Modality-rescaled samples as [frame, row, column], in stored frame order.""" + frames = int(ds.get('NumberOfFrames', 1)) + stored = ds.pixel_array.astype(np.float64).reshape(frames, int(ds.Rows), int(ds.Columns)) + return np.stack([ + stored[frame] * slope + intercept + for frame in range(frames) + for slope, intercept in [rescale(ds, frame)] + ]).astype('; export type DataElement = { tag: number; vr: string; value: Value }; -const LONG_FORM = new Set([ - 'OB', - 'OD', - 'OF', - 'OL', - 'OV', - 'OW', - 'SQ', - 'UN', - 'UT', -]); const NUMBER_WIDTH: Record = { US: 2, SS: 2, @@ -93,7 +82,7 @@ function encodeElement(element: DataElement, encoding: Encoding) { const { littleEndian } = encoding; const value = valueBytes(element, encoding); const head = encoding.explicit - ? LONG_FORM.has(element.vr) + ? LONG_FORM_VRS.has(element.vr) ? [ new TextEncoder().encode(element.vr), new Uint8Array(2), diff --git a/tests/pageobjects/volview.page.ts b/tests/pageobjects/volview.page.ts index 37e58e26b..d7fdde58c 100644 --- a/tests/pageobjects/volview.page.ts +++ b/tests/pageobjects/volview.page.ts @@ -68,6 +68,29 @@ class VolViewPage extends Page { ); } + /** Every view has a sized canvas and none is still loading its image. */ + async waitForViewsLoaded() { + await browser.waitUntil( + () => + browser.execute(() => { + const canvases = Array.from( + document.querySelectorAll( + 'div[data-testid~="vtk-view"] canvas' + ) + ); + return ( + canvases.length > 0 && + canvases.every(({ width, height }) => width > 10 && height > 10) && + !document.querySelector('.loading-indicator') + ); + }), + { + timeout: DOWNLOAD_TIMEOUT, + timeoutMsg: 'Expected every view to finish loading', + } + ); + } + get volumeCards() { return $$('.volume-card'); } @@ -92,6 +115,7 @@ class VolViewPage extends Page { ); }, { + timeout: DOWNLOAD_TIMEOUT, timeoutMsg: `expected volume cards holding ${expected.join( ', ' )} slices`, @@ -99,34 +123,14 @@ class VolViewPage extends Page { ); } - /** - * Deletes the volume of the card at `index` of `getVolumeCardSliceCounts`, - * which orders by slice count rather than by the order the cards render in. - */ - async deleteVolumeCard(index: number) { - const counts = await this.getVolumeCardSliceCounts(); - const cards = [...(await this.volumeCards)]; - const labelled = await Promise.all( - cards.map(async (card) => ({ - card, - count: Number((await card.getText()).match(/\[(\d+)\]/)?.[1]), - })) + /** Deletes the volume whose card label carries `[sliceCount]`. */ + async deleteVolumeCard(sliceCount: number) { + const menu = $(`.volume-card*=[${sliceCount}]`).$( + 'button[data-testid="dataset-menu-button"]' ); - const target = labelled.find(({ count }) => count === counts[index]); - if (!target) throw new Error(`no volume card holding ${counts[index]}`); - - const menu = target.card.$('button[data-testid="dataset-menu-button"]'); await menu.waitForClickable(); await menu.click(); - - const remove = await browser.waitUntil( - async () => { - const items = [...(await $$('.v-overlay-container .v-list-item'))]; - const texts = await Promise.all(items.map((item) => item.getText())); - return items[texts.findIndex((text) => text.trim() === 'Delete')]; - }, - { timeoutMsg: 'expected a Delete item in the dataset menu' } - ); + const remove = $('.v-overlay-container').$('.v-list-item=Delete'); await remove.waitForClickable(); await remove.click(); } @@ -155,8 +159,17 @@ class VolViewPage extends Page { ); } - async getNotificationTitles() { + /** Opens the message center once no toast covers its button. */ + async openNotifications() { + await browser.waitUntil( + async () => (await $$('.Vue-Toastification__toast').length) === 0, + { timeoutMsg: 'expected the toasts to close' } + ); await this.notifications.click(); + } + + async getNotificationTitles() { + await this.openNotifications(); const titles = $$( '.message-center .v-expansion-panel-title .header > span' ); diff --git a/tests/specs/crosshairs-multi-image.e2e.ts b/tests/specs/crosshairs-multi-image.e2e.ts index ebbec7007..a33077b7e 100644 --- a/tests/specs/crosshairs-multi-image.e2e.ts +++ b/tests/specs/crosshairs-multi-image.e2e.ts @@ -145,8 +145,11 @@ describe('Crosshairs with two base images', () => { await crosshairsButton.waitForClickable(); await crosshairsButton.click(); + for (const slot of [0, 1, 2]) + await expect($$('.grid-item')[slot].$('.slice-label')).toHaveText( + 'Slice: 9/16' + ); const before = await getSlices(); - expect(before.slice(0, 3)).toEqual([9, 9, 9]); // Drag the crosshair well off centre in a view of the other image. await dragInSlot(0, 60, 40); diff --git a/tests/specs/dicom-dimension-mismatch.e2e.ts b/tests/specs/dicom-dimension-mismatch.e2e.ts index 0c6b40ca8..75ae9bd07 100644 --- a/tests/specs/dicom-dimension-mismatch.e2e.ts +++ b/tests/specs/dicom-dimension-mismatch.e2e.ts @@ -1,34 +1,23 @@ // A DICOM series whose instances disagree on Rows/Columns is two datasets, not // one volume with a rejected slice: the collection planner splits on pixel -// geometry, so the scout lands in its own volume whether it arrives first or -// last, and neither volume reports an error. +// geometry, so the scout lands in its own volume and neither volume reports an +// error. import * as path from 'path'; import * as fs from 'fs'; +import { DOWNLOAD_TIMEOUT } from '../../wdio.shared.conf'; import { volViewPage } from '../pageobjects/volview.page'; import { buildSyntheticDicom, newUid } from './syntheticDicom'; import { makeTempDir, writeManifestToFile } from './utils'; -const IMAGE_ORIENTATION_PATIENT = [1, 0, 0, 0, 1, 0] as const; const SLICE_COUNT = 5; +const DIR_NAME = 'geometry-split'; -const SERIES_ROWS = 4; -const SERIES_COLS = 6; -const SCOUT_ROWS = 8; -const SCOUT_COLS = 10; - -async function writeSeries( - dirName: string, - scoutSlice: number, - manifestName: string -) { - const dir = makeTempDir(dirName); - +async function writeSeries(manifestName: string) { + const dir = makeTempDir(DIR_NAME); const studyUid = newUid(); const seriesUid = newUid(); - const resources = []; - - for (let i = 0; i < SLICE_COUNT; i++) { - const scout = i === scoutSlice; + const resources = Array.from({ length: SLICE_COUNT }, (_, i) => { + const scout = i === 0; const filename = `slice-${i}.dcm`; fs.writeFileSync( path.join(dir, filename), @@ -37,56 +26,26 @@ async function writeSeries( seriesUid, sopUid: newUid(), instanceNumber: i + 1, - imageOrientationPatient: IMAGE_ORIENTATION_PATIENT, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], imagePositionPatient: [0, 0, i], - rows: scout ? SCOUT_ROWS : SERIES_ROWS, - cols: scout ? SCOUT_COLS : SERIES_COLS, + rows: scout ? 8 : 4, + cols: scout ? 10 : 6, }) ); - resources.push({ url: `tmp/${dirName}/${filename}`, name: filename }); - } - + return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; + }); await writeManifestToFile({ resources }, manifestName); } -async function waitForVolumeCards(count: number) { - await browser.waitUntil( - async () => (await $$('.volume-card').length) === count, - { - timeoutMsg: `expected exactly ${count} volume cards`, - } - ); -} - -async function loadSplitSeries(dirName: string, scoutSlice: number) { - const manifestName = `${dirName}-${Date.now()}.json`; - await writeSeries(dirName, scoutSlice, manifestName); - await volViewPage.open(`?urls=[tmp/${manifestName}]`); - await volViewPage.waitForViews(); - await waitForVolumeCards(2); -} - describe('DICOM series with instances of two pixel geometries', () => { - it('splits the scout out when it arrives first', async () => { - await loadSplitSeries('geometry-split-first', 0); - - await volViewPage.waitForVolumeCardSliceCounts([1, 4]); - - // Splitting is not a failure, so nothing is reported. - expect(await volViewPage.getNotificationsCount()).toBe(0); - }); - - it('splits the scout out when it arrives last', async () => { - await loadSplitSeries('geometry-split-last', SLICE_COUNT - 1); - + it('splits the scout into its own volume and thumbnails both', async () => { + const manifestName = `${DIR_NAME}-${Date.now()}.json`; + await writeSeries(manifestName); + await volViewPage.open(`?urls=[tmp/${manifestName}]`); + await volViewPage.waitForViews(); await volViewPage.waitForVolumeCardSliceCounts([1, 4]); - expect(await volViewPage.getNotificationsCount()).toBe(0); - }); - - it('thumbnails both volumes from their own slices', async () => { - await loadSplitSeries('geometry-split-thumbnails', 0); - + // A thumbnail needs decoded pixels, so both volumes have loaded by then. await browser.waitUntil( async () => { const sources = await $$('.volume-card img.v-img__img').map( @@ -98,9 +57,13 @@ describe('DICOM series with instances of two pixel geometries', () => { ); }, { + timeout: DOWNLOAD_TIMEOUT, timeoutMsg: 'expected both volume cards to render a data-URL thumbnail instead of the modality fallback', } ); + + // Splitting is not a failure, so nothing is reported. + expect(await volViewPage.getNotificationsCount()).toBe(0); }); }); diff --git a/tests/specs/dicom-frame-reconstruction.e2e.ts b/tests/specs/dicom-frame-reconstruction.e2e.ts index 5ff78af4b..db569cf4f 100644 --- a/tests/specs/dicom-frame-reconstruction.e2e.ts +++ b/tests/specs/dicom-frame-reconstruction.e2e.ts @@ -4,7 +4,6 @@ import { resolve } from 'node:path'; import { TEMP_DIR } from '../../wdio.shared.conf'; import { openDicomPage } from '../dicomPages'; import { enhancedFixtureBytes } from '../fixtures/dicom-pages/enhancedFixtures'; -import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { volViewPage } from '../pageobjects/volview.page'; @@ -22,13 +21,6 @@ const frames = { sharedPosition: [10, 20, 30], temporalPositions: [1, 2], }), - varying: enhancedFixtureBytes({ - pixelValues: [2, 2], - transforms: [ - [1, 0], - [2, 0], - ], - }), uniform: enhancedFixtureBytes({ pixelValues: [2, 2], transforms: [ @@ -47,88 +39,55 @@ const hashFrames = (values: number[]) => ) ) .digest('hex'); -const irregular = 'Cannot allocate irregular DICOM geometry: '; + const scenarios = [ { name: 'uneven', - policy: 'preserve-order', + source: 'file', values: [20, 120, 220], reconstruction: 'irregular', }, { - name: 'uneven', - policy: 'reject', - error: `${irregular}uneven-slice-spacing`, - }, - { - name: 'temporal', - policy: 'reject', - error: `${irregular}unreadable-geometry`, - }, - { - name: 'varying', - error: - 'Cannot load DICOM frames with differing modality rescale: the decoder applies one transform to the entire instance', - }, - { - name: 'varying', - decoder: 'custom', - values: [2, 4], + name: 'uniform', + source: 'http', + values: [4, 4], reconstruction: 'regular', }, - { name: 'uniform', values: [4, 4], reconstruction: 'regular' }, ]; describe('Encoded multiframe reconstruction contracts', () => { let fixture: Awaited>; before(async () => { - fixture = await startDicomPages(fixtureBytes(), { - kinds: ['corpus'], - fixtures: frames, - }); + fixture = await startDicomPages({ kinds: ['corpus'], fixtures: frames }); }); after(async () => fixture?.close()); - for (const scenario of scenarios) { - for (const source of ['file', 'http']) { - it(`handles ${scenario.name} frames from ${source} with ${scenario.decoder ?? 'default'} decoding and ${scenario.policy ?? 'default'} geometry policy`, async () => { - const params = new URLSearchParams({ name: scenario.name, source }); - if (scenario.policy) params.set('policy', scenario.policy); - if (scenario.decoder) params.set('decoder', scenario.decoder); - await openDicomPage(`${fixture.urls.corpus}?${params}`, scenario.error); - if (scenario.values) { - await expect($('#pixel-hash')).toHaveText( - hashFrames(scenario.values) - ); - await expect($('#reconstruction')).toHaveText( - scenario.reconstruction - ); - } - }); - } + for (const { name, source, values, reconstruction } of scenarios) { + it(`loads ${name} frames from ${source} in frame order with ${reconstruction} reconstruction`, async () => { + const params = new URLSearchParams({ name, source }); + await openDicomPage(`${fixture.urls.corpus}?${params}`); + await expect($('#pixel-hash')).toHaveText(hashFrames(values)); + await expect($('#reconstruction')).toHaveText(reconstruction); + }); } }); describe('Multiframe reconstruction notices', () => { - for (const name of ['uneven', 'temporal'] as const) { - it(`shows the user why ${name} frames have approximate spatial placement`, async () => { - const file = `enhanced-${name}.dcm`; - writeFileSync(resolve(TEMP_DIR, file), frames[name]); - await volViewPage.open(`?urls=[tmp/${file}]`); - await volViewPage.waitForVolumeCardSliceCounts([ - name === 'uneven' ? 3 : 2, - ]); - await volViewPage.waitForViews(); - expect(await volViewPage.getNotificationsCount()).toBe(1); - await volViewPage.notifications.click(); - const warning = $('.message-center .warn-message'); - await expect(warning).toHaveText( - expect.stringContaining('did not load as one sound volume') - ); - await warning.click(); - await expect($('.message-center .details')).toHaveText( - expect.stringContaining('positions and measurements') - ); - }); - } + it('shows the user why temporal frames have approximate spatial placement', async () => { + const file = 'enhanced-temporal.dcm'; + writeFileSync(resolve(TEMP_DIR, file), frames.temporal); + await volViewPage.open(`?urls=[tmp/${file}]`); + await volViewPage.waitForVolumeCardSliceCounts([2]); + await volViewPage.waitForViews(); + expect(await volViewPage.getNotificationsCount()).toBe(1); + await volViewPage.openNotifications(); + const warning = $('.message-center .warn-message'); + await expect(warning).toHaveText( + expect.stringContaining('did not load as one sound volume') + ); + await warning.click(); + await expect($('.message-center .details')).toHaveText( + expect.stringContaining('positions and measurements') + ); + }); }); diff --git a/tests/specs/dicom-import-regressions.e2e.ts b/tests/specs/dicom-import-regressions.e2e.ts index 574a493bc..4f92fd8ee 100644 --- a/tests/specs/dicom-import-regressions.e2e.ts +++ b/tests/specs/dicom-import-regressions.e2e.ts @@ -1,3 +1,5 @@ +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; import { PNG } from 'pngjs'; import { volViewPage } from '../pageobjects/volview.page'; import { @@ -8,32 +10,22 @@ import { toImplicitVr, undefinedLengthUnknown, } from './syntheticDicom'; +import { dropFiles, makeTempDir, openSpacingDetails } from './utils'; const AXIAL = [1, 0, 0, 0, 1, 0] as const; // Exercise the local File import path, including metadata scanning and pixel // decoding, through the same drop event a user produces. -async function dropFiles(files: Uint8Array[]) { +async function dropSlices(files: Uint8Array[]) { + const directory = makeTempDir('import-regressions'); + const paths = files.map((bytes, i) => { + const file = join(directory, `slice-${i}.dcm`); + writeFileSync(file, bytes); + return file; + }); await volViewPage.open(); await $('#app-container').waitForExist(); - await browser.execute( - (encodedFiles) => { - const transfer = new DataTransfer(); - encodedFiles.forEach((encoded, i) => { - const bytes = Uint8Array.from(atob(encoded), (char) => - char.charCodeAt(0) - ); - transfer.items.add(new File([bytes], `slice-${i}.dcm`)); - }); - const event = new Event('drop', { bubbles: true, cancelable: true }); - // Synthetic items have no filesystem entries, so supply the files list. - Object.defineProperty(event, 'dataTransfer', { - value: { items: null, files: transfer.files }, - }); - document.querySelector('#app-container')!.dispatchEvent(event); - }, - files.map((bytes) => Buffer.from(bytes).toString('base64')) - ); + await dropFiles(paths); } async function probeCenter(view: WebdriverIO.Element, expected: number) { @@ -45,15 +37,6 @@ async function probeCenter(view: WebdriverIO.Element, expected: number) { ).toHaveText(String(expected)); } -async function openSpacingDetails() { - await $('.volume-card [data-testid="dataset-menu-button"]').click(); - const item = $('[data-testid="dataset-menu-spacing-item"]'); - await item.waitForStable(); - await item.waitForClickable(); - await item.click(); - await $('[data-testid="image-spacing-details"]').waitForDisplayed(); -} - async function axialView(sliceCount: number) { return browser.waitUntil(async () => { const views = await $$('[data-testid~="vtk-two-view"]'); @@ -112,16 +95,16 @@ describe('Local DICOM import regressions', () => { }) ); - await dropFiles(files); + await dropSlices(files); await volViewPage.waitForVolumeCardSliceCounts([121]); await volViewPage.waitForViews(); await volViewPage.waitForLoadingIndicator( $('[data-testid~="vtk-two-view"]') ); await openSpacingDetails(); - await expect($('[data-testid="spacing-axis-Z"]')).toHaveText( - expect.stringContaining('5 mm') - ); + await expect( + $('[data-testid="spacing-axis-Z"] td:nth-child(2)') + ).toHaveText('5 mm'); await $('[data-testid="spacing-details-close"]').click(); const view = await axialView(121); for (const index of [0, 60, 120]) { @@ -135,7 +118,7 @@ describe('Local DICOM import regressions', () => { const content = toImplicitVr( rawElement(0x0043, 0x1030, 'LO', new TextEncoder().encode('VALUE ')) ); - await dropFiles([ + await dropSlices([ buildSyntheticDicom({ studyUid: newUid(), seriesUid: newUid(), @@ -162,8 +145,46 @@ describe('Local DICOM import regressions', () => { expect(await volViewPage.getNotificationsCount()).toBe(0); }); - it('renders green and blue content in a color DICOM thumbnail without red samples', async () => { - await dropFiles([ + it('loads the rest of a series and reports once when one slice cannot be decoded', async () => { + const studyUid = newUid(); + const seriesUid = newUid(); + const files = Array.from({ length: 5 }, (_, i) => + buildSyntheticDicom({ + studyUid, + seriesUid, + sopUid: newUid(), + instanceNumber: i + 1, + imageOrientationPatient: AXIAL, + imagePositionPatient: [0, 0, i], + rows: 4, + cols: 4, + pixelValue: 10 * (i + 1), + }) + ); + // 1.2.840.10008.1.2.9 is a transfer syntax no decoder reads. + const syntax = Buffer.from(files[1]).indexOf('1.2.840.10008.1.2.1\0'); + files[1][syntax + 18] = '9'.charCodeAt(0); + + await dropSlices(files); + await volViewPage.waitForVolumeCardSliceCounts([5]); + await volViewPage.waitForNotification(); + await volViewPage.waitForViews(); + await volViewPage.waitForLoadingIndicator( + $('[data-testid~="vtk-two-view"]') + ); + const view = await axialView(5); + for (const index of [0, 2, 4]) { + await selectSlice(view, index, 5); + await probeCenter(view, 10 * (index + 1)); + } + const name = await $('.volume-card .series-desc').getText(); + expect(await volViewPage.getNotificationTitles()).toEqual([ + `Error loading ${name}`, + ]); + }); + + it('shows a color slice with no red as luminance in its thumbnail', async () => { + await dropSlices([ buildSyntheticDicom({ studyUid: newUid(), seriesUid: newUid(), diff --git a/tests/specs/dicom-japanese-name.e2e.ts b/tests/specs/dicom-japanese-name.e2e.ts index 22a88816d..453919998 100644 --- a/tests/specs/dicom-japanese-name.e2e.ts +++ b/tests/specs/dicom-japanese-name.e2e.ts @@ -1,90 +1,33 @@ import * as fs from 'fs'; import * as path from 'path'; -import JSZip from 'jszip'; import { cleanuptotal } from 'wdio-cleanuptotal-service'; import { TEMP_DIR } from '../../wdio.shared.conf'; import { volViewPage } from '../pageobjects/volview.page'; -import { buildSyntheticDicom, newUid } from './syntheticDicom'; +import { + buildSlice, + JAPANESE_NAME, + JAPANESE_NAME_BYTES, +} from './dicomElementFixtures'; +import { newUid } from './syntheticDicom'; import { writeManifestToFile } from './utils'; -const ascii = (text: string) => Array.from(text, (c) => c.charCodeAt(0)); - -// ESC $ B designates JIS X 0208, ESC ( B returns to ASCII, as ISO 2022 IR 87 -// requires around every run of ideographic or phonetic characters. -const jisX0208 = (...codes: number[]) => [ - 0x1b, - 0x24, - 0x42, - ...codes, - 0x1b, - 0x28, - 0x42, -]; - -const JAPANESE_NAME = 'Yamada^Tarou=山田^太郎=やまだ^たろう'; -const JAPANESE_NAME_BYTES = new Uint8Array([ - ...ascii('Yamada^Tarou='), - ...jisX0208(0x3b, 0x33, 0x45, 0x44), - ...ascii('^'), - ...jisX0208(0x42, 0x40, 0x4f, 0x3a), - ...ascii('='), - ...jisX0208(0x24, 0x64, 0x24, 0x5e, 0x24, 0x40), - ...ascii('^'), - ...jisX0208(0x24, 0x3f, 0x24, 0x6d, 0x24, 0x26), -]); - -const japaneseNameDicom = () => - buildSyntheticDicom({ - studyUid: newUid(), - seriesUid: newUid(), - sopUid: newUid(), - instanceNumber: 1, - imageOrientationPatient: [1, 0, 0, 0, 1, 0], - imagePositionPatient: [0, 0, 0], - specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 87', - patientNameBytes: JAPANESE_NAME_BYTES, - }); - -const writeTempFile = (fileName: string, contents: Uint8Array | Buffer) => { - const filePath = path.join(TEMP_DIR, fileName); - fs.writeFileSync(filePath, contents); - cleanuptotal.addCleanup(async () => { - if (fs.existsSync(filePath)) fs.unlinkSync(filePath); - }); - return fileName; -}; - -const patientHeaderNames = async () => { - const headers = await $$('.patient-header-name'); - const names: string[] = []; - for (const header of headers) { - names.push(await header.getText()); - } - return names; -}; - -const waitForPatientName = async (expected: string) => { - let seen: string[] = []; - await browser.waitUntil( - async () => { - seen = await patientHeaderNames(); - return seen.includes(expected); - }, - { - timeoutMsg: `expected a patient named ${expected}`, - } - ); - expect(seen).toContain(expected); -}; - describe('DICOM patient name in a non-default character set', () => { it('decodes an ISO 2022 IR 87 name from a streamed DICOM', async () => { const stamp = Date.now(); - const fileName = writeTempFile( - `japanese-name-${stamp}.dcm`, - japaneseNameDicom() + const fileName = `japanese-name-${stamp}.dcm`; + const filePath = path.join(TEMP_DIR, fileName); + fs.writeFileSync( + filePath, + buildSlice({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 87', + patientNameBytes: JAPANESE_NAME_BYTES, + }) ); + cleanuptotal.addCleanup(async () => fs.unlinkSync(filePath)); const manifestName = `japanese-name-${stamp}.json`; await writeManifestToFile( { resources: [{ url: `/tmp/${fileName}`, name: fileName }] }, @@ -94,20 +37,6 @@ describe('DICOM patient name in a non-default character set', () => { await volViewPage.open(`?urls=[tmp/${manifestName}]`); await volViewPage.waitForViews(); - await waitForPatientName(JAPANESE_NAME); - }); - - it('decodes an ISO 2022 IR 87 name from a DICOM inside an archive', async () => { - const zip = new JSZip(); - zip.file('japanese-name.dcm', japaneseNameDicom()); - const zipName = writeTempFile( - `japanese-name-${Date.now()}.zip`, - await zip.generateAsync({ type: 'nodebuffer' }) - ); - - await volViewPage.open(`?urls=[tmp/${zipName}]`); - await volViewPage.waitForViews(); - - await waitForPatientName(JAPANESE_NAME); + await expect($('.patient-header-name')).toHaveText(JAPANESE_NAME); }); }); diff --git a/tests/specs/dicom-modality-rescale.e2e.ts b/tests/specs/dicom-modality-rescale.e2e.ts deleted file mode 100644 index 7005a4ecb..000000000 --- a/tests/specs/dicom-modality-rescale.e2e.ts +++ /dev/null @@ -1,65 +0,0 @@ -import * as fs from 'fs'; -import * as path from 'path'; - -import { volViewPage } from '../pageobjects/volview.page'; -import { buildSyntheticDicom, newUid } from './syntheticDicom'; -import { waitForFirstCompleteCachedImageScalars } from './imageCacheUtils'; -import { makeTempDir, writeManifestToFile } from './utils'; - -const PUBLIC_DSC_SERIES_UID = - '1.3.6.1.4.1.9590.100.1.2.284777661700890778225181143863199482857'; -const PUBLIC_DSC_SLOPE = 112067.85375182; -const STORED_VALUES = [0, 2, 65131]; -const ROWS = 4; -const COLUMNS = 4; - -async function writeRescaledSeries() { - const dirName = `modality-rescale-${Date.now()}`; - const dir = makeTempDir(dirName); - - const studyUid = newUid(); - const resources = STORED_VALUES.map((pixelValue, index) => { - const filename = `slice-${index}.dcm`; - fs.writeFileSync( - path.join(dir, filename), - buildSyntheticDicom({ - studyUid, - seriesUid: PUBLIC_DSC_SERIES_UID, - sopUid: newUid(), - instanceNumber: index + 1, - imageOrientationPatient: [1, 0, 0, 0, 1, 0], - imagePositionPatient: [0, 0, index], - rows: ROWS, - cols: COLUMNS, - bitsAllocated: 16, - bitsStored: 16, - highBit: 15, - pixelRepresentation: 0, - rescaleSlope: PUBLIC_DSC_SLOPE, - rescaleIntercept: 0, - pixelValue, - }) - ); - return { url: `tmp/${dirName}/${filename}`, name: filename }; - }); - - const manifestName = `modality-rescale-${Date.now()}.json`; - await writeManifestToFile({ resources }, manifestName); - return manifestName; -} - -describe('DICOM modality rescale', () => { - it('keeps the public DSC series rescale to float32 precision through volume loading', async () => { - const manifestName = await writeRescaledSeries(); - await volViewPage.open(`?urls=[tmp/${manifestName}]`); - await volViewPage.waitForViews(); - const scalars = await waitForFirstCompleteCachedImageScalars(); - - expect(await volViewPage.getNotificationsCount()).toBe(0); - expect(scalars.type).toBe('Float32Array'); - const expected = STORED_VALUES.flatMap((stored) => - Array(ROWS * COLUMNS).fill(Math.fround(stored * PUBLIC_DSC_SLOPE)) - ); - expect(scalars.values).toEqual(expected); - }); -}); diff --git a/tests/specs/dicom-module-pages.e2e.ts b/tests/specs/dicom-module-pages.e2e.ts index 17aa8346c..7f7be1389 100644 --- a/tests/specs/dicom-module-pages.e2e.ts +++ b/tests/specs/dicom-module-pages.e2e.ts @@ -8,7 +8,9 @@ import { openDicomPage } from '../dicomPages'; describe('DICOM module pages without VolView startup', () => { let fixture: Awaited>; before(async () => { - fixture = await startDicomPages(fixtureBytes()); + fixture = await startDicomPages({ + fixtures: { 'fixture.dcm': fixtureBytes() }, + }); }); after(async () => fixture?.close()); @@ -23,35 +25,28 @@ describe('DICOM module pages without VolView startup', () => { ); }); - for (const kind of ['core', 'vtk'] as const) { - for (const source of ['file', 'http']) { - it(`${kind} preserves metadata and calibrated pixels from ${source}`, async () => { - await openDicomPage(`${fixture.urls[kind]}?source=${source}`); - await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); - await expect($('#position')).toHaveText('10, 20, 30'); - await expect($('#pixel-spacing')).toHaveText('2, 3'); - if (kind === 'core') { - await expect($('#pixels')).toHaveText( - Array(16).fill('-10').join(', ') - ); - } else { - await expect($('#spacing')).toHaveText('3, 2, 4'); - await expect($('#origin')).toHaveText('10, 20, 30'); - await expect($('#range')).toHaveText('-10, -10'); - const screenshot = PNG.sync.read( - await $('#viewport').saveScreenshot( - resolve(TEMP_DIR, `dicom-${source}.png`) - ) - ); - const center = - ((screenshot.height >> 1) * screenshot.width + - (screenshot.width >> 1)) * - 4; - expect(screenshot.data[center]).toBeGreaterThan(110); - expect(screenshot.data[center]).toBeLessThan(145); - expect(screenshot.data[0]).toBe(0); - } - }); - } - } + it('core reads metadata and calibrated pixels from a file', async () => { + await openDicomPage(`${fixture.urls.core}?source=file`); + await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); + await expect($('#position')).toHaveText('10, 20, 30'); + await expect($('#pixel-spacing')).toHaveText('2, 3'); + await expect($('#pixels')).toHaveText(Array(16).fill('-10').join(', ')); + }); + + it('vtk places and renders the volume read over HTTP', async () => { + await openDicomPage(`${fixture.urls.vtk}?source=http`); + await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); + await expect($('#spacing')).toHaveText('3, 2, 4'); + await expect($('#origin')).toHaveText('10, 20, 30'); + await expect($('#range')).toHaveText('-10, -10'); + const screenshot = PNG.sync.read( + await $('#viewport').saveScreenshot(resolve(TEMP_DIR, 'dicom-vtk.png')) + ); + const center = + ((screenshot.height >> 1) * screenshot.width + (screenshot.width >> 1)) * + 4; + expect(screenshot.data[center]).toBeGreaterThan(110); + expect(screenshot.data[center]).toBeLessThan(145); + expect(screenshot.data[0]).toBe(0); + }); }); diff --git a/tests/specs/dicom-native-parity.e2e.ts b/tests/specs/dicom-native-parity.e2e.ts index c3777b2cf..0fc7d1fc0 100644 --- a/tests/specs/dicom-native-parity.e2e.ts +++ b/tests/specs/dicom-native-parity.e2e.ts @@ -1,15 +1,11 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import JSZip from 'jszip'; -import corpus from '../dicomVolumeCorpus.json'; -import composition from '../dicomCompositionCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; import { openDicomPage } from '../dicomPages'; -import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { EXPLICIT_BE, - EXPLICIT_LE, IMPLICIT_LE, nativePixelDicom, type DataElement, @@ -86,6 +82,7 @@ const synthetic: Array<[string, boolean, NativePixelOptions]> = [ ['ct-fractional', true, { bitsStored: 12, rescale: [0.5, -0.25] }], ['ct-irrational', true, { pixelRepresentation: 1, rescale: [1.9413152, 0.1] }], ['ct-zero-slope', true, { pixelRepresentation: 1, rescale: [0, 7] }], + ['dsc-large-slope', true, { rescale: [112067.85375182, 0] }], ['enhanced-ct-uniform', true, { sopClassUid: SOP_CLASSES.EnhancedCT, frames: 3, frameRescales: [[2, -1], [2, -1], [2, -1]] }], ['enhanced-mr-fractional', true, { sopClassUid: SOP_CLASSES.EnhancedMR, modality: 'MR', frames: 2, frameRescales: [[0.3, 1], [0.3, 1]] }], ['enhanced-ct-differing', false, { sopClassUid: SOP_CLASSES.EnhancedCT, frames: 2, frameRescales: [[1, 0], [2, 0]] }], @@ -97,33 +94,26 @@ const synthetic: Array<[string, boolean, NativePixelOptions]> = [ ), ]; -const NATIVE_SYNTAXES = new Set([IMPLICIT_LE, EXPLICIT_LE, EXPLICIT_BE]); - -// Uncompressed public files decode natively, except the enhanced CT whose -// supplemental palette GDCM applies. -const corpusNative = (name: string, syntax: string) => - NATIVE_SYNTAXES.has(syntax) && !name.includes('eCT_Supplemental'); - const cached = (names: string[]) => names.map( (name) => [name, readFileSync(resolve(DATASET_CACHE, name))] as const ); -const zipped = async (zip: string) => { +/** One slice of an archive whose slices all share a pixel format. */ +const firstSlice = async (zip: string) => { const archive = await JSZip.loadAsync( readFileSync(resolve(DATASET_CACHE, zip)) ); - const files = Object.values(archive.files).filter((file) => !file.dir); - return Promise.all( - files.map( - async (file) => - [`${zip}/${file.name}`, await file.async('uint8array')] as const - ) - ); + const [file] = Object.values(archive.files).filter((entry) => !entry.dir); + return [`${zip}/${file.name}`, await file.async('uint8array')] as const; }; -/** Pages per source, each small enough to finish quickly under load. */ -const PAGES = 16; +// The public singles decode natively except the two compressed ultrasounds. +const publicNative = (name: string) => + !/US_multiframe|jpeg_baseline/.test(name); + +/** Pages small enough to finish quickly under load. */ +const PAGES = 4; type ParityResult = { name: string; @@ -141,33 +131,26 @@ describe('Native frame decoding parity with GDCM', () => { const expectedNative = new Map(); let cases: string[] = []; before(async () => { + const publicFiles = [ + ...cached(['CT000085.dcm', 'minimal.dcm', 'retinal-oct.dcm']), + ...cached(['US-MONO2-8-8x-echo.dcm', 'US_multiframe_30frames.dcm']), + ...cached(['color3d_jpeg_baseline.dcm']), + await firstSlice('prostate.zip'), + await firstSlice('MRA-Head_and_Neck.zip'), + ]; const files = [ ...synthetic.map( ([name, , options], index) => [name, nativePixelDicom({ ...options, instance: index + 1 })] as const ), - ...cached(corpus.map(({ name }) => name)), - ...cached(composition.datasets.map(({ name }) => name)), - ...cached(['CT000085.dcm', 'minimal.dcm', 'retinal-oct.dcm']), - ...cached(['US-MONO2-8-8x-echo.dcm', 'US_multiframe_30frames.dcm']), - ...cached(['color3d_jpeg_baseline.dcm']), - ...(await zipped('prostate.zip')), - ...(await zipped('MRA-Head_and_Neck.zip')), + ...publicFiles, ]; cases = files.map(([name]) => name); synthetic.forEach(([name, native]) => expectedNative.set(name, native)); - corpus.forEach(({ name, transferSyntaxUID }) => - expectedNative.set(name, corpusNative(name, transferSyntaxUID)) + publicFiles.forEach(([name]) => + expectedNative.set(name, publicNative(name)) ); - // The two MR acquisitions are JPEG Lossless; the PET/CT files are not. - composition.datasets.forEach(({ name }) => - expectedNative.set(name, name.startsWith('PET-CT-')) - ); - files.forEach(([name]) => { - if (!expectedNative.has(name)) - expectedNative.set(name, !/US_multiframe|jpeg_baseline/.test(name)); - }); - fixture = await startDicomPages(fixtureBytes(), { + fixture = await startDicomPages({ kinds: ['parity'], fixtures: { ...Object.fromEntries(files), @@ -181,26 +164,23 @@ describe('Native frame decoding parity with GDCM', () => { const pageOf = (page: number) => cases.slice(page * pageSize(), (page + 1) * pageSize()); - for (const source of ['file', 'http']) - for (let page = 0; page < PAGES; page += 1) - it(`writes the volume natively as GDCM does from ${source}, page ${page + 1}`, async () => { - const wanted = pageOf(page); - const from = page * pageSize(); - await openDicomPage( - `${fixture.urls.parity}?source=${source}&from=${from}&to=${from + wanted.length}` - ); - const results: ParityResult[] = JSON.parse( - await $('#report').getText() - ); - const unexpected = results.filter( - (result) => - result.error || - result.mismatch || - result.rawMismatch || - (result.plan === 'frames') !== expectedNative.get(result.name) || - (result.plan === 'frames' && result.native !== result.volume) - ); - expect(unexpected).toEqual([]); - expect(results.map(({ name }) => name)).toEqual(wanted); - }); + for (let page = 0; page < PAGES; page += 1) + it(`writes the volume natively as GDCM does, page ${page + 1}`, async () => { + const wanted = pageOf(page); + const from = page * pageSize(); + await openDicomPage( + `${fixture.urls.parity}?from=${from}&to=${from + wanted.length}` + ); + const results: ParityResult[] = JSON.parse(await $('#report').getText()); + const unexpected = results.filter( + (result) => + result.error || + result.mismatch || + result.rawMismatch || + (result.plan === 'frames') !== expectedNative.get(result.name) || + (result.plan === 'frames' && result.native !== result.volume) + ); + expect(unexpected).toEqual([]); + expect(results.map(({ name }) => name)).toEqual(wanted); + }); }); diff --git a/tests/specs/dicom-spacing-details.e2e.ts b/tests/specs/dicom-spacing-details.e2e.ts index deb1ee55f..ed6209139 100644 --- a/tests/specs/dicom-spacing-details.e2e.ts +++ b/tests/specs/dicom-spacing-details.e2e.ts @@ -8,23 +8,19 @@ import { type SyntheticSliceOptions, } from './syntheticDicom'; import { enhancedFixtureBytes } from '../fixtures/dicom-pages/enhancedFixtures'; -import { dropFiles, SESSION_SAVE_TIMEOUT, waitForFileExists } from './utils'; +import { + dropFiles, + openSpacingDetails, + SESSION_SAVE_TIMEOUT, + waitForFileExists, +} from './utils'; const dialog = () => $('[data-testid="image-spacing-details"]'); const axis = (name: string) => dialog().$(`[data-testid="spacing-axis-${name}"]`); +const step = (name: string) => axis(name).$('td:nth-child(2)'); const closeDetails = () => $('[data-testid="spacing-details-close"]').click(); -async function openDetails() { - await $('.volume-card [data-testid="dataset-menu-button"]').click(); - const item = $('[data-testid="dataset-menu-spacing-item"]'); - await item.waitForDisplayed(); - await item.waitForStable(); - await item.waitForClickable(); - await item.click(); - await dialog().waitForDisplayed(); -} - function slice(options: Partial = {}) { return buildSyntheticDicom({ studyUid: newUid(), @@ -45,14 +41,14 @@ async function openFile(name: string, bytes: Uint8Array, slices = 1) { writeFileSync(join(TEMP_DIR, name), bytes); await volViewPage.open(`?urls=[tmp/${name}]`); await volViewPage.waitForVolumeCardSliceCounts([slices]); - await openDetails(); + await openSpacingDetails(); } describe('DICOM physical spacing details', () => { it('identifies unknown physical units in a public secondary capture', async () => { await volViewPage.open('?urls=[tmp/dicom-corpus-image_dfl.dcm]'); await volViewPage.waitForVolumeCardSliceCounts([1]); - await openDetails(); + await openSpacingDetails(); await expect(axis('X')).toHaveText( expect.stringContaining('physical unit unknown') ); @@ -91,8 +87,8 @@ describe('DICOM physical spacing details', () => { await dropFiles([join(TEMP_DIR, secondName)]); await volViewPage.waitForVolumeCardSliceCounts([2]); - await openDetails(); - await expect(axis('Z')).toHaveText(expect.stringContaining('2 mm')); + await openSpacingDetails(); + await expect(step('Z')).toHaveText('2 mm'); await expect(axis('Z')).toHaveText( expect.stringContaining('Derived: ImagePositionPatient') ); @@ -102,12 +98,11 @@ describe('DICOM physical spacing details', () => { await waitForFileExists(join(TEMP_DIR, saved), SESSION_SAVE_TIMEOUT); await volViewPage.open(`?urls=[tmp/${saved}]`); await volViewPage.waitForVolumeCardSliceCounts([2]); - await openDetails(); + await openSpacingDetails(); await expect(axis('X')).toHaveText(expect.stringContaining('0.25 mm')); await expect(axis('Z')).toHaveText( expect.stringContaining('Derived: ImagePositionPatient') ); - await browser.saveScreenshot(join(TEMP_DIR, 'dicom-spacing-details.png')); }); it('preserves the valid axis when the other PixelSpacing value is unusable', async () => { @@ -130,7 +125,7 @@ describe('DICOM physical spacing details', () => { slice({ framePixelValues: [40, 80], spacingBetweenSlices: 1.5 }), 2 ); - await expect(axis('Z')).toHaveText(expect.stringContaining('1.5 mm')); + await expect(step('Z')).toHaveText('1.5 mm'); await expect(axis('Z')).toHaveText( expect.stringContaining('Declared: SpacingBetweenSlices') ); @@ -145,8 +140,8 @@ describe('DICOM physical spacing details', () => { ultrasoundRegion: { physicalDeltaX: 0.05, physicalDeltaY: 0.03 }, }) ); - await expect(axis('X')).toHaveText(expect.stringContaining('0.5 mm')); - await expect(axis('Y')).toHaveText(expect.stringContaining('0.3 mm')); + await expect(step('X')).toHaveText('0.5 mm'); + await expect(step('Y')).toHaveText('0.3 mm'); await expect(dialog()).toHaveText( expect.stringContaining('cm converted to mm') ); diff --git a/tests/specs/dicom-volume-composition.e2e.ts b/tests/specs/dicom-volume-composition.e2e.ts index 3f7f617d6..bc0e42aa4 100644 --- a/tests/specs/dicom-volume-composition.e2e.ts +++ b/tests/specs/dicom-volume-composition.e2e.ts @@ -4,7 +4,6 @@ import corpus from '../dicomCompositionCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; import { waitForDicomPage } from '../dicomPages'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; -import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { volViewPage } from '../pageobjects/volview.page'; import { waitForRenderedSlice } from './dicomRenderedSlice'; @@ -61,29 +60,29 @@ describe('Downloaded DICOM volume composition', () => { readFileSync(resolve(DATASET_CACHE, name)), ]) ); - fixture = await startDicomPages(fixtureBytes(), { - kinds: ['composition'], - fixtures, - }); + fixture = await startDicomPages({ kinds: ['composition'], fixtures }); }); after(async () => fixture?.close()); + // Composition never sees where bytes come from, so each axis is covered once. + const imports = [ + ['file', 'batch'], + ['http', 'incremental'], + ]; for (const scenario of corpus.cases) { - for (const source of ['file', 'http']) { - for (const mode of ['batch', 'incremental']) { - it(`composes every ${scenario.id} collection from shuffled ${source} sources in ${mode} mode`, async () => { - await browser.url( - `${fixture.urls.composition}?${new URLSearchParams({ case: scenario.id, source, mode })}` - ); - if (mode === 'incremental') { - await waitForDicomPage(undefined, 'partial'); - await expectComposedVolumes(scenario.volumes, true); - await $('#complete-import').click(); - } - await waitForDicomPage(); - await expectComposedVolumes(scenario.volumes, false); - }); - } + for (const [source, mode] of imports) { + it(`composes every ${scenario.id} collection from shuffled ${source} sources in ${mode} mode`, async () => { + await browser.url( + `${fixture.urls.composition}?${new URLSearchParams({ case: scenario.id, source, mode })}` + ); + if (mode === 'incremental') { + await waitForDicomPage(undefined, 'partial'); + await expectComposedVolumes(scenario.volumes, true); + await $('#complete-import').click(); + } + await waitForDicomPage(); + await expectComposedVolumes(scenario.volumes, false); + }); } } }); @@ -100,11 +99,7 @@ describe('VolView downloaded collection import', () => { .map(({ expected }) => expected.dimensions[2]) .sort((a, b) => a - b) ); - await volViewPage.waitForViews(); - const views = $$('[data-testid~="vtk-view"]'); - for (let index = 0; index < (await views.length); index++) - await volViewPage.waitForLoadingIndicator(views[index]); - await expect($('.loading-indicator')).not.toBeExisting(); + await volViewPage.waitForViewsLoaded(); await waitForRenderedSlice( `composition-${scenario.id}.png`, 0, diff --git a/tests/specs/dicom-volume-corpus.e2e.ts b/tests/specs/dicom-volume-corpus.e2e.ts index 10f545a3b..53e1fa07f 100644 --- a/tests/specs/dicom-volume-corpus.e2e.ts +++ b/tests/specs/dicom-volume-corpus.e2e.ts @@ -2,13 +2,10 @@ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { Key } from 'webdriverio'; -import corpus from '../dicomVolumeCorpus.json'; +import volumeCorpus from '../dicomVolumeCorpus.json'; import { DATASET_CACHE } from '../downloadDatasets'; import { openDicomPage } from '../dicomPages'; -import { - fixtureBytes, - nullPaddedFixtureBytes, -} from '../fixtures/dicom-pages/fixtureData'; +import { nullPaddedFixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { volViewPage } from '../pageobjects/volview.page'; import { @@ -16,6 +13,8 @@ import { waitForRenderedSliceChange, } from './dicomRenderedSlice'; +const corpus = volumeCorpus.datasets; + type VolumeExpectation = { dimensions: number[]; range: number[]; @@ -77,7 +76,7 @@ describe('Public DICOM volume corpus', () => { readFileSync(resolve(DATASET_CACHE, name)), ]) ); - fixture = await startDicomPages(fixtureBytes(), { + fixture = await startDicomPages({ kinds: ['corpus'], fixtures: { ...files, @@ -90,25 +89,48 @@ describe('Public DICOM volume corpus', () => { }); after(async () => fixture?.close()); + async function expectVolume( + name: string, + source: string, + expected: VolumeExpectation + ) { + const params = new URLSearchParams({ name, source }); + await openDicomPage(`${fixture.urls.corpus}?${params}`); + await expect($('#dimensions')).toHaveText(expected.dimensions.join(', ')); + await expect($('#pixel-hash')).toHaveText(expected.pixelHash); + await expectNumbers('range', expected.range); + for (const id of ['spacing', 'origin', 'direction'] as const) { + if (expected[id]) await expectNumbers(id, expected[id]); + } + } + for (const { name, expected, expectedError } of cases) { for (const source of ['file', 'http']) { - const behavior = expectedError ? 'rejects' : 'preserves'; - it(`${behavior} ${name} pixels and geometry from ${source}`, async () => { - const params = new URLSearchParams({ name, source }); - await openDicomPage(`${fixture.urls.corpus}?${params}`, expectedError); - if (expectedError) return; - if (!expected) throw new Error(`Missing expectations for ${name}`); - await expect($('#dimensions')).toHaveText( - expected.dimensions.join(', ') - ); - await expect($('#pixel-hash')).toHaveText(expected.pixelHash); - await expectNumbers('range', expected.range); - for (const id of ['spacing', 'origin', 'direction'] as const) { - if (expected[id]) await expectNumbers(id, expected[id]); - } - }); + if (expectedError) { + it(`rejects ${name} from ${source}`, async () => { + const params = new URLSearchParams({ name, source }); + await openDicomPage( + `${fixture.urls.corpus}?${params}`, + expectedError + ); + }); + } else { + it(`preserves ${name} pixels and geometry from ${source}`, async () => { + if (!expected) throw new Error(`Missing expectations for ${name}`); + await expectVolume(name, source, expected); + }); + } } } + + // Each frame is its own ranged read, which this server answers with the file. + it('preserves a multiframe volume from a server that ignores Range', async () => { + const multiframe = corpus.find( + ({ expected }) => expected && expected.dimensions[2] > 30 + ); + if (!multiframe?.expected) throw new Error('No multiframe corpus file'); + await expectVolume(multiframe.name, 'unranged', multiframe.expected); + }); }); describe('VolView multiframe volume import', () => { @@ -122,8 +144,7 @@ describe('VolView multiframe volume import', () => { it(`displays ${name} as a complete volume`, async () => { await volViewPage.open(`?urls=[tmp/${name}]`); await volViewPage.waitForVolumeCardSliceCounts([expected!.dimensions[2]]); - await volViewPage.waitForViews(); - await expect($('.loading-indicator')).not.toBeExisting(); + await volViewPage.waitForViewsLoaded(); const before = await waitForRenderedSlice(`${name}-initial.png`); await volViewPage.focusFirst2DView(); const label = await $( diff --git a/tests/specs/dicomElementFixtures.ts b/tests/specs/dicomElementFixtures.ts index f1402ca0e..df6df01e7 100644 --- a/tests/specs/dicomElementFixtures.ts +++ b/tests/specs/dicomElementFixtures.ts @@ -2,21 +2,13 @@ import { attributeTagValue, buildSyntheticCineDicom, buildSyntheticDicom, + combine, rawElement, SyntheticSliceOptions, undefinedLengthItem, undefinedLengthSequence, } from './syntheticDicom'; -const concat = (...parts: Uint8Array[]) => { - const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); - parts.reduce((offset, part) => { - out.set(part, offset); - return offset + part.length; - }, 0); - return out; -}; - const bytes = (...values: number[]) => new Uint8Array(values); const ascii = (text: string) => new TextEncoder().encode(text); @@ -28,7 +20,7 @@ const jisX0208 = (...codes: number[]) => const JAPANESE_CHARACTER_SET = 'ISO 2022 IR 6\\ISO 2022 IR 87'; export const JAPANESE_NAME = 'Yamada^Tarou=山田^太郎=やまだ^たろう'; -export const JAPANESE_NAME_BYTES = concat( +export const JAPANESE_NAME_BYTES = combine( ascii('Yamada^Tarou='), jisX0208(0x3b, 0x33, 0x45, 0x44), ascii('^'), @@ -41,7 +33,7 @@ export const JAPANESE_NAME_BYTES = concat( // ISO 2022 IR 149 carries KS X 1001 in the high half, no escape needed. export const KOREAN_NAME = 'Hong^Gildong=洪^吉洞=홍^길동'; -export const KOREAN_NAME_BYTES = concat( +export const KOREAN_NAME_BYTES = combine( ascii('Hong^Gildong='), bytes(0xfb, 0xf3), ascii('^'), @@ -54,7 +46,7 @@ export const KOREAN_NAME_BYTES = concat( // GB 2312 in the high half. Odd length, so DICOM pads it with a space. export const CHINESE_NAME_PADDED = '王^小明 '; -export const CHINESE_NAME_BYTES = concat( +export const CHINESE_NAME_BYTES = combine( bytes(0xcd, 0xf5), ascii('^'), bytes(0xd0, 0xa1, 0xc3, 0xf7) @@ -62,7 +54,7 @@ export const CHINESE_NAME_BYTES = concat( // 0x81 0x39 0xee 0x39 is a four-byte GB18030 code no two-byte charset reaches. export const GB18030_NAME_PADDED = '王^㐀 '; -export const GB18030_NAME_BYTES = concat( +export const GB18030_NAME_BYTES = combine( bytes(0xcd, 0xf5), ascii('^'), bytes(0x81, 0x39, 0xee, 0x39) @@ -100,19 +92,14 @@ const floats = (...values: number[]) => { return out; }; -/** - * Elements the named writers cannot emit: a binary buffer VR, an attribute tag, - * binary floats, and the private elements every clinical vendor writes. Tags - * sort after (0028,1053) so the data set stays ascending. - */ export const KATAKANA_NAME = 'アイウ^エオ'; export const KATAKANA_NAME_BYTES = bytes(0xb1, 0xb2, 0xb3, 0x5e, 0xb4, 0xb5); // Half width katakana and JIS X 0208 runs in one value, which ISO 2022 allows -// and no single decoder covers. GDCM stopped at the first escape here, so this +// and no single decoder covers. GDCM stops at the first escape here, so this // fixture stays out of the differential corpus. export const MIXED_JIS_NAME = 'ヤマダ^タロウ=山田^太郎'; -export const MIXED_JIS_NAME_BYTES = concat( +export const MIXED_JIS_NAME_BYTES = combine( bytes(0xd4, 0xcf, 0xc0, 0xde), ascii('^'), bytes(0xc0, 0xdb, 0xb3), @@ -122,12 +109,17 @@ export const MIXED_JIS_NAME_BYTES = concat( jisX0208(0x42, 0x40, 0x4f, 0x3a) ); +/** + * Elements the named writers cannot emit: a binary buffer VR, an attribute tag, + * binary floats, and the private elements every clinical vendor writes. Tags + * sort after (0028,1053) so the data set stays ascending. + */ export const MIXED_VR_ELEMENTS = [ // (0028,2000) ICC Profile, OB. rawElement(0x0028, 0x2000, 'OB', new Uint8Array(8).fill(0x7f)), // (0028,9445) is FL in the dictionary; written UN, as a vendor would. rawElement(0x0028, 0x9445, 'UN', bytes(0x01, 0x02, 0x03, 0x04)), - // Odd groups, which every clinical vendor writes and GDCM never reported. + // Odd groups, which every clinical vendor writes and GDCM never reports. rawElement(0x0029, 0x0010, 'LO', ascii('SIEMENS CSA HEADER ')), rawElement(0x0029, 0x1010, 'OB', new Uint8Array(6).fill(0x41)), rawElement(0x0029, 0x1020, 'UN', new Uint8Array(4).fill(0x02)), @@ -143,7 +135,10 @@ export const MIXED_VR_ELEMENTS = [ 0x0028, 0x000a, 'AT', - concat(attributeTagValue(0x0018, 0x1063), attributeTagValue(0x0028, 0x00ff)) + combine( + attributeTagValue(0x0018, 0x1063), + attributeTagValue(0x0028, 0x00ff) + ) ), ]; @@ -257,7 +252,7 @@ export const tagReaderCorpus = (): Array<{ 0x0040, 0x0275, undefinedLengthItem( - concat( + combine( rawElement(0x0008, 0x0005, 'CS', ascii(JAPANESE_CHARACTER_SET)), rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES) ) @@ -315,7 +310,7 @@ export const tagReaderCorpus = (): Array<{ specificCharacterSet: 'ISO 2022 IR 13\\ISO 2022 IR 87', patientNameBytes: KATAKANA_NAME_BYTES, }), - // GDCM converted every string VR under the declared character set, so its + // GDCM converts every string VR under the declared character set, so its // CS and DS values carry the JIS X 0201 yen sign where the file wrote the // 0x5c value delimiter. PS3.5 6.1.2 limits that conversion to SH, LO, ST, // PN, LT, UC and UT, and the delimiter is never part of a value. diff --git a/tests/specs/dicomRenderedSlice.ts b/tests/specs/dicomRenderedSlice.ts index a4dec4653..d1fe5ca16 100644 --- a/tests/specs/dicomRenderedSlice.ts +++ b/tests/specs/dicomRenderedSlice.ts @@ -1,52 +1,20 @@ -import { resolve } from 'node:path'; -import { PNG } from 'pngjs'; -import { TEMP_DIR } from '../../wdio.shared.conf'; +import { captureViewPixels } from './utils'; type RenderedSlice = { width: number; height: number; data: Buffer }; +// The inset excludes orientation labels, slice counters, sliders and viewport +// controls, so UI text cannot satisfy image assertions. +const VIEW_INSET = 80; + async function captureSlice(fileName: string, viewIndex: number) { - const image = PNG.sync.read( - await browser.saveScreenshot(resolve(TEMP_DIR, fileName)) + const views = await captureViewPixels( + '[data-testid~="vtk-two-view"]', + VIEW_INSET, + fileName ); - const geometry = await browser.execute((index) => { - const view = document.querySelectorAll('[data-testid~="vtk-two-view"]')[ - index - ]; - if (!view) return null; - const rect = view.getBoundingClientRect(); - return { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - viewportWidth: window.innerWidth, - viewportHeight: window.innerHeight, - }; - }, viewIndex); - if (!geometry) throw new Error(`No slice viewport at index ${viewIndex}`); - const scaleX = image.width / geometry.viewportWidth; - const scaleY = image.height / geometry.viewportHeight; - const left = Math.ceil((geometry.x + geometry.width * 0.18) * scaleX); - const top = Math.ceil((geometry.y + geometry.height * 0.18) * scaleY); - const width = Math.floor(geometry.width * 0.64 * scaleX); - const height = Math.floor(geometry.height * 0.64 * scaleY); - if ( - width <= 0 || - height <= 0 || - left < 0 || - top < 0 || - left + width > image.width || - top + height > image.height - ) - throw new Error('The slice viewport has no interior image region'); - // The central image region excludes orientation labels, slice counters, - // sliders and viewport controls, so UI text cannot satisfy image assertions. - const data = Buffer.alloc(width * height * 4); - for (let row = 0; row < height; row++) { - const source = ((top + row) * image.width + left) * 4; - image.data.copy(data, row * width * 4, source, source + width * 4); - } - return { width, height, data }; + const view = views[viewIndex]; + if (!view) throw new Error(`No slice viewport at index ${viewIndex}`); + return { ...view, height: view.data.length / 4 / view.width }; } function hasImageContent( diff --git a/tests/specs/imageCacheUtils.ts b/tests/specs/imageCacheUtils.ts index 78f680e11..93ea32cd3 100644 --- a/tests/specs/imageCacheUtils.ts +++ b/tests/specs/imageCacheUtils.ts @@ -1,7 +1,5 @@ -type CachedImageScalars = { type: string; values: number[] }; - -async function readFirstCachedImage(property: 'spacing' | 'complete-scalars') { - return browser.execute((requestedProperty) => { +export function getFirstCachedImageSpacing() { + return browser.execute(() => { const app = (document.querySelector('#app') as any)?.__vue_app__; const pinia = app?.config?.globalProperties?.$pinia ?? @@ -17,22 +15,8 @@ async function readFirstCachedImage(property: 'spacing' | 'complete-scalars') { const id = imageCache?.imageIds?.[0]; const imageData = imageCache?.getVtkImageData(id); if (!imageData) return null; - if (requestedProperty === 'spacing') { - return Array.from(imageData.getSpacing()).map(Number); - } - if (imageCache.imageStatus[id] !== 'complete') return null; - - const data = imageData.getPointData().getScalars()?.getData(); - if (!data) return null; - return { - type: data.constructor.name, - values: Array.from(data as ArrayLike), - }; - }, property); -} - -export function getFirstCachedImageSpacing() { - return readFirstCachedImage('spacing') as Promise; + return Array.from(imageData.getSpacing()).map(Number); + }) as Promise; } export async function waitForFirstCachedImageSpacing() { @@ -49,24 +33,3 @@ export async function waitForFirstCachedImageSpacing() { ); return spacing!; } - -export function getFirstCompleteCachedImageScalars() { - return readFirstCachedImage( - 'complete-scalars' - ) as Promise; -} - -export async function waitForFirstCompleteCachedImageScalars() { - let scalars: CachedImageScalars | null = null; - await browser.waitUntil( - async () => { - scalars = await getFirstCompleteCachedImageScalars(); - return scalars !== null; - }, - { - timeout: 30_000, - timeoutMsg: 'Expected first cached image scalars to become available', - } - ); - return scalars!; -} diff --git a/tests/specs/incremental-positionless-import.e2e.ts b/tests/specs/incremental-positionless-import.e2e.ts index 1a9105fdf..86c5682b8 100644 --- a/tests/specs/incremental-positionless-import.e2e.ts +++ b/tests/specs/incremental-positionless-import.e2e.ts @@ -1,9 +1,12 @@ -// A second import must not dissolve the volumes the first one earned. +// One series carrying several overlapping acquisitions loads as one volume +// per acquisition, and a second import must not dissolve those volumes. // -// One series holds two overlapping acquisitions, which load as two volumes. -// A later import brings one more slice of that series whose +// Modelled on IDC series +// 1.3.6.1.4.1.14519.5.2.1.3098.5025.295130953269492004748715270821, which +// holds three 2.5mm chest/abdomen passes offset from each other by fractions +// of a slice. A later import brings one more slice of that series whose // ImagePositionPatient is empty, so nothing can be said about where it sits. -// Both volumes must survive, the unplaceable slice must arrive as a volume of +// Every volume must survive, the unplaceable slice must arrive as a volume of // its own, and the user must be told about it. // // Synthetic DICOMs are generated on the fly so the test carries no binary @@ -12,101 +15,59 @@ import * as path from 'path'; import * as fs from 'fs'; import { volViewPage } from '../pageobjects/volview.page'; import { TEMP_DIR } from '../../wdio.shared.conf'; -import { dropFiles, writeManifestToFile } from './utils'; +import { dropFiles, writeAcquisitions, writeManifestToFile } from './utils'; import { buildSyntheticDicom, newUid } from './syntheticDicom'; -const SLICE_SPACING = 2.5; -const ORIENTATION = [1, 0, 0, 0, 1, 0] as const; - -// Offset by half a slice, so the two passes overlap and the planner separates -// them. Slice counts differ so each volume card is identifiable by its label. +// Each pass is uniform on its own; the sub-slice offsets are what make the +// merged stack irregular. Slice counts differ so each volume card is +// identifiable by its label alone. const ACQUISITIONS = [ { number: 1, firstSliceZ: 0, sliceCount: 5 }, - { number: 2, firstSliceZ: 1.25, sliceCount: 6 }, + { number: 2, firstSliceZ: 0.75, sliceCount: 6 }, + { number: 3, firstSliceZ: 1.75, sliceCount: 4 }, ]; const DIR_NAME = 'incremental-positionless-import'; const MANIFEST_NAME = 'incremental-positionless-import.json'; -const POSITIONLESS_NAME = 'positionless.dcm'; - -const seriesUid = newUid(); -const studyUid = newUid(); - -const dir = () => path.join(TEMP_DIR, DIR_NAME); - -function writeSeries() { - fs.mkdirSync(dir(), { recursive: true }); - - let instanceNumber = 0; - return ACQUISITIONS.flatMap(({ number, firstSliceZ, sliceCount }) => - Array.from({ length: sliceCount }, (_, i) => { - instanceNumber += 1; - const filename = `acq${number}-slice${i}.dcm`; - fs.writeFileSync( - path.join(dir(), filename), - buildSyntheticDicom({ - studyUid, - seriesUid, - sopUid: newUid(), - instanceNumber, - acquisitionNumber: number, - imageOrientationPatient: ORIENTATION, - imagePositionPatient: [0, 0, firstSliceZ + i * SLICE_SPACING], - sliceThickness: SLICE_SPACING, - }) - ); - return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; - }) - ); -} - -// Same series and same hard facts as the two passes, so only its unreadable -// geometry can keep it out of them. -function writePositionlessSlice() { - fs.writeFileSync( - path.join(dir(), POSITIONLESS_NAME), - buildSyntheticDicom({ - studyUid, - seriesUid, - sopUid: newUid(), - instanceNumber: 99, - imageOrientationPatient: ORIENTATION, - imagePositionPatient: null, - sliceThickness: SLICE_SPACING, - }) - ); -} +const POSITIONLESS = path.join(TEMP_DIR, DIR_NAME, 'positionless.dcm'); describe('Incremental import of a slice with no readable position', () => { before(async () => { - const resources = writeSeries(); - writePositionlessSlice(); + const uids = { studyUid: newUid(), seriesUid: newUid() }; + const resources = writeAcquisitions(DIR_NAME, uids, ACQUISITIONS); + // Same series and same hard facts as the passes, so only its unreadable + // geometry can keep it out of them. + fs.writeFileSync( + POSITIONLESS, + buildSyntheticDicom({ + ...uids, + sopUid: newUid(), + instanceNumber: 99, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: null, + sliceThickness: 2.5, + }) + ); await writeManifestToFile({ resources }, MANIFEST_NAME); }); - it('keeps both acquisitions and warns about the slice it cannot place', async () => { + it('keeps every acquisition and warns about the slice it cannot place', async () => { await volViewPage.open(`?urls=[tmp/${MANIFEST_NAME}]`); await volViewPage.waitForViews(); + // One card per acquisition, each holding only that acquisition's slices. const passes = ACQUISITIONS.map((a) => a.sliceCount).sort((a, b) => a - b); await volViewPage.waitForVolumeCardSliceCounts(passes); expect(await volViewPage.getNotificationsCount()).toEqual(0); - await dropFiles([path.join(dir(), POSITIONLESS_NAME)]); + await dropFiles([POSITIONLESS]); - // The two passes are untouched, and the unplaceable slice is a volume of - // its own rather than a member of either. + // The passes are untouched, and the unplaceable slice is a volume of its + // own rather than a member of any. await volViewPage.waitForVolumeCardSliceCounts([1, ...passes]); await volViewPage.waitForNotification(); - - // The toast of that same warning covers the notifications button. - await browser.waitUntil( - async () => (await $$('.Vue-Toastification__toast').length) === 0, - { timeoutMsg: 'expected the warning toast to close' } - ); - - await volViewPage.notifications.click(); + await volViewPage.openNotifications(); const dialog = await $('.message-center'); await dialog.waitForDisplayed(); expect(await dialog.getText()).toContain( diff --git a/tests/specs/multi-acquisition-series.e2e.ts b/tests/specs/multi-acquisition-series.e2e.ts deleted file mode 100644 index f299ca446..000000000 --- a/tests/specs/multi-acquisition-series.e2e.ts +++ /dev/null @@ -1,78 +0,0 @@ -// One DICOM series carrying several overlapping acquisitions must load as one -// volume per acquisition, not as a single stack of interleaved slices. -// -// Modelled on IDC series -// 1.3.6.1.4.1.14519.5.2.1.3098.5025.295130953269492004748715270821, which -// holds three 2.5mm chest/abdomen passes offset from each other by fractions -// of a slice. Synthetic DICOMs are generated on the fly so the test carries -// no binary fixtures. -import * as path from 'path'; -import * as fs from 'fs'; -import { volViewPage } from '../pageobjects/volview.page'; -import { TEMP_DIR } from '../../wdio.shared.conf'; -import { writeManifestToFile } from './utils'; -import { buildSyntheticDicom, newUid } from './syntheticDicom'; - -const SLICE_SPACING = 2.5; - -// Each pass is uniform on its own; the sub-slice offsets are what make the -// merged stack irregular. Slice counts differ so each volume card is -// identifiable by its label alone. -const ACQUISITIONS = [ - { number: 1, firstSliceZ: 0, sliceCount: 5 }, - { number: 2, firstSliceZ: 0.75, sliceCount: 6 }, - { number: 3, firstSliceZ: 1.75, sliceCount: 4 }, -]; - -const DIR_NAME = 'multi-acquisition-series'; -const MANIFEST_NAME = 'multi-acquisition-series.json'; - -async function writeSeries() { - const studyUid = newUid(); - const seriesUid = newUid(); - const dir = path.join(TEMP_DIR, DIR_NAME); - fs.mkdirSync(dir, { recursive: true }); - - let instanceNumber = 0; - const resources = ACQUISITIONS.flatMap( - ({ number, firstSliceZ, sliceCount }) => - Array.from({ length: sliceCount }, (_, i) => { - instanceNumber += 1; - const filename = `acq${number}-slice${i}.dcm`; - fs.writeFileSync( - path.join(dir, filename), - buildSyntheticDicom({ - studyUid, - seriesUid, - sopUid: newUid(), - instanceNumber, - acquisitionNumber: number, - imageOrientationPatient: [1, 0, 0, 0, 1, 0], - imagePositionPatient: [0, 0, firstSliceZ + i * SLICE_SPACING], - sliceThickness: SLICE_SPACING, - }) - ); - return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; - }) - ); - - await writeManifestToFile({ resources }, MANIFEST_NAME); -} - -describe('Multi-acquisition series: one series holding three overlapping scans', () => { - before(async () => { - await writeSeries(); - }); - - it('loads one volume per acquisition instead of one interleaved stack', async () => { - await volViewPage.open(`?urls=[tmp/${MANIFEST_NAME}]`); - await volViewPage.waitForViews(); - - const expected = ACQUISITIONS.map((a) => a.sliceCount).sort( - (a, b) => a - b - ); - - // One card per acquisition, each holding only that acquisition's slices. - await volViewPage.waitForVolumeCardSliceCounts(expected); - }); -}); diff --git a/tests/specs/pet-ct-sample.e2e.ts b/tests/specs/pet-ct-sample.e2e.ts index 8be49d489..ed35d82c1 100644 --- a/tests/specs/pet-ct-sample.e2e.ts +++ b/tests/specs/pet-ct-sample.e2e.ts @@ -1,7 +1,6 @@ import * as path from 'path'; import { readFileSync, writeFileSync } from 'node:fs'; import dcmjs from 'dcmjs'; -import { getDatasetTag, readDicomDataset } from '@/packages/dicom/core'; import { TEMP_DIR } from '@/wdio.shared.conf'; import { PET_CT_DICOM_DATASETS } from '../datasets'; import { setValueVueInput, volViewPage } from '../pageobjects/volview.page'; @@ -309,11 +308,10 @@ describe('PET/CT sample', () => { const ctFile = PET_CT_DICOM_DATASETS.find(({ name }) => name.startsWith('PET-CT-CT-') )!; - const dataset = readDicomDataset( - new Uint8Array(readFileSync(path.join(TEMP_DIR, ctFile.name))) + const { dict } = dcmjs.data.DicomMessage.readFile( + Uint8Array.from(readFileSync(path.join(TEMP_DIR, ctFile.name))).buffer ); - const firstValue = (tag: string) => - Number(getDatasetTag(dataset, tag)!.split('\\')[0]); + const firstValue = (tag: string) => Number(dict[tag]!.Value[0]); const width = firstValue('00281051'); const level = firstValue('00281050'); expect(width).toBeGreaterThan(0); diff --git a/tests/specs/sample-rendering.e2e.ts b/tests/specs/sample-rendering.e2e.ts index 1020854e7..ac6b8fbb7 100644 --- a/tests/specs/sample-rendering.e2e.ts +++ b/tests/specs/sample-rendering.e2e.ts @@ -1,7 +1,6 @@ import AppPage from '../pageobjects/volview.page'; import { PROSTATEX_DATASET } from '../datasets'; import { useCachedSample } from './utils'; -import { DOWNLOAD_TIMEOUT } from '../../wdio.shared.conf'; const THRESHOLD = 12; // percent - handle pixel jitter in 3D view const RENDER_STABLE_TIMEOUT = 5000; @@ -13,26 +12,8 @@ describe('VolView', () => { await AppPage.open(); await AppPage.downloadProstateSample(); - await browser.waitUntil( - async () => - browser.execute(() => { - const canvases = document.querySelectorAll( - '.layout-container [data-testid~="vtk-view"] canvas' - ); - return ( - canvases.length === 4 && - Array.from(canvases).every((element) => { - const canvas = element as HTMLCanvasElement; - return canvas.width > 10 && canvas.height > 10; - }) && - !document.querySelector('.layout-container .loading-indicator') - ); - }), - { - timeout: DOWNLOAD_TIMEOUT, - timeoutMsg: 'Expected all sample views to finish loading', - } - ); + await AppPage.waitForViewCounts(3, true); + await AppPage.waitForViewsLoaded(); const layoutContainer = await $('.layout-container'); diff --git a/tests/specs/session-overlapping-imports.e2e.ts b/tests/specs/session-overlapping-imports.e2e.ts index e0080eb48..70af88e75 100644 --- a/tests/specs/session-overlapping-imports.e2e.ts +++ b/tests/specs/session-overlapping-imports.e2e.ts @@ -10,19 +10,16 @@ // Synthetic DICOMs are generated on the fly so the test carries no binary // fixtures. import * as path from 'path'; -import * as fs from 'fs'; import { volViewPage } from '../pageobjects/volview.page'; import { TEMP_DIR } from '../../wdio.shared.conf'; import { SESSION_SAVE_TIMEOUT, dropFiles, waitForFileExists, + writeAcquisitions, writeManifestToFile, } from './utils'; -import { buildSyntheticDicom, newUid } from './syntheticDicom'; - -const SLICE_SPACING = 2.5; -const ORIENTATION = [1, 0, 0, 0, 1, 0] as const; +import { newUid } from './syntheticDicom'; // Offset by half a slice, so the two passes overlap and the planner separates // them. Slice counts differ so each volume card is identifiable by its label. @@ -32,36 +29,6 @@ const SECOND_PASS = { number: 2, firstSliceZ: 1.25, sliceCount: 6 }; const DIR_NAME = 'session-overlapping-imports'; const MANIFEST_NAME = 'session-overlapping-imports.json'; -const seriesUid = newUid(); -const studyUid = newUid(); - -const dir = () => path.join(TEMP_DIR, DIR_NAME); - -type Pass = typeof FIRST_PASS; - -function writePass({ number, firstSliceZ, sliceCount }: Pass) { - fs.mkdirSync(dir(), { recursive: true }); - - return Array.from({ length: sliceCount }, (_, i) => { - const filename = `acq${number}-slice${i}.dcm`; - fs.writeFileSync( - path.join(dir(), filename), - buildSyntheticDicom({ - studyUid, - seriesUid, - sopUid: newUid(), - // Unique across both passes, so no instance looks like a re-send. - instanceNumber: number * 100 + i, - acquisitionNumber: number, - imageOrientationPatient: ORIENTATION, - imagePositionPatient: [0, 0, firstSliceZ + i * SLICE_SPACING], - sliceThickness: SLICE_SPACING, - }) - ); - return { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; - }); -} - const saveSession = async () => { const fileName = await volViewPage.saveSession(); await waitForFileExists(path.join(TEMP_DIR, fileName), SESSION_SAVE_TIMEOUT); @@ -77,8 +44,11 @@ describe('Session saved after an incremental import of one series', () => { let secondPassFiles: string[]; before(async () => { - const resources = writePass(FIRST_PASS); - secondPassFiles = writePass(SECOND_PASS).map(({ name }) => name); + const uids = { studyUid: newUid(), seriesUid: newUid() }; + const resources = writeAcquisitions(DIR_NAME, uids, [FIRST_PASS]); + secondPassFiles = writeAcquisitions(DIR_NAME, uids, [SECOND_PASS]).map( + ({ name }) => path.join(TEMP_DIR, DIR_NAME, name) + ); await writeManifestToFile({ resources }, MANIFEST_NAME); }); @@ -88,18 +58,16 @@ describe('Session saved after an incremental import of one series', () => { await volViewPage.waitForVolumeCardSliceCounts([FIRST_PASS.sliceCount]); // The regroup this triggers replaces the volume the first import earned. - await dropFiles(secondPassFiles.map((name) => path.join(dir(), name))); - const bothPasses = [FIRST_PASS.sliceCount, SECOND_PASS.sliceCount].sort( - (a, b) => a - b - ); + await dropFiles(secondPassFiles); + const bothPasses = [FIRST_PASS.sliceCount, SECOND_PASS.sliceCount]; await volViewPage.waitForVolumeCardSliceCounts(bothPasses); const withBoth = await saveSession(); await openSavedSession(withBoth); await volViewPage.waitForVolumeCardSliceCounts(bothPasses); - await volViewPage.deleteVolumeCard(0); - const survivor = bothPasses.slice(1); + await volViewPage.deleteVolumeCard(FIRST_PASS.sliceCount); + const survivor = [SECOND_PASS.sliceCount]; await volViewPage.waitForVolumeCardSliceCounts(survivor); const withSurvivor = await saveSession(); diff --git a/tests/specs/syntheticDicom.ts b/tests/specs/syntheticDicom.ts index a41596f35..8d39b677e 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -276,12 +276,7 @@ const rgbFrame = (samples: readonly number[], count: number, bits: number) => { // A single-item sequence with an explicit item length, so a reader that skips // sequences and one that descends into them both stay in step. const sequenceOfOneItem = (g: number, e: number, item: Uint8Array) => - elemLong( - g, - e, - 'SQ', - combine(tagBytes(0xfffe, 0xe000), writeLong(item.length), item) - ); + elemLong(g, e, 'SQ', sequenceItem(item)); export type SyntheticSliceOptions = { studyUid: string; @@ -507,10 +502,6 @@ export const stripFileMeta = (bytes: Uint8Array) => { return meta.slice(12 + bodyLength); }; -/** One item of an encapsulated Pixel Data value, written with the length given. */ -export const pixelItem = (bytes: Uint8Array) => - combine(tagBytes(ITEM_GROUP, ITEM_TAG), writeLong(bytes.length), bytes); - export type EncapsulatedFrames = { /** Each frame's fragments, in order. */ frames: readonly (readonly Uint8Array[])[]; @@ -523,7 +514,9 @@ export function encapsulatedPixelData({ frames, offsetTable = false, }: EncapsulatedFrames) { - const items = frames.map((fragments) => combine(...fragments.map(pixelItem))); + const items = frames.map((fragments) => + combine(...fragments.map(sequenceItem)) + ); const starts = items.reduce( (offsets, _, index) => index === 0 @@ -535,7 +528,7 @@ export function encapsulatedPixelData({ ? combine(...starts.map(writeLong)) : new Uint8Array(); return combine( - pixelItem(table), + sequenceItem(table), ...items, tagBytes(ITEM_GROUP, SEQUENCE_DELIMITER_TAG), writeLong(0) diff --git a/tests/specs/utils.ts b/tests/specs/utils.ts index 2ee03a8d4..82e4d85eb 100644 --- a/tests/specs/utils.ts +++ b/tests/specs/utils.ts @@ -6,6 +6,7 @@ import { PNG } from 'pngjs'; import { TEMP_DIR } from '../../wdio.shared.conf'; import { volViewPage } from '../pageobjects/volview.page'; import type { TestDataset } from '../datasets'; +import { buildSyntheticDicom, newUid } from './syntheticDicom'; export async function captureViewPixels( selector: string, @@ -333,6 +334,60 @@ export async function dropFiles(filePaths: string[]) { expect(dropped).toBe(true); } +/** Opens the Image spacing dialog of the first volume card. */ +export async function openSpacingDetails() { + await $('.volume-card [data-testid="dataset-menu-button"]').click(); + const item = $('[data-testid="dataset-menu-spacing-item"]'); + await item.waitForDisplayed(); + await item.waitForStable(); + await item.waitForClickable(); + await item.click(); + await $('[data-testid="image-spacing-details"]').waitForDisplayed(); +} + +const ACQUISITION_SLICE_SPACING = 2.5; + +export type AcquisitionPass = { + number: number; + firstSliceZ: number; + sliceCount: number; +}; + +/** + * Writes acquisitions of one series as axial 2.5 mm stacks and returns their + * manifest resources. Instance numbers are unique across passes, so no + * instance looks like a re-send. + */ +export function writeAcquisitions( + dirName: string, + uids: { studyUid: string; seriesUid: string }, + passes: AcquisitionPass[] +) { + const dir = makeTempDir(dirName); + return passes.flatMap(({ number, firstSliceZ, sliceCount }) => + Array.from({ length: sliceCount }, (_, i) => { + const name = `acq${number}-slice${i}.dcm`; + fs.writeFileSync( + path.join(dir, name), + buildSyntheticDicom({ + ...uids, + sopUid: newUid(), + instanceNumber: number * 100 + i, + acquisitionNumber: number, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [ + 0, + 0, + firstSliceZ + i * ACQUISITION_SLICE_SPACING, + ], + sliceThickness: ACQUISITION_SLICE_SPACING, + }) + ); + return { url: `tmp/${dirName}/${name}`, name }; + }) + ); +} + /** Loads a file into the page already open, through the Open files dialog. */ export async function openThroughDialog( filePath: string, diff --git a/tests/unit/octFixture.ts b/tests/unit/octFixture.ts index 40ca29f84..4beddbc98 100644 --- a/tests/unit/octFixture.ts +++ b/tests/unit/octFixture.ts @@ -5,7 +5,6 @@ import { getDatasetTag, readInstance, type Instance, - type InstanceCollectionUpdate, type WholeInstanceDecode, } from '@/packages/dicom/core'; import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; @@ -22,17 +21,24 @@ export const readFixtureInstance = (file: Blob) => readInstance(fromBlob(file), new AbortController().signal); /** - * Allocates these instances in the given order as one volume. Fixtures keep - * deliberate groups, so geometry is judged by allocation, not by the planner. + * Allocates these instances as one volume. A group the planner would split + * sits on no lattice, so it is allocated in the given order as an irregular + * stack. */ export function volumeOf(instances: Instance[]) { - // The first member planned alone gives the validated orientation. - const { orientation } = plannedUpdate([instances[0]]).collection; + const update = plannedUpdate(instances); + if (update.members.length === instances.length) return allocateVolume(update); return allocateVolume({ kind: 'image', - id: 'fixture', members: instances, - collection: { orientation } as InstanceCollectionUpdate['collection'], + collection: { + ...plannedUpdate([instances[0]]).collection, + reconstruction: { + kind: 'irregular', + reason: 'unreadable-geometry', + sliceSpacing: null, + }, + }, }); } diff --git a/tsconfig.json b/tsconfig.json index c7a479f9d..5d191773a 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -24,9 +24,17 @@ "@wdio/visual-service" ], "paths": { - "@/*": ["./*"] + "@/*": [ + "./*" + ] }, - "lib": ["esnext", "dom", "dom.iterable", "scripthost", "WebWorker"] + "lib": [ + "esnext", + "dom", + "dom.iterable", + "scripthost", + "WebWorker" + ] }, "include": [ "src/**/*.ts", @@ -38,7 +46,9 @@ "tests/**/*.tsx", "packages/dicom/**/*.ts" ], - "exclude": ["node_modules"], + "exclude": [ + "node_modules" + ], "ts-node": { "esm": true, "experimentalSpecifierResolution": "node" diff --git a/vite.config.ts b/vite.config.ts index 64a6423cf..1a1c0a526 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -282,9 +282,6 @@ export default defineConfig({ environment: 'happy-dom', // canvas support. See: https://github.com/vitest-dev/vitest/issues/740 maxWorkers: 1, - // A store that outlives an import must not pin its chunks, which only a - // collection proves. - execArgv: ['--expose-gc'], server: { deps: { inline: ['vuetify'], From fadf4a31ef4f26deef9cf4b05962c2935bc759d2 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 15 Nov 2026 04:34:03 -0500 Subject: [PATCH 07/32] chore(checks): hold the DICOM module to the quality limits The module carries no complexity debt, so lint now fails on any function in packages/dicom that exceeds the complexity, depth, parameter or line limits, where src only warns and relies on the per-commit ratchet. Both read the limits from scripts/checks/config.mjs. The duplication ratchet covers the module's source as well as tests, so a new 60-token clone there fails the commit. --- eslint.config.js | 34 +++++++++++++++++++++------------- scripts/checks/duplication.mjs | 26 ++++++++++++++------------ 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index fb460209d..f4c0f0057 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -4,6 +4,17 @@ import eslintPluginVue from 'eslint-plugin-vue'; import tseslint from 'typescript-eslint'; import eslintConfigPrettier from 'eslint-config-prettier'; import globals from 'globals'; +import { limits } from './scripts/checks/config.mjs'; + +const limitRules = (level) => ({ + complexity: [level, limits.complexity], + 'max-depth': [level, limits['max-depth']], + 'max-params': [level, limits['max-params']], + 'max-lines': [ + level, + { max: limits['max-lines'], skipBlankLines: true, skipComments: true }, + ], +}); // --------------------------------------------------------------------------- // Feature layering boundaries. @@ -387,27 +398,24 @@ export default tseslint.config( ], }, }, - // Mirrors the limits scripts/checks/complexity.mjs enforces per commit. Warn - // level because the ratchet only fails a file whose debt grows, so existing + // The limits scripts/checks/complexity.mjs enforces per commit. Warn level + // in src because the ratchet only fails a file whose debt grows, so existing // files stay over these numbers without failing `npm run lint`. { - files: ['src/**/*.{js,ts,vue}', 'packages/dicom/**/*.{js,ts}'], + files: ['src/**/*.{js,ts,vue}'], ignores: [ - 'packages/dicom/**/__tests__/**', 'src/**/__tests__/**', 'src/**/*.{spec,test}.{js,ts}', 'src/**/*.d.ts', '**/emscripten-build/**', ], - rules: { - complexity: ['warn', 10], - 'max-depth': ['warn', 3], - 'max-params': ['warn', 4], - 'max-lines': [ - 'warn', - { max: 600, skipBlankLines: true, skipComments: true }, - ], - }, + rules: limitRules('warn'), + }, + // The DICOM module carries no debt, so it is held to the limits outright. + { + files: ['packages/dicom/**/*.{js,ts}'], + ignores: ['packages/dicom/**/__tests__/**'], + rules: limitRules('error'), }, { files: ['tests/**/*.{js,ts,mjs}'], diff --git a/scripts/checks/duplication.mjs b/scripts/checks/duplication.mjs index cd5835261..490d9458f 100755 --- a/scripts/checks/duplication.mjs +++ b/scripts/checks/duplication.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node -// Test duplication ratchet: the staged tests may not introduce a clone that -// did not already exist at the base ref. +// Duplication ratchet: the staged tests and DICOM module may not introduce a +// clone that did not already exist at the base ref. // // duplication.mjs --base main compares the index with merge-base(main, HEAD). import { execFileSync } from 'node:child_process'; @@ -11,16 +11,18 @@ import { createRequire } from 'node:module'; import { git, materialize, paths, stagedContext } from './git.mjs'; import { minCloneTokens as MIN_TOKENS } from './config.mjs'; -const TEST = /(__tests__\/.*|\.(spec|test)|^tests\/.*)\.[cm]?[jt]sx?$/; +// The DICOM module's source is in scope as well as tests, since it has no clones. +const SCOPE = + /(__tests__\/.*|\.(spec|test)|^tests\/.*|^packages\/dicom\/.*)\.[cm]?[jt]sx?$/; const { base, baseRef, changed: entries, worktree } = stagedContext(); -const changed = entries.filter(({ file }) => TEST.test(file)); +const changed = entries.filter(({ file }) => SCOPE.test(file)); if (changed.length === 0) process.exit(0); const ts = createRequire(path.join(worktree, 'package.json'))('typescript'); -const indexTests = paths(git('ls-files', '-z')).filter((f) => TEST.test(f)); -const baseTests = paths(git('ls-tree', '-rz', '--name-only', base)).filter( - (f) => TEST.test(f) +const indexFiles = paths(git('ls-files', '-z')).filter((f) => SCOPE.test(f)); +const baseFiles = paths(git('ls-tree', '-rz', '--name-only', base)).filter( + (f) => SCOPE.test(f) ); const withoutImports = (file, text) => { @@ -73,18 +75,18 @@ try { materialize( candRoot, - indexTests.map((f) => [flatten(f), withoutImports(f, git('show', `:${f}`))]) + indexFiles.map((f) => [flatten(f), withoutImports(f, git('show', `:${f}`))]) ); materialize( baseRoot, - baseTests.map((f) => [ + baseFiles.map((f) => [ flatten(f), withoutImports(f, git('show', `${base}:${f}`)), ]) ); // Fingerprints are content-derived, so a baseline taken from the base tree - // identifies exactly the clones the staged tests add. + // identifies exactly the clones the staged files add. run(baseRoot, ['--baseline', baseline, '--update-baseline', '-r', 'silent']); run(candRoot, ['--baseline', baseline, '-r', 'json', '-o', report]); @@ -95,7 +97,7 @@ try { if (added.length > 0) { console.error( - '\nTest duplication ratchet: these clones are new since %s.\n', + '\nDuplication ratchet: these clones are new since %s.\n', baseRef ); added.forEach(({ firstFile, secondFile, tokens }) => { @@ -106,7 +108,7 @@ try { ); }); console.error( - `\nA clone is ${MIN_TOKENS}+ identical tokens. Pull the shared setup into a helper the existing specs already use.` + + `\nA clone is ${MIN_TOKENS}+ identical tokens. Pull the shared code into one helper both places use.` + `\nBypass additional checks for one commit with CHECKS_SKIP=1.\n` ); process.exitCode = 1; From 68077b1dd8865f1bddfe063076ce4d3d48315631 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 15 Nov 2026 04:34:05 -0500 Subject: [PATCH 08/32] refactor(dicom): tidy the loading module Shorten code that said in many lines what a few say clearly, drop exports, parameters, casts and annotations nothing needs, and give the repeated shapes in pixel formats and validation one name each. The HTTP status constants live where they are used, and the Content-Range parser no longer models a range the only caller rejects. The test DICOM writers share one element encoder, one Part 10 assembler and the sequence, decimal and long helpers; every generated byte is unchanged. Specs share their repeated setup through helpers, and cases that restated another case are gone. restoreState takes the reports it shows the user as one object, which brings it within the parameter limit. --- .../__tests__/assignCollectionIds.spec.ts | 27 +- .../__tests__/instanceFacts.spec.ts | 30 +- .../__tests__/instanceRegistry.spec.ts | 3 +- .../__tests__/multiframeGeometry.spec.ts | 6 +- .../__tests__/planDicomCollections.spec.ts | 41 +-- .../collections/__tests__/sliceFixture.ts | 27 +- packages/dicom/core/collections/groupBy.ts | 4 +- .../dicom/core/collections/instanceFacts.ts | 16 +- .../core/collections/instanceRegistry.ts | 13 +- .../core/collections/planDicomCollections.ts | 9 +- .../core/collections/reconstructVolume.ts | 8 +- .../splitOverlappingAcquisitions.ts | 50 +-- packages/dicom/core/header/byteDeque.ts | 63 +--- packages/dicom/core/header/dicomParser.ts | 133 +++---- packages/dicom/core/header/readDicomHeader.ts | 6 +- .../dicom/core/header/streamingByteReader.ts | 32 +- packages/dicom/core/index.ts | 6 +- .../__tests__/readInstanceSources.spec.ts | 28 +- .../metadata/__tests__/dcmjsParser.spec.ts | 26 +- .../metadata/__tests__/dicomDataset.spec.ts | 62 ++-- packages/dicom/core/metadata/datasetAccess.ts | 3 +- packages/dicom/core/metadata/dcmjs.d.ts | 18 +- packages/dicom/core/metadata/dcmjsParser.ts | 78 ++--- packages/dicom/core/metadata/dicomDataset.ts | 6 +- packages/dicom/core/metadata/dicomTags.ts | 109 +++--- .../dicom/core/metadata/functionalGroups.ts | 3 +- .../dicom/core/metadata/ultrasoundRegion.ts | 7 +- .../dicom/core/pixels/encapsulatedFrames.ts | 21 +- .../runtime/__tests__/requestPool.spec.ts | 21 +- packages/dicom/core/runtime/requestPool.ts | 1 + .../core/source/__tests__/byteSource.spec.ts | 114 +++--- .../__tests__/parseContentRangeHeader.spec.ts | 56 +-- packages/dicom/core/source/byteSource.ts | 9 +- packages/dicom/core/source/httpCodes.ts | 3 - .../core/source/parseContentRangeHeader.ts | 18 +- packages/dicom/core/utils.ts | 25 +- .../volume/__tests__/allocateVolume.spec.ts | 4 +- .../volume/__tests__/frameGeometry.spec.ts | 3 +- .../core/volume/__tests__/loadFrames.spec.ts | 16 +- .../volume/__tests__/volumeLayout.spec.ts | 19 +- packages/dicom/core/volume/allocateVolume.ts | 9 +- packages/dicom/core/volume/loadVolume.ts | 14 +- packages/dicom/core/volume/nmGeometry.ts | 4 +- packages/dicom/core/volume/pixelFormat.ts | 44 +-- packages/dicom/core/volume/pixelValidation.ts | 20 +- .../dicom/vtk/__tests__/thumbnail.spec.ts | 14 - .../dicom/vtk/__tests__/volumeImage.spec.ts | 33 +- packages/dicom/vtk/thumbnail.ts | 2 +- src/components/ImageSpacingDetails.vue | 6 +- src/components/PatientStudyVolumeBrowser.vue | 20 +- src/core/cine/DicomCineImage.ts | 34 +- .../cine/__tests__/DicomCineImage.spec.ts | 51 ++- src/core/cine/__tests__/cineInstance.spec.ts | 2 +- src/core/cine/cineInstance.ts | 3 +- .../__tests__/dicomVolumeImage.spec.ts | 24 +- src/core/streaming/cachedStreamFetcher.ts | 7 +- src/core/streaming/dicom/octMetadata.ts | 28 +- src/core/streaming/dicomVolumeImage.ts | 17 +- src/core/streaming/httpCodes.ts | 7 - src/enface/availability.ts | 12 +- src/io/dicom.ts | 26 +- .../importDicomInstanceSources.spec.ts | 15 +- .../__tests__/missingArchiveMember.spec.ts | 6 +- .../__tests__/restoreCoveredErrors.spec.ts | 6 +- .../__tests__/restoreStateFileLeaves.spec.ts | 61 ++-- .../import/__tests__/stateFileLeaves.spec.ts | 58 +--- src/io/import/importDataSources.ts | 16 +- .../processors/__tests__/handleDicom.spec.ts | 4 +- src/io/import/processors/handleDicom.ts | 10 +- src/io/import/processors/restoreStateFile.ts | 16 +- .../datasets-dicom-acquisition-split.spec.ts | 14 +- .../__tests__/datasets-dicom-cine.spec.ts | 8 +- .../__tests__/datasets-dicom-reimport.spec.ts | 4 +- src/store/__tests__/dicomImportFixtures.ts | 20 +- .../__tests__/duplicateDatasetSave.spec.ts | 98 ++---- src/store/datasets-dicom.ts | 5 +- .../fixtures/dicom-pages/enhancedFixtures.ts | 37 +- tests/fixtures/oct/dicom.ts | 23 +- tests/nativePixelDicom.ts | 70 ++-- tests/pageobjects/volview.page.ts | 22 +- tests/specs/dicom-import-regressions.e2e.ts | 6 - tests/specs/dicom-japanese-name.e2e.ts | 3 +- tests/specs/dicom-module-pages.e2e.ts | 13 +- tests/specs/dicom-native-parity.e2e.ts | 33 +- tests/specs/dicom-spacing-details.e2e.ts | 2 - tests/specs/dicom-volume-composition.e2e.ts | 1 - tests/specs/dicomElementFixtures.ts | 2 +- tests/specs/dicomRenderedSlice.ts | 20 +- tests/specs/imageCacheUtils.ts | 2 +- .../incremental-positionless-import.e2e.ts | 3 - tests/specs/octTestUtils.ts | 3 +- tests/specs/pet-ct-sample.e2e.ts | 83 ++--- .../specs/session-overlapping-imports.e2e.ts | 3 - tests/specs/syntheticDicom.ts | 327 ++++++++---------- tests/specs/utils.ts | 2 +- 95 files changed, 953 insertions(+), 1544 deletions(-) delete mode 100644 packages/dicom/core/source/httpCodes.ts delete mode 100644 src/core/streaming/httpCodes.ts diff --git a/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts b/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts index a85ae6f7a..78450f8d4 100644 --- a/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts +++ b/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts @@ -1,6 +1,5 @@ import { describe, it, expect } from 'vitest'; import { assignIds, encodeCollectionKey } from '../assignCollectionIds'; -import type { CommittedCollection } from '../assignCollectionIds'; import { ORIENTATION_TOLERANCE } from '../orientation'; import { planDicomCollections } from '../planDicomCollections'; import type { CollectionKey, DicomCollection } from '../planDicomCollections'; @@ -92,9 +91,7 @@ describe('assignIds', () => { it('keeps the committed id when key and members are unchanged', () => { const collection = collectionOf(['a', 'b']); - const committed: CommittedCollection[] = [ - { id: 'visible-1', sopInstanceUids: ['a', 'b'] }, - ]; + const committed = [{ id: 'visible-1', sopInstanceUids: ['a', 'b'] }]; const collections = assignIds([collection], committed); @@ -148,7 +145,7 @@ describe('assignIds', () => { it('gives a committed id to the collection holding most of its members', () => { const majority = collectionOf(['a', 'b', 'c'], keyOf('1,0,0,0,1,0')); const remainder = collectionOf(['d'], keyOf('0,1,0,0,0,1')); - const committed: CommittedCollection[] = [ + const committed = [ { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, ]; @@ -161,7 +158,7 @@ describe('assignIds', () => { it('mints for both halves of an evenly split committed collection', () => { const left = collectionOf(['a', 'b'], keyOf('1,0,0,0,1,0')); const right = collectionOf(['c', 'd'], keyOf('0,1,0,0,0,1')); - const committed: CommittedCollection[] = [ + const committed = [ { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, ]; @@ -173,9 +170,7 @@ describe('assignIds', () => { it('mints when nothing overlaps, without reusing a committed id', () => { const collection = collectionOf(['a']); - const committed: CommittedCollection[] = [ - { id: 'visible-1', sopInstanceUids: ['x', 'y'] }, - ]; + const committed = [{ id: 'visible-1', sopInstanceUids: ['x', 'y'] }]; const collections = assignIds([collection], committed); @@ -185,7 +180,7 @@ describe('assignIds', () => { it('never mints an id already taken by a committed collection', () => { const collection = collectionOf(['a']); - const committed: CommittedCollection[] = [ + const committed = [ { id: encodeCollectionKey(collection.key), sopInstanceUids: ['x'], @@ -199,7 +194,7 @@ describe('assignIds', () => { it('prefers the committed collection it overlaps most', () => { const collection = collectionOf(['a', 'b', 'c', 'd', 'e']); - const committed: CommittedCollection[] = [ + const committed = [ { id: 'small', sopInstanceUids: ['a', 'b'] }, { id: 'large', sopInstanceUids: ['c', 'd', 'e'] }, ]; @@ -211,7 +206,7 @@ describe('assignIds', () => { it('breaks an equal overlap on the smallest committed id', () => { const collection = collectionOf(['a', 'b', 'c', 'd']); - const committed: CommittedCollection[] = [ + const committed = [ { id: 'zeta', sopInstanceUids: ['a', 'b'] }, { id: 'alpha', sopInstanceUids: ['c', 'd'] }, ]; @@ -223,9 +218,7 @@ describe('assignIds', () => { it('measures overlap only on members that have a SOP Instance UID', () => { const collection = collectionOf([null, 'a']); - const committed: CommittedCollection[] = [ - { id: 'visible-1', sopInstanceUids: ['a'] }, - ]; + const committed = [{ id: 'visible-1', sopInstanceUids: ['a'] }]; const collections = assignIds([collection], committed); @@ -234,9 +227,7 @@ describe('assignIds', () => { it('mints for a collection whose members all lack a SOP Instance UID', () => { const collection = collectionOf([null, null]); - const committed: CommittedCollection[] = [ - { id: 'visible-1', sopInstanceUids: ['a'] }, - ]; + const committed = [{ id: 'visible-1', sopInstanceUids: ['a'] }]; const collections = assignIds([collection], committed); diff --git a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts index bb0c07f79..914911ba1 100644 --- a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts @@ -231,16 +231,6 @@ describe('instance facts', () => { expect(facts.projectedPosition).toBeCloseTo(30, 3); }); - it.each([ - ['zero', '0\\0.5'], - ['negative', '-1\\0.5'], - ['blank', '\\0.5'], - ])('reads a %s pixel spacing as unknown', (_case, value) => { - expect( - factsOf(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing - ).toBeNull(); - }); - it('projects the position onto the slice normal, not onto z', () => { // Rows run along +y and columns along +z, so the normal is +x. const facts = factsOf( @@ -258,13 +248,12 @@ describe('instance facts', () => { }); it.each([ - ['a missing tag', without(Tags.PixelSpacing), null], - ['a single value', metadata({ [Tags.PixelSpacing]: '0.5' }), null], - [ - 'a non numeric value', - metadata({ [Tags.PixelSpacing]: '0.5\\bad' }), - null, - ], + ['a missing tag', without(Tags.PixelSpacing)], + ['a single value', metadata({ [Tags.PixelSpacing]: '0.5' })], + ['a non numeric value', metadata({ [Tags.PixelSpacing]: '0.5\\bad' })], + ['a zero value', metadata({ [Tags.PixelSpacing]: '0\\0.5' })], + ['a negative value', metadata({ [Tags.PixelSpacing]: '-1\\0.5' })], + ['a blank value', metadata({ [Tags.PixelSpacing]: '\\0.5' })], ])('reads a pixel spacing with %s as unknown', (_case, entries) => { expect(factsOf(entries).pixelSpacing).toBeNull(); }); @@ -344,11 +333,8 @@ describe('single-frame and spacing normalization', () => { 'defaults NumberOfFrames %s to one', (frames) => { expect( - readInstanceDetails( - datasetFromTags( - frames === undefined ? [] : [[Tags.NumberOfFrames, frames]] - ) - ).facts.numberOfFrames + factsOf(frames === undefined ? [] : [[Tags.NumberOfFrames, frames]]) + .numberOfFrames ).toBe('1'); } ); diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts index 3b06558c9..eaacd8d34 100644 --- a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -7,7 +7,6 @@ import { emptyRegistry, forgetCollection, registerInstances, - type RegistryState, } from '../instanceRegistry'; import { UNREADABLE_POSITION_WARNING } from '../planDicomCollections'; import { mergingInstances, tilt } from '@/tests/dicomOrientationFixtures'; @@ -428,7 +427,7 @@ describe('pure instance registry', () => { it('drops an emptied series from the state', () => { const only = slice(); const { state, updates } = registerInstances(emptyRegistry, [only]); - const forgotten: RegistryState = forgetCollection(state, updates[0].id); + const forgotten = forgetCollection(state, updates[0].id); expect(forgotten.size).toBe(0); }); }); diff --git a/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts b/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts index f64748a9b..4f783ad69 100644 --- a/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts +++ b/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts @@ -18,9 +18,9 @@ import { tags, } from '../../volume/__tests__/enhancedFixture'; -const collectionOf = (metadata: DicomDataset, seriesKey = 'frames') => +const collectionOf = (metadata: DicomDataset) => planDicomCollections({ - seriesKey, + seriesKey: 'frames', instances: [readInstanceDetails(metadata).facts], })[0]; @@ -94,6 +94,6 @@ describe('multiframe geometry', () => { [0, 1, 0, 1].map((z) => positioned(`0\\0\\${z}`)), { '00080060': 'SEG' } ); - expect(collectionOf(metadata, 'seg').warnings).toEqual([]); + expect(collectionOf(metadata).warnings).toEqual([]); }); }); diff --git a/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts b/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts index e037764a6..469940743 100644 --- a/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts +++ b/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts @@ -142,22 +142,12 @@ describe('planDicomCollections', () => { }); it('buckets a chain of anonymous near orientations the same under permutation', () => { - const anonymousChain = () => [ + const [x, y, z] = [0, CHAIN, 2 * CHAIN].map((theta, position) => makeFacts(null, { - orientation: IDENTITY_ORIENTATION, - projectedPosition: 0, - }), - makeFacts(null, { - orientation: tiltedOrientation(CHAIN), - projectedPosition: 1, - }), - makeFacts(null, { - orientation: tiltedOrientation(2 * CHAIN), - projectedPosition: 2, - }), - ]; - - const [x, y, z] = anonymousChain(); + orientation: tiltedOrientation(theta), + projectedPosition: position, + }) + ); const forward = plan([x, y, z]); expect(forward.map((c) => c.members.length)).toEqual([1, 2]); @@ -249,12 +239,9 @@ describe('planDicomCollections', () => { }); it('breaks a shared position between anonymous members on instance number', () => { - const anonymousPair = () => [ - makeFacts(null, { projectedPosition: 0, instanceNumber: 1 }), - makeFacts(null, { projectedPosition: 0, instanceNumber: 2 }), - ]; - - const [a, b] = anonymousPair(); + const [a, b] = [1, 2].map((instanceNumber) => + makeFacts(null, { projectedPosition: 0, instanceNumber }) + ); const forward = plan([a, b]); expect(forward[0].members.map((m) => m.instanceNumber)).toEqual([1, 2]); @@ -707,18 +694,6 @@ describe('acquisition descriptors', () => { expect(plan(members)).toEqual(plan([...members].reverse())); }); - it('labels incompatible pixel shapes', () => { - const collections = plan([ - makeFacts('small', { rows: '4' }), - makeFacts('large', { rows: '8' }), - ]); - - expect(collections.map((collection) => collection.label)).toEqual([ - 'rows 4', - 'rows 8', - ]); - }); - it('keeps incompatible acquisition descriptors apart when geometry is unreadable', () => { const collections = plan( ['first', 'second'].map((sequenceName) => diff --git a/packages/dicom/core/collections/__tests__/sliceFixture.ts b/packages/dicom/core/collections/__tests__/sliceFixture.ts index 4f2f94eb6..b9cb3215a 100644 --- a/packages/dicom/core/collections/__tests__/sliceFixture.ts +++ b/packages/dicom/core/collections/__tests__/sliceFixture.ts @@ -19,6 +19,13 @@ export type SliceOptions = { let sopCounter = 0; +// A null value leaves its tag out. +const present = ( + tag: string, + value: T | null, + format: (value: T) => string = String +): Array<[string, string]> => (value === null ? [] : [[tag, format(value)]]); + /** A planner-ready MR slice header; every call mints a fresh SOP UID by default. */ export function sliceDataset(options: SliceOptions = {}) { const { @@ -32,7 +39,7 @@ export function sliceDataset(options: SliceOptions = {}) { tags = {}, } = options; - const entries: Array<[string, string]> = [ + return datasetFromTags([ [Tags.StudyInstanceUID, '1.2.826.0.1.3680043.9.1'], [Tags.PatientID, 'patient-1'], [Tags.SeriesNumber, '1'], @@ -40,17 +47,13 @@ export function sliceDataset(options: SliceOptions = {}) { [Tags.Rows, rows], [Tags.Columns, '4'], [Tags.SamplesPerPixel, '1'], - ]; - if (orientation !== null) - entries.push([Tags.ImageOrientationPatient, orientation]); - if (series !== null) entries.push([Tags.SeriesInstanceUID, series]); - if (sop !== null) entries.push([Tags.SOPInstanceUID, sop]); - if (z !== null) entries.push([Tags.ImagePositionPatient, `0\\0\\${z}`]); - if (instanceNumber !== null) - entries.push(['0020|0013', String(instanceNumber)]); - entries.push(...Object.entries(tags)); - - return datasetFromTags(entries); + ...present(Tags.ImageOrientationPatient, orientation), + ...present(Tags.SeriesInstanceUID, series), + ...present(Tags.SOPInstanceUID, sop), + ...present(Tags.ImagePositionPatient, z, (value) => `0\\0\\${value}`), + ...present('0020|0013', instanceNumber), + ...Object.entries(tags), + ]); } /** The planner's facts for one slice, read the way a real header is. */ diff --git a/packages/dicom/core/collections/groupBy.ts b/packages/dicom/core/collections/groupBy.ts index fec13bb4b..f12ba239a 100644 --- a/packages/dicom/core/collections/groupBy.ts +++ b/packages/dicom/core/collections/groupBy.ts @@ -1,6 +1,6 @@ /** Groups preserve input order, both of the keys and of their members. */ -export const groupBy = (items: T[], keyOf: (item: T) => string) => { - const groups = new Map(); +export const groupBy = (items: T[], keyOf: (item: T) => K) => { + const groups = new Map(); items.forEach((item) => { const key = keyOf(item); const group = groups.get(key); diff --git a/packages/dicom/core/collections/instanceFacts.ts b/packages/dicom/core/collections/instanceFacts.ts index 837f0fb81..6f83ddc26 100644 --- a/packages/dicom/core/collections/instanceFacts.ts +++ b/packages/dicom/core/collections/instanceFacts.ts @@ -35,18 +35,14 @@ const vectorOf = ( metadata: DicomDataset, tag: string, length: number, - frameIndex = 0 + frameIndex: number ) => { - const raw = getFrameTag(metadata, tag, frameIndex); - const text = raw === undefined ? null : trimDicomPadding(raw); - if (text === null) return null; - const parts = text.split('\\').map(trimDicomPadding); + const parts = getFrameTag(metadata, tag, frameIndex) + ?.split('\\') + .map(trimDicomPadding); + if (parts?.length !== length || !parts.every(Boolean)) return null; const values = parts.map(Number); - return parts.length === length && - parts.every((part) => part.length > 0) && - values.every((value) => Number.isFinite(value)) - ? values - : null; + return values.every((value) => Number.isFinite(value)) ? values : null; }; const cross = (left: number[], right: number[]) => [ diff --git a/packages/dicom/core/collections/instanceRegistry.ts b/packages/dicom/core/collections/instanceRegistry.ts index 39023501c..8378d8ab9 100644 --- a/packages/dicom/core/collections/instanceRegistry.ts +++ b/packages/dicom/core/collections/instanceRegistry.ts @@ -71,13 +71,13 @@ export const emptyRegistry: RegistryState = new Map(); const emptySeries: SeriesState = { instances: new Map(), committed: new Map() }; -const keyOf = (instance: Instance): InstanceKey => +const keyOf = (instance: Instance) => trimDicomPadding( getDatasetTag(instance.dataset, Tags.SOPInstanceUID) ?? '' ) || instance; // A facts object of its own: the planner's members are matched back by identity. -const registeredOf = (instance: Instance): Registered => ({ +const registeredOf = (instance: Instance) => ({ key: keyOf(instance), instance, facts: { ...readDatasetDetails(instance.dataset).facts }, @@ -117,10 +117,7 @@ const unchanged = (before: Committed, after: Committed) => sameList(before.orientation, after.orientation) && sameReconstruction(before.reconstruction, after.reconstruction); -const changeOf = ( - before: Committed | undefined, - after: Committed -): CollectionChange => { +const changeOf = (before: Committed | undefined, after: Committed) => { if (!before) return 'new'; return unchanged(before, after) ? 'unchanged' : 'changed'; }; @@ -130,9 +127,7 @@ const sameDescription = (before: Committed | undefined, after: Committed) => (before.label === after.label && sameList(before.warnings, after.warnings)); const kindOf = (first: Instance) => - getDatasetModality(first.dataset) === 'SEG' - ? ('segmentation' as const) - : ('image' as const); + getDatasetModality(first.dataset) === 'SEG' ? 'segmentation' : 'image'; // The first registration of an instance wins; a re-supply only reports back. function mergeBatch(series: SeriesState, batch: Registered[]) { diff --git a/packages/dicom/core/collections/planDicomCollections.ts b/packages/dicom/core/collections/planDicomCollections.ts index c1a017122..1451f4fee 100644 --- a/packages/dicom/core/collections/planDicomCollections.ts +++ b/packages/dicom/core/collections/planDicomCollections.ts @@ -336,8 +336,7 @@ const unreadablePositionNotes = ( unreadable && (placed || stacked) ? [UNREADABLE_POSITION_WARNING] : [], }); -export function planDicomCollections(input: PlanInput) { - const { instances } = input; +export function planDicomCollections({ seriesKey, instances }: PlanInput) { const labelHardFacts = hardFactLabeler(instances); const multiframe = (instance: InstanceFacts) => @@ -369,12 +368,12 @@ export function planDicomCollections(input: PlanInput) { const placed = parts.some(({ part }) => !part.unreadablePositions); - const collections = parts + return parts .map(({ group, bucket, positionOf, part }) => { const members = orderMembers(part.members, positionOf); const reconstruction = reconstructInstances(members, bucket.normal); const key: CollectionKey = { - seriesKey: input.seriesKey, + seriesKey, parts: [ ...hardFactParts(group[0]), [ORIENTATION_RULE, bucket.value], @@ -414,6 +413,4 @@ export function planDicomCollections(input: PlanInput) { .sort((left, right) => canonicalKey(left.key) < canonicalKey(right.key) ? -1 : 1 ); - - return collections; } diff --git a/packages/dicom/core/collections/reconstructVolume.ts b/packages/dicom/core/collections/reconstructVolume.ts index 820522ce9..7f0a24ca2 100644 --- a/packages/dicom/core/collections/reconstructVolume.ts +++ b/packages/dicom/core/collections/reconstructVolume.ts @@ -37,10 +37,10 @@ export type Reconstruction = /** * How far apart two slice gaps may be and still be one lattice: a tenth of a * millimetre (capped at a tenth of the gap), or one part in a hundred of the - * gap, whichever is larger. DICOM - * prints a position as a decimal string, so the projection of an oblique stack - * onto its normal jitters in the last digits; a genuine slab boundary or a - * missed slice is orders of magnitude larger. + * gap, whichever is larger. DICOM prints a position as a decimal string, so + * the projection of an oblique stack onto its normal jitters in the last + * digits; a genuine slab boundary or a missed slice is orders of magnitude + * larger. */ const SLICE_SPACING_TOLERANCE_MM = 0.1; const SLICE_SPACING_TOLERANCE_CAP = 0.1; diff --git a/packages/dicom/core/collections/splitOverlappingAcquisitions.ts b/packages/dicom/core/collections/splitOverlappingAcquisitions.ts index 71b1485a4..32453a7ae 100644 --- a/packages/dicom/core/collections/splitOverlappingAcquisitions.ts +++ b/packages/dicom/core/collections/splitOverlappingAcquisitions.ts @@ -53,30 +53,16 @@ const UNREADABLE_GEOMETRY = 'unreadable'; */ export type PositionOf = (member: InstanceFacts) => number | null; -const countDistinctPositions = ( - members: InstanceFacts[], - positionOf: PositionOf -) => new Set(members.map(positionOf)).size; - -const hasRepeatedPositions = ( - members: InstanceFacts[], - positionOf: PositionOf -) => countDistinctPositions(members, positionOf) !== members.length; +const spanOf = (group: InstanceFacts[], positionOf: PositionOf) => { + const positions = group.map(positionOf) as number[]; + return { min: Math.min(...positions), max: Math.max(...positions) }; +}; /** * Whether any two groups cover overlapping stretches of the slice axis. * Bounds are closed, so scans sharing a boundary slice count as overlapping: * that shared position is a duplicate either way. */ -const spanOf = (group: InstanceFacts[], positionOf: PositionOf) => - group.reduce( - (span, member) => ({ - min: Math.min(span.min, positionOf(member) as number), - max: Math.max(span.max, positionOf(member) as number), - }), - { min: Infinity, max: -Infinity } - ); - const anySpansOverlap = (groups: InstanceFacts[][], positionOf: PositionOf) => { const spans = groups .map((group) => spanOf(group, positionOf)) @@ -96,14 +82,10 @@ const groupByAxis = ( singlePlane: boolean ) => { const independentImages = singlePlane && axis.kind === 'descriptor'; - const tagged = new Map(); - members.forEach((member) => { - const value = member[axis.fact]; - if (value === null && !independentImages) return; - const group = tagged.get(value); - if (group) group.push(member); - else tagged.set(value, [member]); - }); + const tagged = groupBy( + members.filter((member) => member[axis.fact] !== null || independentImages), + (member) => member[axis.fact] + ); // A counter stamped per slice cannot establish a separate acquisition. // Descriptor differences on one plane distinguish images without removing // a slice from a spatial stack. @@ -113,15 +95,12 @@ const groupByAxis = ( axis.kind === 'contrast' || independentImages || group.length > 1 ) ); - const remainder = members.filter((member) => { - const value = member[axis.fact]; - return !eligible.has(value); - }); + const remainder = members.filter( + (member) => !eligible.has(member[axis.fact]) + ); return { tagged: eligible, remainder }; }; -type Split = { value: string | null; members: InstanceFacts[] }; - /** * The first axis whose tagged groups cover overlapping stretches of the slice * axis, with the members that carry no value for it as their own part. Scans @@ -198,7 +177,8 @@ function splitByAxes( ): SemanticPart[] { // Counters alone leave a repeatedly scanned plane as a time series. Contrast // tags and descriptors can still distinguish independent images on it. - const singlePlane = countDistinctPositions(members, positionOf) === 1; + const distinctPositions = new Set(members.map(positionOf)).size; + const singlePlane = distinctPositions === 1; const found = firstSplittingAxis( members, singlePlane ? axes.filter((axis) => axis.kind !== 'counter') : axes, @@ -206,13 +186,13 @@ function splitByAxes( singlePlane ); if (!found) - return unsplit(members, axes, hasRepeatedPositions(members, positionOf)); + return unsplit(members, axes, distinctPositions !== members.length); const { axis, tagged, remainder } = found; const index = axes.indexOf(axis); const skipped = axes.slice(0, index); const rest = axes.slice(index + 1); - const splits: Split[] = [ + const splits = [ ...[...tagged].map(([value, group]) => ({ value, members: group })), ...(remainder.length > 0 ? [{ value: null, members: remainder }] : []), ]; diff --git a/packages/dicom/core/header/byteDeque.ts b/packages/dicom/core/header/byteDeque.ts index ab962bff5..0b7811130 100644 --- a/packages/dicom/core/header/byteDeque.ts +++ b/packages/dicom/core/header/byteDeque.ts @@ -1,6 +1,4 @@ -/** - * A byte array deque. - */ +/** A queue of byte chunks, consumed from the start. */ export default class ByteDeque { private arrays: Uint8Array[] = []; private _size = 0; @@ -9,67 +7,40 @@ export default class ByteDeque { return this._size; } - /** - * Push a new Uint8Array to the end. - */ pushEnd(bytes: Uint8Array) { this.arrays.push(bytes); this._size += bytes.length; } - /** - * Push a new Uint8Array to the start. - */ pushStart(bytes: Uint8Array) { this.arrays.unshift(bytes); this._size += bytes.length; } - /** - * Pop bytes off the start. - */ - popStart(count: number): Uint8Array { - return this.consumeStart(count, false) as Uint8Array; + /** Removes up to `count` bytes off the start and returns them. */ + popStart(count: number) { + const popped = new Uint8Array(Math.min(count, this.size)); + this.consumeStart(count, (bytes, offset) => popped.set(bytes, offset)); + return popped; } - /** - * Erase bytes off the start. - * - * This is more efficient than ignoring the return value of popStart - * due to not allocating memory for the return result. - */ - eraseStart(count: number): void { - this.consumeStart(count, true); + /** Removes up to `count` bytes off the start without copying them. */ + eraseStart(count: number) { + this.consumeStart(count); } - private consumeStart(count: number, discard = false) { + private consumeStart( + count: number, + copy?: (bytes: Uint8Array, offset: number) => void + ) { let processed = 0; - const bufferSize = Math.min(count, this.size); - const popped = discard ? null : new Uint8Array(bufferSize); - let writeOffset = 0; - while (processed < count && this.arrays.length) { const bytes = this.arrays.shift()!; - const remaining = count - processed; - // chomp bytes[:offset] - const offset = Math.min(remaining, bytes.length); - const takeEntireArray = offset === bytes.length; - - if (popped) { - const toSet = takeEntireArray ? bytes : bytes.subarray(0, offset); - popped.set(toSet, writeOffset); - writeOffset += toSet.length; - } - - if (!takeEntireArray) { - // put back remainder - this.arrays.unshift(bytes.subarray(offset)); - } - - processed += offset; + const taken = Math.min(count - processed, bytes.length); + copy?.(bytes.subarray(0, taken), processed); + if (taken < bytes.length) this.arrays.unshift(bytes.subarray(taken)); + processed += taken; } - this._size = Math.max(0, this._size - count); - return popped ?? undefined; } } diff --git a/packages/dicom/core/header/dicomParser.ts b/packages/dicom/core/header/dicomParser.ts index f54127034..207e8ffa5 100644 --- a/packages/dicom/core/header/dicomParser.ts +++ b/packages/dicom/core/header/dicomParser.ts @@ -39,6 +39,7 @@ const Tags = { TransferSyntaxUID: [0x0002, 0x0010] as Tag, ItemDelimiter: [0xfffe, 0xe00d] as Tag, Item: [0xfffe, 0xe000] as Tag, + SequenceDelimiter: [0xfffe, 0xe0dd] as Tag, }; // VR reference: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html @@ -72,18 +73,11 @@ function* peekElementTag( { littleEndian = false } = {} ) { const bytes = yield* reader.read(4, { peek: true }); - let group = 0; - let element = 0; - - if (littleEndian) { - group = bytes[0] | (bytes[1] << 8); - element = bytes[2] | (bytes[3] << 8); - } else { - group = bytes[1] | (bytes[0] << 8); - element = bytes[3] | (bytes[2] << 8); - } - - return [group, element] as Tag; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return [ + view.getUint16(0, littleEndian), + view.getUint16(2, littleEndian), + ] as Tag; } /** @@ -130,7 +124,8 @@ function* readFragments(reader: StreamingByteReader, opts: ParseOptions) { for (;;) { const [group, element] = yield* readElementTag(reader, opts); const length = yield* reader.readUint32(opts); - if (group === 0xfffe && element === 0xe0dd && length === 0) return; + if (equalsToTag(Tags.SequenceDelimiter)(group, element) && length === 0) + return; if (!equalsToTag(Tags.Item)(group, element) || length === UNDEFINED_LENGTH) throw new Error('Expected a defined-length encapsulated fragment'); yield* reader.seek(length); @@ -145,53 +140,36 @@ function* readFragments(reader: StreamingByteReader, opts: ParseOptions) { * Assumes the reader is pointing to the start of a Data Element. * https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.1 */ -function* readDataElement( - reader: StreamingByteReader, - opts: ParseOptions = {} -) { +function* readDataElement(reader: StreamingByteReader, opts: ParseOptions) { const { littleEndian = false, explicitVr = false } = opts; - // read tag const [group, element] = yield* readElementTag(reader, { littleEndian }); - let length = 0; - let vr: string = ''; - let data: DataElement['data']; + let vr = ''; + let length: number; if (explicitVr) { - // read VR vr = yield* reader.readAscii(2); if (ExplicitVrLegacyDataElementFormat.has(vr)) { length = yield* reader.readUint16({ littleEndian }); } else { - // skip reserved bytes + // Two reserved bytes precede the 32 bit length. yield* reader.seek(2); length = yield* reader.readUint32({ littleEndian }); } - if ( length === UNDEFINED_LENGTH && ExplicitVrCannotHaveUndefinedLength.has(vr) - ) { + ) console.warn(`Invalid DICOM. VR ${vr} may not have undefined length`); - } - - data = yield* readElementValue(reader, vr, length, { - littleEndian, - explicitVr, - }); } else { length = yield* reader.readUint32({ littleEndian }); - - // For implicit VR with undefined length, assume it's a sequence - if (length === UNDEFINED_LENGTH) { - vr = 'SQ'; - } - - data = yield* readElementValue(reader, vr, length, { - littleEndian, - explicitVr, - }); + // An implicit VR element of undefined length is read as a sequence. + if (length === UNDEFINED_LENGTH) vr = 'SQ'; } + const data = yield* readElementValue(reader, vr, length, { + littleEndian, + explicitVr, + }); return { group, element, vr, length, data }; } @@ -252,7 +230,7 @@ function* skipSequenceValue( const [group, element] = yield* readElementTag(reader, opts); if (equalsToTag(Tags.Item)(group, element)) { yield* skipSequenceItem(reader, opts); - } else if (group === 0xfffe && element === 0xe0dd) { + } else if (equalsToTag(Tags.SequenceDelimiter)(group, element)) { yield* reader.seek(4); return; } else { @@ -266,56 +244,50 @@ function* skipSequenceValue( } // Per Part 10: "File Meta Information shall be encoded using the Explicit VR Little Endian Transfer Syntax" +const FILE_META_ENCODING = { explicitVr: true, littleEndian: true }; + +/** Reads the file meta information and returns its transfer syntax. */ function* readFileMetaInfo( reader: StreamingByteReader, - opts?: { onDataElement?: DataElementCallback } + onDataElement: DataElementCallback | undefined ) { - // read up until the Transfer Syntax UID yield* readDataElementsUntil(reader, equalsToTag(Tags.TransferSyntaxUID), { - explicitVr: true, - littleEndian: true, - onDataElement: opts?.onDataElement, + ...FILE_META_ENCODING, + onDataElement, }); - const transferSyntaxUidElement = yield* readDataElement(reader, { - explicitVr: true, - littleEndian: true, - }); - opts?.onDataElement?.(transferSyntaxUidElement); + const transferSyntaxUidElement = yield* readDataElement( + reader, + FILE_META_ENCODING + ); + onDataElement?.(transferSyntaxUidElement); if (transferSyntaxUidElement.vr !== 'UI') throw new Error('Transfer syntax UID element does not have a VR of UI'); if (!transferSyntaxUidElement.data) throw new Error('Did not get data for the transfer syntax UID element'); - const transferSyntaxUid = toAscii( - transferSyntaxUidElement.data as Uint8Array, - { - ignoreNulls: true, - } - ); + const transferSyntaxUid = toAscii(transferSyntaxUidElement.data, { + ignoreNulls: true, + }); // Compressed bytes can resemble meta elements. The complete reader will // locate the end of group 2 and inflate the dataset before walking it. if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) - return { transferSyntaxUid }; + return transferSyntaxUid; - // read until end of file meta info group block, which is the first non 0x0002 grouped element. - // "Values of all Tags (0002,xxxx) are reserved for use by this Standard and later versions of DICOM." + // The meta group ends at the first element outside group 0002. // https://dicom.nema.org/medical/dicom/current/output/html/part10.html#table_7.1-1 yield* readDataElementsUntil(reader, (group) => group !== 0x0002, { - explicitVr: true, - littleEndian: true, - onDataElement: opts?.onDataElement, + ...FILE_META_ENCODING, + onDataElement, }); - return { - transferSyntaxUid, - }; + return transferSyntaxUid; } type ReadDicomOptions = { - stopAtElement?(group: number, element: number): boolean; + stopAtElement: (group: number, element: number) => boolean; onDataElement?: DataElementCallback; /** Called once the opening bytes say how the file is laid out. */ onLayout?(layout: DicomLayout): void; @@ -323,37 +295,34 @@ type ReadDicomOptions = { onTransferSyntax?(transferSyntaxUid: string): void; }; -function* readDicomUntilPixelData(opts?: ReadDicomOptions) { +function* readDicomUntilPixelData(opts: ReadDicomOptions) { const reader = new StreamingByteReader(); // Peeked rather than read: a file without the Part 10 preamble has its // first element at byte 0. const head = yield* reader.read(PART_10_HEADER_LENGTH, { peek: true }); const layout = sniffDicomLayout(head); - opts?.onLayout?.(layout); + opts.onLayout?.(layout); if (layout.preamble) yield* reader.seek(PART_10_HEADER_LENGTH); const transferSyntaxUid = layout.fileMeta - ? (yield* readFileMetaInfo(reader, { - onDataElement: opts?.onDataElement, - })).transferSyntaxUid + ? yield* readFileMetaInfo(reader, opts.onDataElement) : layout.transferSyntaxUid; - opts?.onTransferSyntax?.(transferSyntaxUid); + opts.onTransferSyntax?.(transferSyntaxUid); // A negative boundary asks the metadata loader to retain the complete file. if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) return { position: -1 }; const explicitVr = transferSyntaxUid !== IMPLICIT_VR_LITTLE_ENDIAN; const littleEndian = transferSyntaxUid !== EXPLICIT_VR_BIG_ENDIAN; - yield* readDataElementsUntil( - reader, - (group, element) => opts?.stopAtElement?.(group, element) ?? false, - { explicitVr, littleEndian, onDataElement: opts?.onDataElement } - ); + yield* readDataElementsUntil(reader, opts.stopAtElement, { + explicitVr, + littleEndian, + onDataElement: opts.onDataElement, + }); return { position: reader.position }; } -export const createDicomParser = (callbacks?: ReadDicomOptions) => { - return asCoroutine(readDicomUntilPixelData(callbacks)); -}; +export const createDicomParser = (callbacks: ReadDicomOptions) => + asCoroutine(readDicomUntilPixelData(callbacks)); diff --git a/packages/dicom/core/header/readDicomHeader.ts b/packages/dicom/core/header/readDicomHeader.ts index 878a8aa5b..8565001ce 100644 --- a/packages/dicom/core/header/readDicomHeader.ts +++ b/packages/dicom/core/header/readDicomHeader.ts @@ -150,15 +150,13 @@ export async function readDicomHeader( received, Math.min(total, (end ?? total) + PIXEL_DATA_HEAD_LENGTH) ); - const head = - found.atPixelData && end !== undefined ? bytes.subarray(end) : null; return { header: bytes.subarray(0, end), layout: found.layout, transferSyntaxUid, pixelData: - head && transferSyntaxUid - ? pixelDataElement(head, end!, transferSyntaxUid) + found.atPixelData && end !== undefined && transferSyntaxUid + ? pixelDataElement(bytes.subarray(end), end, transferSyntaxUid) : null, }; } diff --git a/packages/dicom/core/header/streamingByteReader.ts b/packages/dicom/core/header/streamingByteReader.ts index 1258361c9..8a32712cb 100644 --- a/packages/dicom/core/header/streamingByteReader.ts +++ b/packages/dicom/core/header/streamingByteReader.ts @@ -1,18 +1,10 @@ import ByteDeque from './byteDeque'; import { toAscii } from '../utils'; -/** - * StreamingByteReader - * - * Expects Uint8Array inputs - */ +/** Reads values off a byte stream that a generator's caller feeds chunk by chunk. */ export default class StreamingByteReader { - protected leftover: ByteDeque; - protected pos = 0; - - constructor() { - this.leftover = new ByteDeque(); - } + private leftover = new ByteDeque(); + private pos = 0; get position() { return this.pos; @@ -57,28 +49,26 @@ export default class StreamingByteReader { return data; } - /** Reads an ASCII string. */ - *readAscii(length: number, { ignoreNulls = false, peek = false } = {}) { - const bytes = yield* this.read(length, { peek }); - return toAscii(bytes, { ignoreNulls }); + *readAscii(length: number) { + return toAscii(yield* this.read(length)); } /** `length` must be the length associated with the method. */ private *readDataView( method: 'getUint16' | 'getUint32', length: number, - { littleEndian = false, peek = false } = {} + littleEndian: boolean ) { - const bytes = yield* this.read(length, { peek }); + const bytes = yield* this.read(length); const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); return dv[method](0, littleEndian); } - *readUint16(opts = {}) { - return yield* this.readDataView('getUint16', 2, opts); + *readUint16({ littleEndian = false } = {}) { + return yield* this.readDataView('getUint16', 2, littleEndian); } - *readUint32(opts = {}) { - return yield* this.readDataView('getUint32', 4, opts); + *readUint32({ littleEndian = false } = {}) { + return yield* this.readDataView('getUint32', 4, littleEndian); } } diff --git a/packages/dicom/core/index.ts b/packages/dicom/core/index.ts index 0668a5769..753ccbb97 100644 --- a/packages/dicom/core/index.ts +++ b/packages/dicom/core/index.ts @@ -19,11 +19,7 @@ export { } from './metadata/dicomLayout'; // Datasets -export { - readDicomDataset, - type DicomDataset, - type DicomElement, -} from './metadata/dicomDataset'; +export { readDicomDataset, type DicomDataset } from './metadata/dicomDataset'; export { getDatasetTag, getDatasetModality } from './metadata/datasetAccess'; export { sequenceItems } from './metadata/functionalGroups'; export { trimDicomPadding } from './utils'; diff --git a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts index 1bbcfe420..2bf8eb941 100644 --- a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts +++ b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts @@ -31,6 +31,16 @@ const REGION = { physicalDeltaX: 0.0625, physicalDeltaY: 0.125 }; const never = () => new AbortController().signal; const CHUNK = 256; +/** A dataset reader that records the header bytes it is handed. */ +const recordingReader = () => { + const seen: Uint8Array[] = []; + const readDataset = (header: Uint8Array) => { + seen.push(header); + return { elements: [], specificCharacterSet: null }; + }; + return { seen, readDataset }; +}; + const largeSlice = () => syntheticSlice({ rows: 64, @@ -162,7 +172,7 @@ describe('readInstance over byte sources', () => { it('parses nothing when the stream fails before the header ends', async () => { const bytes = syntheticSlice(); - const seen: Uint8Array[] = []; + const { seen, readDataset } = recordingReader(); const failing = { read: () => new ReadableStream({ @@ -174,26 +184,16 @@ describe('readInstance over byte sources', () => { }; await expect( - readInstance(failing, never(), { - readDataset: (header) => { - seen.push(header); - return { elements: [], specificCharacterSet: null }; - }, - }) + readInstance(failing, never(), { readDataset }) ).rejects.toThrow('connection reset'); expect(seen).toEqual([]); }); it('hands the dataset reader the header bytes, once', async () => { const bytes = syntheticSlice(); - const seen: Uint8Array[] = []; + const { seen, readDataset } = recordingReader(); - await readInstance(trackedSource(bytes).source, never(), { - readDataset: (header) => { - seen.push(header); - return { elements: [], specificCharacterSet: null }; - }, - }); + await readInstance(trackedSource(bytes).source, never(), { readDataset }); expect(seen).toEqual([bytes.slice(0, pixelDataStart(bytes))]); }); diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts index 2c0990b41..8836a3d20 100644 --- a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -1,6 +1,6 @@ import { readDicomDataset, findElement } from '../dicomDataset'; import { getDatasetTag } from '../datasetAccess'; -import { getFrameTag } from '../functionalGroups'; +import { getFrameTag, sequenceItems } from '../functionalGroups'; import { createDicomParser } from '../../header/dicomParser'; import { deflateRawSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; @@ -20,6 +20,7 @@ import { } from '@/tests/specs/syntheticDicom'; const PREAMBLE_LENGTH = 128; +const encode = (text: string) => new TextEncoder().encode(text); // (0002,0000) UL occupies twelve bytes, including its value. const GROUP_LENGTH_ELEMENT_LENGTH = 12; const withoutGroupLength = (file: Uint8Array) => @@ -70,7 +71,6 @@ describe('file meta information', () => { ({ groupLength, deflate }) => { const file = buildSlice(); file.fill(0x41, 0, PREAMBLE_LENGTH); - const encode = (text: string) => new TextEncoder().encode(text); const meta = concatBytes([ rawElement(0x0002, 0x0010, 'UI', encode('1.2.840.10008.1.2.1.99')), // The transfer syntax need not be the last file-meta element. @@ -104,7 +104,6 @@ describe('file meta information', () => { }); describe('lenient headers with standards-defined values', () => { - const encode = (text: string) => new TextEncoder().encode(text); it.each([false, true])( 'ignores an undersized meta group length (implicit: %s)', (implicitVr) => { @@ -251,9 +250,8 @@ describe('lenient headers with standards-defined values', () => { ], }) ); - const sequence = findElement(dataset, '00081140')!.values; - if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); - expect(findElement(sequence.items[0], '00291010')!.values).toEqual({ + const [reference] = sequenceItems(dataset, '00081140'); + expect(findElement(reference, '00291010')!.values).toEqual({ kind: 'bytes', values: [bytes], }); @@ -279,7 +277,6 @@ describe('lenient headers with standards-defined values', () => { it.each([sequenceItem, undefinedLengthItem])( 'reads an implicit private undefined-length sequence with %s', async (item) => { - const encode = (text: string) => new TextEncoder().encode(text); const content = toImplicitVr( rawElement(0x0010, 0x0010, 'PN', encode('DOE^JANE')) ); @@ -296,16 +293,14 @@ it.each([sequenceItem, undefinedLengthItem])( base.subarray(pixelStart), ]); const dataset = readDicomDataset(bytes); - const sequence = findElement(dataset, '00431029')!.values; - if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); - expect(getDatasetTag(sequence.items[0], '00100010')).toBe('DOE^JANE'); + const [privateItem] = sequenceItems(dataset, '00431029'); + expect(getDatasetTag(privateItem, '00100010')).toBe('DOE^JANE'); const instance = await readHeader(bytes, 7); expect(instance.dataset).toEqual(readDicomDataset(base)); } ); it('decodes a known UN nested inside an explicit sequence with inherited UTF-8', () => { - const encode = (text: string) => new TextEncoder().encode(text); const dataset = readDicomDataset( concatBytes([ rawElement(0x0008, 0x0005, 'CS', encode('ISO_IR 192')), @@ -317,16 +312,13 @@ it('decodes a known UN nested inside an explicit sequence with inherited UTF-8', ), ]) ); - const sequence = findElement(dataset, '00081140')!.values; - if (sequence.kind !== 'sequence') throw new Error('Expected a sequence'); - expect(getDatasetTag(sequence.items[0], '00100010')?.trim()).toBe( - 'M\u00dcLLER' - ); + const [reference] = sequenceItems(dataset, '00081140'); + expect(getDatasetTag(reference, '00100010')?.trim()).toBe('M\u00dcLLER'); }); it('stops before a known UN Pixel Data value, even when only its header is present', () => { const input = concatBytes([ - rawElement(0x0008, 0x0060, 'CS', new TextEncoder().encode('CT')), + rawElement(0x0008, 0x0060, 'CS', encode('CT')), rawElement(0x7fe0, 0x0010, 'UN', new Uint8Array(16)).subarray(0, 12), ]); expect(parseDicomElements(input)).toHaveLength(1); diff --git a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts index 58aa35da8..0321dfb91 100644 --- a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from 'vitest'; import { DicomDataset, findElement, readDicomDataset } from '../dicomDataset'; +import { sequenceItems } from '../functionalGroups'; +import { concatBytes } from '../../utils'; import { rawElement, sequenceItem, @@ -33,15 +35,6 @@ const STUDY_COMMENTS = '00324000'; const ascii = (text: string) => new TextEncoder().encode(text); -const concat = (...parts: Uint8Array[]) => { - const out = new Uint8Array(parts.reduce((n, part) => n + part.length, 0)); - parts.reduce((offset, part) => { - out.set(part, offset); - return offset + part.length; - }, 0); - return out; -}; - const item = sequenceItem; const sequence = (group: number, element: number, items: Uint8Array) => @@ -53,14 +46,14 @@ const NESTED_SEQUENCE = sequence( 0x0040, 0x0275, item( - concat( + concatBytes([ sequence( 0x0040, 0x0008, item(rawElement(0x0008, 0x0104, 'LO', ascii('MEANING '))) ), - rawElement(0x0040, 0x0009, 'SH', ascii('SPS1 ')) - ) + rawElement(0x0040, 0x0009, 'SH', ascii('SPS1 ')), + ]) ) ); @@ -116,18 +109,16 @@ describe('readDicomDataset', () => { const dataset = readDicomDataset( buildSlice({ extraElements: [NESTED_SEQUENCE] }) ); - const outer = valuesOf(dataset, REQUEST_ATTRIBUTES); - if (outer?.kind !== 'sequence') throw new Error('not a sequence'); - const inner = valuesOf(outer.items[0], REFERENCED_STUDY); - if (inner?.kind !== 'sequence') throw new Error('not a sequence'); + const outer = sequenceItems(dataset, REQUEST_ATTRIBUTES); + const inner = sequenceItems(outer[0], REFERENCED_STUDY); - expect(outer.items).toHaveLength(1); - expect(valuesOf(outer.items[0], SCHEDULED_PROCEDURE_STEP_ID)).toEqual({ + expect(outer).toHaveLength(1); + expect(valuesOf(outer[0], SCHEDULED_PROCEDURE_STEP_ID)).toEqual({ kind: 'text', values: ['SPS1 '], }); - expect(inner.items).toHaveLength(1); - expect(valuesOf(inner.items[0], CODE_MEANING)).toEqual({ + expect(inner).toHaveLength(1); + expect(valuesOf(inner[0], CODE_MEANING)).toEqual({ kind: 'text', values: ['MEANING '], }); @@ -148,19 +139,18 @@ describe('readDicomDataset', () => { 0x0040, 0x0275, item( - concat( + concatBytes([ ...localCharacterSet, - rawElement(0x0008, 0x0104, 'LO', ascii(UTF8_ITEM_TEXT)) - ) + rawElement(0x0008, 0x0104, 'LO', ascii(UTF8_ITEM_TEXT)), + ]) ) ), ], }) ); - const values = valuesOf(dataset, REQUEST_ATTRIBUTES); - if (values?.kind !== 'sequence') throw new Error('not a sequence'); + const [requested] = sequenceItems(dataset, REQUEST_ATTRIBUTES); - expect(valuesOf(values.items[0], CODE_MEANING)).toEqual({ + expect(valuesOf(requested, CODE_MEANING)).toEqual({ kind: 'text', values: [UTF8_ITEM_TEXT], }); @@ -184,22 +174,21 @@ describe('readDicomDataset', () => { specificCharacterSet: JAPANESE_CHARACTER_SET, extraElements: [ build( - concat( + concatBytes([ rawElement(0x0008, 0x0005, 'CS', ascii(JAPANESE_CHARACTER_SET)), - rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES) - ) + rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES), + ]) ), ], }) ); - const values = valuesOf(dataset, REQUEST_ATTRIBUTES); - if (values?.kind !== 'sequence') throw new Error('not a sequence'); + const [requested] = sequenceItems(dataset, REQUEST_ATTRIBUTES); - expect(values.items[0].specificCharacterSet).toEqual([ + expect(requested.specificCharacterSet).toEqual([ 'ISO 2022 IR 6', 'ISO 2022 IR 87', ]); - expect(valuesOf(values.items[0], PATIENT_NAME)).toEqual({ + expect(valuesOf(requested, PATIENT_NAME)).toEqual({ kind: 'text', values: [JAPANESE_NAME], }); @@ -218,16 +207,15 @@ describe('readDicomDataset', () => { ultrasoundRegion: { physicalDeltaX: 0.1, physicalDeltaY: 0.2 }, }) ); - const values = valuesOf(dataset, ULTRASOUND_REGIONS); - if (values?.kind !== 'sequence') throw new Error('not a sequence'); + const [region] = sequenceItems(dataset, ULTRASOUND_REGIONS); - expect(values.items[0].elements.map(({ tag }) => tag)).toEqual([ + expect(region.elements.map(({ tag }) => tag)).toEqual([ '00186024', '00186026', '0018602C', '0018602E', ]); - expect(valuesOf(values.items[0], PHYSICAL_DELTA_X)).toEqual({ + expect(valuesOf(region, PHYSICAL_DELTA_X)).toEqual({ kind: 'number', values: [0.1], }); diff --git a/packages/dicom/core/metadata/datasetAccess.ts b/packages/dicom/core/metadata/datasetAccess.ts index 522ec0fe4..b2b34b0b1 100644 --- a/packages/dicom/core/metadata/datasetAccess.ts +++ b/packages/dicom/core/metadata/datasetAccess.ts @@ -5,8 +5,7 @@ import { trimDicomPadding } from '../utils'; export const canonicalTag = (tag: string) => tag.replace('|', '').toUpperCase(); /** Text and numeric values retain multiplicity; sequences and opaque bytes do not become text. */ -function getElementText(element: DicomElement): string | undefined { - const { values } = element; +function getElementText({ values }: DicomElement) { switch (values.kind) { case 'text': case 'number': diff --git a/packages/dicom/core/metadata/dcmjs.d.ts b/packages/dicom/core/metadata/dcmjs.d.ts index a74c509fa..1e4cc1e35 100644 --- a/packages/dicom/core/metadata/dcmjs.d.ts +++ b/packages/dicom/core/metadata/dcmjs.d.ts @@ -15,7 +15,6 @@ declare module 'dcmjs' { untilTag?: string; includeUntilTagValue?: boolean; forceStoreRaw?: boolean; - ignoreErrors?: boolean; }; export type DicomStringDecoder = { @@ -29,7 +28,6 @@ declare module 'dcmjs' { end(): boolean; increment(count: number): void; setEndian(littleEndian: boolean): void; - readAsciiString(length: number): string; readVR(): string; readUint16(): number; readUint32(): number; @@ -38,17 +36,8 @@ declare module 'dcmjs' { slice(start: number, end: number): ArrayBuffer; }; - export type DicomDictionaryEntry = { - tag: string; - vr: string; - vm: string; - name: string; - }; - export type DicomDataElement = { - vr: string; Value: unknown[]; - _rawValue: unknown; }; const dcmjs: { @@ -57,7 +46,7 @@ declare module 'dcmjs' { }; data: { DicomMetaDictionary: { - dictionary: Record; + dictionary: Record; }; ReadBufferStream: new (buffer: ArrayBuffer) => DicomReadStream; DeflatedReadBufferStream: new ( @@ -73,11 +62,6 @@ declare module 'dcmjs' { syntax: string, options?: DicomReadOptions ): DicomElement; - _read( - stream: DicomReadStream, - syntax: string, - options?: DicomReadOptions - ): Record; _normalizeSyntax(syntax: string): string; }; }; diff --git a/packages/dicom/core/metadata/dcmjsParser.ts b/packages/dicom/core/metadata/dcmjsParser.ts index 5846cbe63..758c846ed 100644 --- a/packages/dicom/core/metadata/dcmjsParser.ts +++ b/packages/dicom/core/metadata/dcmjsParser.ts @@ -117,14 +117,14 @@ const bufferOf = (bytes: Uint8Array) => ? (bytes.buffer as ArrayBuffer) : (bytes.slice().buffer as ArrayBuffer); +const pastDeflatedMeta = (syntax: unknown, offset: number, end: number) => + syntax === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN && offset >= end; + /** * Opens the data set. A file without the Part 10 preamble is read from its * first element; one without file meta information is read in the transfer * syntax its first element suggests. */ -const pastDeflatedMeta = (syntax: unknown, offset: number, end: number) => - syntax === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN && offset >= end; - const openFile = (bytes: Uint8Array) => { const layout = sniffDicomLayout(bytes.subarray(0, PART_10_HEADER_LENGTH)); @@ -262,31 +262,33 @@ const READ_OPTIONS = { forceStoreRaw: true, }; +/** An Implicit VR Little Endian element: tag, 32 bit length and value. */ +const implicitElement = (group: number, element: number, value: Uint8Array) => { + const bytes = new Uint8Array(8 + value.length); + const header = new DataView(bytes.buffer); + header.setUint16(0, group, true); + header.setUint16(2, element, true); + header.setUint32(4, value.length, true); + bytes.set(value, 8); + return bytes; +}; + const readSequence = ( dataSet: DicomReadStream, syntax: string, - sequence: { - group: number; - element: number; - valueStart: number; - end: number | null; - unknown?: boolean; - } + sequence: NonNullable> ): ParsedElement => { - if (sequence.end !== null && sequence.end > dataSet.endOffset) + const { group, element, valueStart, end } = sequence; + if (end !== null && end > dataSet.endOffset) throw new Error('Sequence exceeds the available dataset bytes'); - if (sequence.unknown && sequence.end !== null) { + const takeValue = (valueEnd: number) => { + const value = new Uint8Array(dataSet.slice(valueStart, valueEnd)); + dataSet.offset = valueEnd; + return value; + }; + if (sequence.unknown && end !== null) { // PS3.5 6.2.2: a known UN value retains Implicit VR Little Endian encoding. - const value = new Uint8Array( - dataSet.slice(sequence.valueStart, sequence.end) - ); - const bytes = new Uint8Array(8 + value.length); - const header = new DataView(bytes.buffer); - header.setUint16(0, sequence.group, true); - header.setUint16(2, sequence.element, true); - header.setUint32(4, value.length, true); - bytes.set(value, 8); - dataSet.offset = sequence.end; + const bytes = implicitElement(group, element, takeValue(end)); return readElements( readsBytes(new ReadBufferStream(bytes.buffer)), IMPLICIT_VR_LITTLE_ENDIAN, @@ -294,29 +296,21 @@ const readSequence = ( )[0]; } - const itemSyntax = sequence.unknown ? IMPLICIT_VR_LITTLE_ENDIAN : syntax; - dataSet.offset = sequence.valueStart; + const head = { + group, + element, + vr: sequence.unknown ? 'UN' : 'SQ', + values: [], + }; + dataSet.offset = valueStart; try { - const items = readSequenceItems(dataSet, itemSyntax, sequence.end); - return { - group: sequence.group, - element: sequence.element, - vr: sequence.unknown ? 'UN' : 'SQ', - values: [], - items, - }; + const itemSyntax = sequence.unknown ? IMPLICIT_VR_LITTLE_ENDIAN : syntax; + return { ...head, items: readSequenceItems(dataSet, itemSyntax, end) }; } catch (error) { - if (sequence.end === null) throw error; - const bytes = new Uint8Array( - dataSet.slice(sequence.valueStart, sequence.end) - ); - dataSet.offset = sequence.end; + if (end === null) throw error; return { - group: sequence.group, - element: sequence.element, - vr: sequence.unknown ? 'UN' : 'SQ', - values: [], - unread: { bytes, reason: String(error) }, + ...head, + unread: { bytes: takeValue(end), reason: String(error) }, }; } }; diff --git a/packages/dicom/core/metadata/dicomDataset.ts b/packages/dicom/core/metadata/dicomDataset.ts index e2c712b06..47b7deb5c 100644 --- a/packages/dicom/core/metadata/dicomDataset.ts +++ b/packages/dicom/core/metadata/dicomDataset.ts @@ -59,7 +59,7 @@ export type DicomDataset = { const tagKey = (group: number, element: number) => `${hex4(group)}${hex4(element)}`; -export const isPrivateElement = ({ group }: DicomElement) => (group & 1) === 1; +const isPrivateElement = ({ group }: DicomElement) => (group & 1) === 1; export const findElement = (dataset: DicomDataset, tag: DicomTagKey) => dataset.elements.find((element) => element.tag === tag); @@ -190,9 +190,7 @@ export const readDicomDataset = (bytes: Uint8Array) => buildDataset(parseDicomElements(bytes), null); /** Image loading uses public attributes; private payloads stay in the source. */ -export const withoutPrivateElements = ( - dataset: DicomDataset -): DicomDataset => ({ +const withoutPrivateElements = (dataset: DicomDataset): DicomDataset => ({ ...dataset, elements: dataset.elements .filter((element) => !isPrivateElement(element)) diff --git a/packages/dicom/core/metadata/dicomTags.ts b/packages/dicom/core/metadata/dicomTags.ts index 06b164742..edefa324d 100644 --- a/packages/dicom/core/metadata/dicomTags.ts +++ b/packages/dicom/core/metadata/dicomTags.ts @@ -1,60 +1,55 @@ -type Tag = { - name: string; - tag: string; +export const Tags = { + SOPInstanceUID: '0008|0018', + PatientName: '0010|0010', + PatientID: '0010|0020', + PatientBirthDate: '0010|0030', + PatientSex: '0010|0040', + StudyInstanceUID: '0020|000d', + StudyDate: '0008|0020', + StudyTime: '0008|0030', + StudyID: '0020|0010', + AccessionNumber: '0008|0050', + StudyDescription: '0008|1030', + Modality: '0008|0060', + SeriesInstanceUID: '0020|000e', + SeriesNumber: '0020|0011', + SeriesDate: '0008|0021', + SeriesDescription: '0008|103e', + InstanceNumber: '0020|0013', + WindowLevel: '0028|1050', + WindowWidth: '0028|1051', + VOILUTFunction: '0028|1056', + Rows: '0028|0010', + Columns: '0028|0011', + BitsAllocated: '0028|0100', + BitsStored: '0028|0101', + PixelRepresentation: '0028|0103', + AcquisitionNumber: '0020|0012', + TemporalPositionIdentifier: '0020|0100', + EchoNumbers: '0018|0086', + DiffusionBValue: '0018|9087', + ImagePositionPatient: '0020|0032', + ImageOrientationPatient: '0020|0037', + PixelSpacing: '0028|0030', + SpacingBetweenSlices: '0018|0088', + SliceThickness: '0018|0050', + SequenceName: '0018|0024', + SamplesPerPixel: '0028|0002', + RescaleIntercept: '0028|1052', + RescaleSlope: '0028|1053', + NumberOfFrames: '0028|0008', + SOPClassUID: '0008|0016', + OphthalmicVolumetricPropertiesFlag: '0022|1622', + PhotometricInterpretation: '0028|0004', + PlanarConfiguration: '0028|0006', + FrameTime: '0018|1063', + SequenceOfUltrasoundRegions: '0018|6011', + PhysicalUnitsXDirection: '0018|6024', + PhysicalUnitsYDirection: '0018|6026', + PhysicalDeltaX: '0018|602c', + PhysicalDeltaY: '0018|602e', }; -const tags: Tag[] = [ - { name: 'SOPInstanceUID', tag: '0008|0018' }, - { name: 'PatientName', tag: '0010|0010' }, - { name: 'PatientID', tag: '0010|0020' }, - { name: 'PatientBirthDate', tag: '0010|0030' }, - { name: 'PatientSex', tag: '0010|0040' }, - { name: 'StudyInstanceUID', tag: '0020|000d' }, - { name: 'StudyDate', tag: '0008|0020' }, - { name: 'StudyTime', tag: '0008|0030' }, - { name: 'StudyID', tag: '0020|0010' }, - { name: 'AccessionNumber', tag: '0008|0050' }, - { name: 'StudyDescription', tag: '0008|1030' }, - { name: 'Modality', tag: '0008|0060' }, - { name: 'SeriesInstanceUID', tag: '0020|000e' }, - { name: 'SeriesNumber', tag: '0020|0011' }, - { name: 'SeriesDate', tag: '0008|0021' }, - { name: 'SeriesDescription', tag: '0008|103e' }, - { name: 'InstanceNumber', tag: '0020|0013' }, - { name: 'WindowLevel', tag: '0028|1050' }, - { name: 'WindowWidth', tag: '0028|1051' }, - { name: 'VOILUTFunction', tag: '0028|1056' }, - { name: 'Rows', tag: '0028|0010' }, - { name: 'Columns', tag: '0028|0011' }, - { name: 'BitsAllocated', tag: '0028|0100' }, - { name: 'BitsStored', tag: '0028|0101' }, - { name: 'PixelRepresentation', tag: '0028|0103' }, - { name: 'AcquisitionNumber', tag: '0020|0012' }, - { name: 'TemporalPositionIdentifier', tag: '0020|0100' }, - { name: 'EchoNumbers', tag: '0018|0086' }, - { name: 'DiffusionBValue', tag: '0018|9087' }, - { name: 'ImagePositionPatient', tag: '0020|0032' }, - { name: 'ImageOrientationPatient', tag: '0020|0037' }, - { name: 'PixelSpacing', tag: '0028|0030' }, - { name: 'SpacingBetweenSlices', tag: '0018|0088' }, - { name: 'SliceThickness', tag: '0018|0050' }, - { name: 'SequenceName', tag: '0018|0024' }, - { name: 'SamplesPerPixel', tag: '0028|0002' }, - { name: 'RescaleIntercept', tag: '0028|1052' }, - { name: 'RescaleSlope', tag: '0028|1053' }, - { name: 'NumberOfFrames', tag: '0028|0008' }, - { name: 'SOPClassUID', tag: '0008|0016' }, - { name: 'OphthalmicVolumetricPropertiesFlag', tag: '0022|1622' }, - { name: 'PhotometricInterpretation', tag: '0028|0004' }, - { name: 'PlanarConfiguration', tag: '0028|0006' }, - { name: 'FrameTime', tag: '0018|1063' }, - { name: 'SequenceOfUltrasoundRegions', tag: '0018|6011' }, - { name: 'PhysicalUnitsXDirection', tag: '0018|6024' }, - { name: 'PhysicalUnitsYDirection', tag: '0018|6026' }, - { name: 'PhysicalDeltaX', tag: '0018|602c' }, - { name: 'PhysicalDeltaY', tag: '0018|602e' }, -]; - // DICOM SOP Class UIDs for Ultrasound Multi-frame Image Storage. The current // identifier is .4.1.1.3.1; the retired pre-1993 identifier is .4.1.1.3. // Some legacy clinical archives and well-known test corpora (e.g. GDCM's @@ -63,12 +58,10 @@ export const SOP_CLASS_ULTRASOUND_MULTIFRAME = '1.2.840.10008.5.1.4.1.1.3.1'; export const SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED = '1.2.840.10008.5.1.4.1.1.3'; -export function isUltrasoundMultiframeSopClass(uid: string): boolean { +export function isUltrasoundMultiframeSopClass(uid: string) { const trimmed = uid.trim(); return ( trimmed === SOP_CLASS_ULTRASOUND_MULTIFRAME || trimmed === SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED ); } - -export const Tags = Object.fromEntries(tags.map((t) => [t.name, t.tag])); diff --git a/packages/dicom/core/metadata/functionalGroups.ts b/packages/dicom/core/metadata/functionalGroups.ts index 63035cb98..7e4fc7375 100644 --- a/packages/dicom/core/metadata/functionalGroups.ts +++ b/packages/dicom/core/metadata/functionalGroups.ts @@ -1,5 +1,4 @@ -import type { DicomDataset } from './dicomDataset'; -import { findElement } from './dicomDataset'; +import { findElement, type DicomDataset } from './dicomDataset'; import { canonicalTag, getDatasetTag } from './datasetAccess'; import { getNmDetectorTag } from './nmReconstruction'; diff --git a/packages/dicom/core/metadata/ultrasoundRegion.ts b/packages/dicom/core/metadata/ultrasoundRegion.ts index 48dae7531..284050488 100644 --- a/packages/dicom/core/metadata/ultrasoundRegion.ts +++ b/packages/dicom/core/metadata/ultrasoundRegion.ts @@ -1,7 +1,7 @@ import { getDatasetTag } from './datasetAccess'; import { sequenceItems } from './functionalGroups'; import type { DicomDataset } from './dicomDataset'; -import { trimDicomPadding } from '../utils'; +import { numberOr } from '../utils'; import { Tags } from './dicomTags'; // DICOM unit codes for PhysicalUnitsXDirection / YDirection. @@ -28,10 +28,7 @@ type UltrasoundRegion = { }; const readRegion = (item: DicomDataset): UltrasoundRegion => { - const value = (tag: string) => { - const text = trimDicomPadding(getDatasetTag(item, tag) ?? ''); - return text ? Number(text) : NaN; - }; + const value = (tag: string) => numberOr(getDatasetTag(item, tag), NaN); return { physicalDeltaX: value(Tags.PhysicalDeltaX), physicalDeltaY: value(Tags.PhysicalDeltaY), diff --git a/packages/dicom/core/pixels/encapsulatedFrames.ts b/packages/dicom/core/pixels/encapsulatedFrames.ts index ecca72ad5..9b12c5e6a 100644 --- a/packages/dicom/core/pixels/encapsulatedFrames.ts +++ b/packages/dicom/core/pixels/encapsulatedFrames.ts @@ -1,4 +1,5 @@ import { UNDEFINED_LENGTH } from '../metadata/dicomLayout'; +import { concatBytes } from '../utils'; const ITEM = 0xe000; const SEQUENCE_DELIMITER = 0xe0dd; @@ -53,17 +54,10 @@ function readOffsetTable(table: Uint8Array) { ); } -const joinFragments = (fragments: readonly Fragment[]) => { - if (fragments.length === 1) return fragments[0].bytes; - const out = new Uint8Array( - fragments.reduce((total, { bytes }) => total + bytes.length, 0) - ); - fragments.reduce((offset, { bytes }) => { - out.set(bytes, offset); - return offset + bytes.length; - }, 0); - return out; -}; +const joinFragments = (fragments: readonly Fragment[]) => + fragments.length === 1 + ? fragments[0].bytes + : concatBytes(fragments.map(({ bytes }) => bytes)); function framesFromOffsets(fragments: readonly Fragment[], offsets: number[]) { const starts = offsets.map((offset, frame) => { @@ -119,12 +113,11 @@ export function splitEncapsulatedFrames(value: Uint8Array, frameCount: number) { const items = readItems(value); if (items.length === 0) throw malformed('no Basic Offset Table item'); const [table, ...rest] = items; - const base = rest[0]?.position ?? 0; + if (rest.length === 0) throw malformed('no fragments'); const fragments = rest.map(({ position, bytes }) => ({ - offset: position - base, + offset: position - rest[0].position, bytes, })); - if (fragments.length === 0) throw malformed('no fragments'); const offsets = readOffsetTable(table.bytes); const frames = offsets.length === frameCount diff --git a/packages/dicom/core/runtime/__tests__/requestPool.spec.ts b/packages/dicom/core/runtime/__tests__/requestPool.spec.ts index 8ef50ca45..653db1a0c 100644 --- a/packages/dicom/core/runtime/__tests__/requestPool.spec.ts +++ b/packages/dicom/core/runtime/__tests__/requestPool.spec.ts @@ -1,22 +1,11 @@ import { RequestPool } from '../requestPool'; import { describe, it, expect } from 'vitest'; -const abortableFetch = async ( - _input: RequestInfo | URL, - init?: RequestInit -) => { - return new Promise((_resolve, reject) => { - if (init?.signal) { - if (init.signal.aborted) { - reject(init.signal.reason); - return; - } - init.signal.addEventListener('abort', () => { - reject(init.signal!.reason); - }); - } +/** A fetch that never answers and rejects once its request is aborted. */ +const abortableFetch = (_input: RequestInfo | URL, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)); }); -}; describe('requestPool', () => { it('should not have more active requests than the pool size', () => { @@ -36,7 +25,7 @@ describe('requestPool', () => { const N = 4; const pool = new RequestPool(N, abortableFetch); const controllers: AbortController[] = []; - const promises: Promise[] = []; + const promises: Promise[] = []; for (let i = 0; i < 10; i++) { const controller = new AbortController(); diff --git a/packages/dicom/core/runtime/requestPool.ts b/packages/dicom/core/runtime/requestPool.ts index 167945829..d4313d830 100644 --- a/packages/dicom/core/runtime/requestPool.ts +++ b/packages/dicom/core/runtime/requestPool.ts @@ -87,6 +87,7 @@ export class RequestPool { private async startRequest(request: FetchRequest) { this.inflight.add(request); try { + // Called unbound: a native fetch rejects any other `this`. const fetchFn = this.fetchFn; const response = await fetchFn(request.request, { ...request.init, diff --git a/packages/dicom/core/source/__tests__/byteSource.spec.ts b/packages/dicom/core/source/__tests__/byteSource.spec.ts index 44789b7ec..4b1359c23 100644 --- a/packages/dicom/core/source/__tests__/byteSource.spec.ts +++ b/packages/dicom/core/source/__tests__/byteSource.spec.ts @@ -25,53 +25,79 @@ type ServerOptions = { contentRange?: string; }; -/** A fetch that serves `bytes` in 64-byte chunks and records what it was asked. */ +/** The span a server answers a Range header with, or null for the whole body. */ +const answeredSpan = ( + range: string | null, + { honorRange = true, startShift = 0 }: ServerOptions +) => { + const match = range?.match(/^bytes=(\d+)-(\d*)$/); + if (!honorRange || !match) return null; + return { + start: Number(match[1]) + startShift, + end: match[2] ? Number(match[2]) + 1 : bytes.length, + }; +}; + +/** `bytes[start, end)` in 64-byte chunks, flagging `body` when cancelled. */ +const chunkedBody = ( + start: number, + end: number, + body: { cancelled: boolean } +) => { + let offset = start; + return new ReadableStream({ + pull: (controller) => { + if (offset >= end) { + controller.close(); + return; + } + controller.enqueue(bytes.slice(offset, Math.min(end, offset + 64))); + offset += 64; + }, + cancel: () => { + body.cancelled = true; + }, + }); +}; + +/** A fetch that serves `bytes` and records what it was asked. */ const server = (options: ServerOptions = {}) => { - const { honorRange = true, exposeContentRange = true, status } = options; - const { startShift = 0, contentRange } = options; + const { exposeContentRange = true, status, contentRange } = options; const requests: Array = []; const caches: Array = []; const signals: Array = []; const bodies: Array<{ cancelled: boolean }> = []; - const fetchFn: typeof fetch = async (_input, init) => { - const range = new Headers(init?.headers).get('Range'); + const fetchFn: typeof fetch = async (_input, init = {}) => { + const range = new Headers(init.headers).get('Range'); requests.push(range); - caches.push(init?.cache); - signals.push(init?.signal); - const match = range?.match(/^bytes=(\d+)-(\d*)$/); - const partial = honorRange && match !== null && match !== undefined; - const start = partial ? Number(match[1]) + startShift : 0; - const end = partial && match[2] ? Number(match[2]) + 1 : bytes.length; + caches.push(init.cache); + signals.push(init.signal); + const span = answeredSpan(range, options); + const { start, end } = span ?? { start: 0, end: bytes.length }; const body = { cancelled: false }; bodies.push(body); - let offset = start; - const stream = new ReadableStream({ - pull: (controller) => { - if (offset >= end) { - controller.close(); - return; - } - controller.enqueue(bytes.slice(offset, Math.min(end, offset + 64))); - offset += 64; - }, - cancel: () => { - body.cancelled = true; - }, - }); const headers = new Headers({ 'content-length': String(end - start) }); - if (partial && exposeContentRange) + if (span && exposeContentRange) headers.set( 'content-range', contentRange ?? `bytes ${start}-${end - 1}/${bytes.length}` ); - return new Response(stream, { - status: status ?? (partial ? 206 : 200), + return new Response(chunkedBody(start, end, body), { + status: status ?? (span ? 206 : 200), headers, }); }; return { fetch: fetchFn, requests, caches, bodies, signals }; }; +const urlSource = (options?: ServerOptions) => { + const http = server(options); + return { + http, + source: fromUrl('https://example.test/a.dcm', { fetch: http.fetch }), + }; +}; + const signal = () => new AbortController().signal; describe('blob byte source', () => { @@ -127,8 +153,7 @@ describe('blob byte source', () => { describe('URL byte source', () => { it('reads the whole resource without a Range header', async () => { - const http = server(); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { http, source } = urlSource(); expect(await readStream(source.read(signal()))).toEqual(bytes); expect(http.requests).toEqual([null]); }); @@ -138,8 +163,7 @@ describe('URL byte source', () => { ['hides Content-Range from CORS', { exposeContentRange: false }], ['ignores Range and answers 200', { honorRange: false }], ])('reads a range when the server %s', async (_name, options) => { - const http = server(options); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { http, source } = urlSource(options); const bounded = await readStream( source.read(signal(), { start: 100, end: 300 }) @@ -157,10 +181,7 @@ describe('URL byte source', () => { ])( 'reports a server that honours Range (%s) as %s, bypassing the HTTP cache for ranges', async (honorRange, support) => { - const http = server({ honorRange }); - const source = fromUrl('https://example.test/a.dcm', { - fetch: http.fetch, - }); + const { http, source } = urlSource({ honorRange }); expect(source.rangeSupport?.()).toBe('unknown'); await readStream(source.read(signal())); expect(source.rangeSupport?.()).toBe('unknown'); @@ -171,23 +192,20 @@ describe('URL byte source', () => { ); it('stops the ignored-Range body once the range is read', async () => { - const http = server({ honorRange: false }); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { http, source } = urlSource({ honorRange: false }); await readStream(source.read(signal(), { start: 0, end: 10 })); expect(http.bodies[0].cancelled).toBe(true); }); it('opens a fresh request for every read', async () => { - const http = server(); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { http, source } = urlSource(); await readStream(source.read(signal(), { start: 0, end: 4 })); await readStream(source.read(signal(), { start: 0, end: 4 })); expect(http.requests).toHaveLength(2); }); it('reads a range from a 206 that starts before it', async () => { - const http = server({ startShift: -50 }); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { source } = urlSource({ startShift: -50 }); expect( await readStream(source.read(signal(), { start: 100, end: 300 })) ).toEqual(expected({ start: 100, end: 300 })); @@ -201,16 +219,14 @@ describe('URL byte source', () => { /Invalid content-range/, ], ])('fails a 206 that %s', async (_name, options, message) => { - const http = server(options); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { source } = urlSource(options); await expect( readStream(source.read(signal(), { start: 100, end: 300 })) ).rejects.toThrow(message); }); it('aborts its request once the body is read to the end', async () => { - const http = server(); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { http, source } = urlSource(); await readStream(source.read(signal(), { start: 0, end: 10 })); expect(http.signals[0]?.aborted).toBe(true); }); @@ -221,16 +237,14 @@ describe('URL byte source', () => { [500, /HTTP 500/], [416, /Range could not be satisfied/], ])('fails a %i response', async (status, message) => { - const http = server({ status }); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { source } = urlSource({ status }); await expect( readStream(source.read(signal(), { start: 0, end: 4 })) ).rejects.toThrow(message); }); it('cancels the response body when the reader cancels', async () => { - const http = server(); - const source = fromUrl('https://example.test/a.dcm', { fetch: http.fetch }); + const { http, source } = urlSource(); const reader = source.read(signal()).getReader(); await reader.read(); await reader.cancel(); diff --git a/packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts b/packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts index 7f0837449..ee149d52a 100644 --- a/packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts +++ b/packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts @@ -2,45 +2,25 @@ import { parseContentRangeHeader } from '../parseContentRangeHeader'; import { describe, expect, it } from 'vitest'; describe('parseContentRangeHeader', () => { - it('should handle valid ranges', () => { - let range = parseContentRangeHeader('bytes 0-1/123'); - expect(range.type).toEqual('range'); - if (range.type !== 'range') return; // ts can't narrow on expect() - - expect(range.start).toEqual(0); - expect(range.end).toEqual(1); - expect(range.length).toEqual(123); - - range = parseContentRangeHeader('bytes 2-5/*'); - expect(range.type).toEqual('range'); - if (range.type !== 'range') return; // ts can't narrow on expect() - - expect(range.start).toEqual(2); - expect(range.end).toEqual(5); - expect(range.length).to.be.null; - }); - - it('should handle unsatisfied ranges', () => { - const range = parseContentRangeHeader('bytes */12'); - expect(range.type).toEqual('unsatisfied-range'); - if (range.type !== 'unsatisfied-range') return; // ts can't narrow on expect() - - expect(range.length).toEqual(12); + it.each([ + ['bytes 0-1/123', { type: 'range', start: 0, end: 1, length: 123 }], + ['bytes 2-5/*', { type: 'range', start: 2, end: 5, length: null }], + ])('reads %s', (header, range) => { + expect(parseContentRangeHeader(header)).toEqual(range); }); - it('should handle invalid ranges', () => { - [ - '', - 'bytes', - 'bytes */*', - 'byte 0-1/2', - 'bytes 1-0/2', - 'bytes 0-1/1', - 'bytes 1-3/2', - 'bytes 1-/2', - 'bytes -1/2', - ].forEach((range) => { - expect(parseContentRangeHeader(range).type).toEqual('invalid-range'); - }); + it.each([ + '', + 'bytes', + 'bytes */12', + 'bytes */*', + 'byte 0-1/2', + 'bytes 1-0/2', + 'bytes 0-1/1', + 'bytes 1-3/2', + 'bytes 1-/2', + 'bytes -1/2', + ])('rejects %j', (header) => { + expect(parseContentRangeHeader(header)).toEqual({ type: 'invalid-range' }); }); }); diff --git a/packages/dicom/core/source/byteSource.ts b/packages/dicom/core/source/byteSource.ts index 01f4d4f63..b93e60d16 100644 --- a/packages/dicom/core/source/byteSource.ts +++ b/packages/dicom/core/source/byteSource.ts @@ -1,11 +1,10 @@ -import { - HTTP_STATUS_OK, - HTTP_STATUS_PARTIAL_CONTENT, - HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE, -} from './httpCodes'; import { concatBytes, linkedController } from '../utils'; import { parseContentRangeHeader } from './parseContentRangeHeader'; +const HTTP_STATUS_OK = 200; +const HTTP_STATUS_PARTIAL_CONTENT = 206; +const HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416; + /** Half-open byte interval; an absent end reads to the last byte. */ export type ByteRange = { start: number; end?: number }; diff --git a/packages/dicom/core/source/httpCodes.ts b/packages/dicom/core/source/httpCodes.ts deleted file mode 100644 index c395609a5..000000000 --- a/packages/dicom/core/source/httpCodes.ts +++ /dev/null @@ -1,3 +0,0 @@ -export const HTTP_STATUS_OK = 200; -export const HTTP_STATUS_PARTIAL_CONTENT = 206; -export const HTTP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE = 416; diff --git a/packages/dicom/core/source/parseContentRangeHeader.ts b/packages/dicom/core/source/parseContentRangeHeader.ts index fc26f9eab..b43281f9c 100644 --- a/packages/dicom/core/source/parseContentRangeHeader.ts +++ b/packages/dicom/core/source/parseContentRangeHeader.ts @@ -1,31 +1,23 @@ const CONTENT_RANGE_REGEXP = - /^bytes (?(?\d+)-(?\d+)|\*)\/(?\d+|\*)$/; + /^bytes (?\d+)-(?\d+)\/(?\d+|\*)$/; -export type ContentRange = +type ContentRange = | { type: 'empty-range' } | { type: 'invalid-range' } - | { type: 'unsatisfied-range'; length: number } | { type: 'range'; start: number; end: number; length: number | null }; -/** Parses a Content-Range header. Only supports bytes ranges. */ +/** Parses a 206 response's Content-Range, where an unsatisfied `*` range is invalid. */ export function parseContentRangeHeader( headerValue: string | null ): ContentRange { if (headerValue == null) return { type: 'empty-range' }; - const match = CONTENT_RANGE_REGEXP.exec(headerValue); - const groups = match?.groups; + const groups = CONTENT_RANGE_REGEXP.exec(headerValue)?.groups; if (!groups) return { type: 'invalid-range' }; - const length = groups.length === '*' ? null : parseInt(groups.length, 10); - - if (groups.range === '*') { - if (length === null) return { type: 'invalid-range' }; - return { type: 'unsatisfied-range', length }; - } - const start = parseInt(groups.start, 10); const end = parseInt(groups.end, 10); + const length = groups.length === '*' ? null : parseInt(groups.length, 10); if (end < start || (length !== null && length <= end)) return { type: 'invalid-range' }; diff --git a/packages/dicom/core/utils.ts b/packages/dicom/core/utils.ts index a7de0f0f9..eb9801381 100644 --- a/packages/dicom/core/utils.ts +++ b/packages/dicom/core/utils.ts @@ -1,4 +1,5 @@ export type Awaitable = T | Promise; + /** Boundary padding accepted by numeric readers, without changing the stored text. */ export const trimDicomPadding = (value: string) => value.replace(/^[\s\0]+|[\s\0]+$/g, ''); @@ -17,27 +18,13 @@ export function concatBytes( return out; } -export function toAscii( - bytes: Uint8Array | Uint8ClampedArray, - { ignoreNulls = false } = {} -) { - const chars = []; - for (let i = 0; i < bytes.length; i++) { - if (!(ignoreNulls && bytes[i] === 0)) { - chars.push(String.fromCharCode(bytes[i])); - } - } - return chars.join(''); -} +export const toAscii = (bytes: Uint8Array, { ignoreNulls = false } = {}) => + Array.from(ignoreNulls ? bytes.filter((byte) => byte !== 0) : bytes, (byte) => + String.fromCharCode(byte) + ).join(''); -/** - * Wraps a generator as a coroutine. - * @param generator - * @param args - * @returns - */ +/** Starts a generator and returns a function that feeds it one value per step. */ export function asCoroutine(gen: Generator) { - // run initial code const result = gen.next(); if (result.done) return () => result; return (value: N): IteratorResult => gen.next(value); diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts index 588c8205d..0fa8705f1 100644 --- a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest'; -import { instanceFor } from '@/tests/dicomDataset'; import { allocateVolume } from '../allocateVolume'; import { allocated, pixelSlice } from './volumeFixture'; import { plannedUpdate } from '@/tests/dicomVolumeFixtures'; @@ -68,9 +67,8 @@ describe('allocateVolume', () => { }); it('applies the first ultrasound region as display spacing', () => { - const { dataset, source } = pixelSlice(0, { modality: 'US' }); const ultrasound = { - ...instanceFor(dataset, source), + ...pixelSlice(0, { modality: 'US' }), ultrasoundRegions: { regionCount: 1, region: { diff --git a/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts b/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts index 4eb322db1..262045596 100644 --- a/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts +++ b/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts @@ -204,13 +204,12 @@ describe('enhanced volume Functional Groups', () => { 'preserves stored frame direction %s through registration and image allocation', (direction) => { const positions = [0, 1, 2].map((index) => 10 + direction * index * 3); - const instance = instanceFor( + const volume = allocate( enhanced( ctShared(), positions.map((z) => positioned(`1\\2\\${z}`)) ) ); - const volume = allocateVolume(plannedUpdate([instance])); expect(volume.spacing[2]).toBe(3); positions.forEach((z, index) => expect(indexToWorld(volume, [0, 0, index])).toEqual([1, 2, z]) diff --git a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts index 871e7f476..5cf274515 100644 --- a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -403,17 +403,11 @@ describe('loadVolume with native frames', () => { const { volume, updates } = await load([instance], { runtime }); - expect(updates).toEqual([ - { - slot: 0, - extent: [0, 2, 0, 1, 0, FRAMES - 1], - error: expect.objectContaining({ - message: expect.stringMatching( - /^Partial codec planned units that do not cover frames 0 to 4 of File .* exactly once$/ - ), - }), - }, - ]); + expect(updates).toEqual( + failsWhole( + /^Partial codec planned units that do not cover frames 0 to 4 of File .* exactly once$/ + ) + ); expect(ranges).toEqual([undefined]); expect(volume.loaded).toEqual(new Uint8Array(FRAMES)); } diff --git a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts index 8c7fba876..64930112c 100644 --- a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts +++ b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts @@ -8,7 +8,7 @@ import { reconstructVolume } from '../../collections/reconstructVolume'; import { Tags } from '../../metadata/dicomTags'; import { volumeLayout, type VolumeSource } from '../volumeLayout'; -function volumeSource(overrides: Record = {}): VolumeSource { +function volumeSource(overrides: Record = {}) { const metadata = { [Tags.SOPInstanceUID]: '1.2.3', [Tags.ImagePositionPatient]: '0\\0\\0', @@ -41,7 +41,7 @@ function layoutOf(sources: VolumeSource[], orientation: number[] | null) { return volumeLayout(sources, orientation, reconstruction); } -const spacingOf = (layout: ReturnType) => +const spacingOf = (layout: ReturnType) => layout.spatialMetadata.axes.map((axis) => axis.value); const dimensionsOf = ({ @@ -174,19 +174,4 @@ describe('volumeLayout', () => { expect(spacingOf(layout)[2]).toBe(2.5); }); - - it('takes the declared SpacingBetweenSlices for a multi-frame instance', () => { - const layout = layoutOf( - [ - volumeSource({ - [Tags.NumberOfFrames]: '4', - [Tags.SpacingBetweenSlices]: '1.5', - }), - ], - AXIAL - ); - - expect(dimensionsOf(layout)).toEqual([4, 3, 4]); - expect(spacingOf(layout)[2]).toBe(1.5); - }); }); diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts index cb9e65415..92de8da4a 100644 --- a/packages/dicom/core/volume/allocateVolume.ts +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -4,7 +4,8 @@ import type { SpatialMetadata } from '../metadata/spatialMetadata'; import type { VolumeBuffer } from './pixelFormat'; import { planVolumeAllocation } from './volumeLayout'; -type Vector3 = readonly [number, number, number]; +type Triple = [number, number, number]; +type Vector3 = Readonly; /** * One buffer plus the geometry that places it. Everything is immutable except @@ -100,11 +101,9 @@ export function allocateVolume( members: Object.freeze([...members]), dimensions: [columns, rows, slices] as const, components: samplesPerPixel, - origin: (layout.origin ?? [0, 0, 0]) as unknown as Vector3, + origin: (layout.origin ?? [0, 0, 0]) as Triple, direction: layout.direction ?? IDENTITY, - spacing: layout.spatialMetadata.axes.map( - (axis) => axis.value - ) as unknown as Vector3, + spacing: layout.spatialMetadata.axes.map((axis) => axis.value) as Triple, spatialMetadata: layout.spatialMetadata, warnings, data: new layout.bufferType(columns * rows * slices * samplesPerPixel), diff --git a/packages/dicom/core/volume/loadVolume.ts b/packages/dicom/core/volume/loadVolume.ts index 781a0984c..8b46b23ee 100644 --- a/packages/dicom/core/volume/loadVolume.ts +++ b/packages/dicom/core/volume/loadVolume.ts @@ -410,12 +410,12 @@ function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { /** * Decodes the slices not yet loaded, the focused slot first and then coarse * to fine, writing each into the volume's buffer as it decodes and marking it - * loaded as its update is yielded. Each instance loads in the - * units its first willing decoder in the runtime's table plans. Reads run - * ahead of decoding in the same order. A failed unit yields an error update - * and loading goes on. Aborting `signal`, disposing the runtime or leaving - * the loop stops reads and decodes; the iteration then returns rather than - * throwing, and yields nothing more. + * loaded as its update is yielded. Each instance loads in the units its first + * willing decoder in the runtime's table plans. Reads run ahead of decoding in + * the same order. A failed unit yields an error update and loading goes on. + * Aborting `signal`, disposing the runtime or leaving the loop stops reads and + * decodes; the iteration then returns rather than throwing, and yields + * nothing more. */ export async function* loadVolume( volume: Volume, @@ -425,7 +425,7 @@ export async function* loadVolume( focus = () => middleSlot(volume), readAhead = runtime.readConcurrency, }: LoadVolumeOptions -): AsyncGenerator { +) { if (!Number.isInteger(readAhead) || readAhead < 1) throw new Error('Read ahead must be a positive integer'); const { controller, release } = linkedController(signal, runtime.signal); diff --git a/packages/dicom/core/volume/nmGeometry.ts b/packages/dicom/core/volume/nmGeometry.ts index ce72c16eb..1302687d7 100644 --- a/packages/dicom/core/volume/nmGeometry.ts +++ b/packages/dicom/core/volume/nmGeometry.ts @@ -1,6 +1,6 @@ -import { DicomDataset } from '../metadata/dicomDataset'; +import type { DicomDataset } from '../metadata/dicomDataset'; import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; -import { type Reconstruction } from '../collections/reconstructVolume'; +import type { Reconstruction } from '../collections/reconstructVolume'; import { readNmReconstruction } from '../metadata/nmReconstruction'; export function nmGeometry(metadata: DicomDataset) { diff --git a/packages/dicom/core/volume/pixelFormat.ts b/packages/dicom/core/volume/pixelFormat.ts index 224eb0cf9..7a5705f5b 100644 --- a/packages/dicom/core/volume/pixelFormat.ts +++ b/packages/dicom/core/volume/pixelFormat.ts @@ -19,11 +19,11 @@ export type VolumeBufferConstructor = | typeof Float64Array; export type VolumeBuffer = InstanceType; +export type ValueRange = { min: number; max: number }; +export type Rescale = { rescaleSlope: number; rescaleIntercept: number }; + // In the order a range is matched: unsigned before signed, narrow before wide. -const INTEGER_VALUE_RANGES = new Map< - IntegerArrayConstructor, - { min: number; max: number } ->([ +const INTEGER_VALUE_RANGES = new Map([ [Uint8Array, { min: 0, max: 2 ** 8 - 1 }], [Uint16Array, { min: 0, max: 2 ** 16 - 1 }], [Uint32Array, { min: 0, max: 2 ** 32 - 1 }], @@ -46,13 +46,12 @@ export function getBufferValueRange(buffer: ArrayBufferView) { * Whether a decoded value range is representable in `buffer`'s element type. * A buffer with no enforceable range accepts everything. */ -export function valuesFitBuffer( - range: { min: number; max: number }, - buffer: ArrayBufferView -) { +export function valuesFitBuffer(range: ValueRange, buffer: ArrayBufferView) { const bufferRange = getBufferValueRange(buffer); - if (!bufferRange) return true; - return range.min >= bufferRange.min && range.max <= bufferRange.max; + return ( + !bufferRange || + (range.min >= bufferRange.min && range.max <= bufferRange.max) + ); } /** @@ -121,42 +120,31 @@ const FLOAT32_EXACT_INTEGER = 2 ** 24; const FLOAT32_RELATIVE_STEP = 2 ** -23; const FLOAT32_MAX_BITS_STORED = 24; -const magnitude = ({ min, max }: { min: number; max: number }) => +const magnitude = ({ min, max }: ValueRange) => Math.max(Math.abs(min), Math.abs(max)); -const isIntegralRescale = (format: { - rescaleSlope: number; - rescaleIntercept: number; -}) => +const isIntegralRescale = (format: Rescale) => Number.isInteger(format.rescaleSlope) && Number.isInteger(format.rescaleIntercept); /** Float32 holds every integer up to 2^24 exactly. */ -const float32KeepsIntegers = (range: { min: number; max: number }) => +const float32KeepsIntegers = (range: ValueRange) => magnitude(range) <= FLOAT32_EXACT_INTEGER; /** Float32's spacing near `range` stays below one stored step of `slope`. */ -const float32KeepsSteps = ( - range: { min: number; max: number }, - slope: number -) => slope !== 0 && magnitude(range) * FLOAT32_RELATIVE_STEP < Math.abs(slope); +const float32KeepsSteps = (range: ValueRange, slope: number) => + slope !== 0 && magnitude(range) * FLOAT32_RELATIVE_STEP < Math.abs(slope); /** * Whether a float32 buffer holds `range` as the rescale requires: integral * values exactly, fractional ones with adjacent stored steps kept apart. */ -export const float32Holds = ( - range: { min: number; max: number }, - format: { rescaleSlope: number; rescaleIntercept: number } -) => +export const float32Holds = (range: ValueRange, format: Rescale) => isIntegralRescale(format) ? float32KeepsIntegers(range) : float32KeepsSteps(range, format.rescaleSlope); -type UsableFormat = { - format: PixelFormat; - range: { min: number; max: number }; -}; +type UsableFormat = { format: PixelFormat; range: ValueRange }; function fractionalBufferType(usable: UsableFormat[]) { return usable.every( diff --git a/packages/dicom/core/volume/pixelValidation.ts b/packages/dicom/core/volume/pixelValidation.ts index c94ec69bd..49bffd86e 100644 --- a/packages/dicom/core/volume/pixelValidation.ts +++ b/packages/dicom/core/volume/pixelValidation.ts @@ -3,10 +3,15 @@ import { getBufferValueRange, valuesFitBuffer, samplesAreIntegral, + type Rescale, + type ValueRange, } from './pixelFormat'; +const UNCONVERTED = + 'Every file in a volume must decode to values its buffer can hold without conversion.'; + /** What a unit decodes to, or what its header says it will. */ -export type UnitShape = Readonly<{ +type UnitShape = Readonly<{ size: readonly number[]; components: number; samples: number; @@ -14,7 +19,7 @@ export type UnitShape = Readonly<{ export function assertSamplesRepresentable( decoded: ArrayLike, - range: { min: number; max: number }, + range: ValueRange, buffer: ArrayBufferView, { where, @@ -22,10 +27,7 @@ export function assertSamplesRepresentable( }: { where: string; /** Every frame calibration the samples went through; read only for Float32. */ - rescales: () => ReadonlyArray<{ - rescaleSlope: number; - rescaleIntercept: number; - }>; + rescales: () => readonly Rescale[]; } ) { const unheld = @@ -37,7 +39,7 @@ export function assertSamplesRepresentable( `${where} has pixel values the volume it belongs to cannot represent. ` + `Its pixel values run from ${range.min} to ${range.max} with a rescale slope of ${unheld.rescaleSlope}, ` + `but the volume's buffer is Float32Array, which would merge or round values of that size. ` + - `Every file in a volume must decode to values its buffer can hold without conversion.` + UNCONVERTED ); } if (!valuesFitBuffer(range, buffer)) { @@ -46,7 +48,7 @@ export function assertSamplesRepresentable( `${where} has pixel values the volume it belongs to cannot represent. ` + `Its pixel values run from ${range.min} to ${range.max}, but the volume's buffer is ` + `${buffer.constructor.name}, holding values from ${bufferRange.min} to ${bufferRange.max}. ` + - `Every file in a volume must decode to values its buffer can hold without conversion.` + UNCONVERTED ); } if (!samplesAreIntegral(decoded, buffer)) { @@ -54,7 +56,7 @@ export function assertSamplesRepresentable( `${where} has fractional pixel values the volume it belongs to cannot represent. ` + `Its pixel values run from ${range.min} to ${range.max}, but the volume's buffer is ` + `${buffer.constructor.name}, which holds only whole numbers. ` + - `Every file in a volume must decode to values its buffer can hold without conversion.` + UNCONVERTED ); } } diff --git a/packages/dicom/vtk/__tests__/thumbnail.spec.ts b/packages/dicom/vtk/__tests__/thumbnail.spec.ts index 66e827c41..0c79597fb 100644 --- a/packages/dicom/vtk/__tests__/thumbnail.spec.ts +++ b/packages/dicom/vtk/__tests__/thumbnail.spec.ts @@ -71,20 +71,6 @@ describe('sliceToThumbnail', () => { expect(bytes(slice).slice(0, 4)).toEqual([0, 2, 4, 6]); }); - it('keeps every sample of a slice that already fits', () => { - const slice = sliceToThumbnail({ - data: [0, 1, 2, 3], - width: 2, - height: 2, - components: 1, - range: [0, 3], - }); - - expect(slice.width).toBe(2); - expect(slice.height).toBe(2); - expect(slice.data).toHaveLength(4); - }); - it('samples RGB luminance for color slices', () => { const slice = sliceToThumbnail({ data: [255, 0, 0, 0, 255, 0, 0, 0, 255], diff --git a/packages/dicom/vtk/__tests__/volumeImage.spec.ts b/packages/dicom/vtk/__tests__/volumeImage.spec.ts index fad7666b3..b67e5cc25 100644 --- a/packages/dicom/vtk/__tests__/volumeImage.spec.ts +++ b/packages/dicom/vtk/__tests__/volumeImage.spec.ts @@ -26,6 +26,18 @@ const rangeOf = (image: vtkImageData) => [ ...image.getPointData().getScalars().getRange(0), ]; +const rgbImage = (dimensions: [number, number, number], values: number[]) => { + const image = vtkImageData.newInstance(); + image.setDimensions(dimensions); + image.getPointData().setScalars( + vtkDataArray.newInstance({ + numberOfComponents: 3, + values: new Uint8Array(values), + }) + ); + return image; +}; + /** Loads one slice at a time, recording the scalar range after each update. */ async function loadRanges(volume: Volume) { const image = toVtkImageData(volume); @@ -110,29 +122,16 @@ describe('vtk volume adapter', () => { }); it('shows green and blue pixels of an RGB slice as luminance', () => { - const image = vtkImageData.newInstance(); - image.setDimensions(3, 1, 1); - image.getPointData().setScalars( - vtkDataArray.newInstance({ - numberOfComponents: 3, - values: new Uint8Array([0, 0, 0, 0, 255, 0, 0, 0, 255]), - }) - ); + const image = rgbImage([3, 1, 1], [0, 0, 0, 0, 255, 0, 0, 0, 255]); expect(Array.from(sliceThumbnail(image, 0).data)).toEqual([0, 255, 50]); image.delete(); }); it('windows a color slice to its own luminance, whatever the other slices hold', () => { - const image = vtkImageData.newInstance(); - image.setDimensions(2, 1, 2); - image.getPointData().setScalars( - vtkDataArray.newInstance({ - numberOfComponents: 3, - values: new Uint8Array([ - 0, 0, 0, 100, 100, 100, 255, 255, 255, 0, 0, 0, - ]), - }) + const image = rgbImage( + [2, 1, 2], + [0, 0, 0, 100, 100, 100, 255, 255, 255, 0, 0, 0] ); expect(Array.from(sliceThumbnail(image, 0).data)).toEqual([0, 255]); diff --git a/packages/dicom/vtk/thumbnail.ts b/packages/dicom/vtk/thumbnail.ts index 319f88737..4f8523c38 100644 --- a/packages/dicom/vtk/thumbnail.ts +++ b/packages/dicom/vtk/thumbnail.ts @@ -47,7 +47,7 @@ export function sliceToThumbnail({ height, components, range, -}: SliceToThumbnailInput): ThumbnailSlice { +}: SliceToThumbnailInput) { const [low, high] = range; const span = high - low; diff --git a/src/components/ImageSpacingDetails.vue b/src/components/ImageSpacingDetails.vue index 05da6ab11..d94d07274 100644 --- a/src/components/ImageSpacingDetails.vue +++ b/src/components/ImageSpacingDetails.vue @@ -4,15 +4,15 @@ import { useImageCacheStore } from '@/src/store/image-cache'; const imageID = defineModel({ required: true }); const cache = useImageCacheStore(); -const image = computed(() => cache.getImageMetadata(imageID.value)); -const spatial = computed(() => image.value?.spatialMetadata); +const metadata = computed(() => cache.getImageMetadata(imageID.value)); +const spatial = computed(() => metadata.value?.spatialMetadata); const rows = computed( () => spatial.value?.axes.map((axis, index) => ({ ...axis, label: ['X', 'Y', 'Z'][index], value: Number(axis.value.toPrecision(7)).toString(), - singleton: image.value?.dimensions[index] === 1, + singleton: metadata.value?.dimensions[index] === 1, })) ?? [] ); const statuses = { diff --git a/src/components/PatientStudyVolumeBrowser.vue b/src/components/PatientStudyVolumeBrowser.vue index 572d5d60c..14c3c6bb7 100644 --- a/src/components/PatientStudyVolumeBrowser.vue +++ b/src/components/PatientStudyVolumeBrowser.vue @@ -130,31 +130,23 @@ export default defineComponent({ volumeKeys.value.includes(key) && imageCacheStore.imageById[key] === image && dicomStore.volumeInfo[key] === info; + const modality: Thumbnail = { kind: 'text', value: info.Modality }; try { const thumb = await image.getThumbnail(); if (!isCurrent()) return; - if (thumb) { - thumbnailCache[cacheKey] = { kind: 'image', value: thumb }; - } else { - thumbnailCache[cacheKey] = { - kind: 'text', - value: info.Modality, - }; - } + thumbnailCache[cacheKey] = thumb + ? { kind: 'image', value: thumb } + : modality; } catch (err) { if (!isCurrent()) return; if (err instanceof Error && err.name !== 'AbortError') { - const messageStore = useMessageStore(); - messageStore.addError('Failed to generate thumbnails', { + useMessageStore().addError('Failed to generate thumbnails', { error: err, details: `${err}. More details can be found in the developer's console.`, }); } - thumbnailCache[cacheKey] = { - kind: 'text', - value: info.Modality, - }; + thumbnailCache[cacheKey] = modality; } }); diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index 709a80f38..c7da41c37 100644 --- a/src/core/cine/DicomCineImage.ts +++ b/src/core/cine/DicomCineImage.ts @@ -33,6 +33,10 @@ import { decodeNativeFrame, } from './frameCache'; +const REGION_SOURCE = 'Ultrasound region (cm converted to mm)'; +const NO_SPACING = + 'No usable spatial ultrasound region or PixelSpacing is supplied.'; + function spatialRegionSpacing(r: CineHeader['regions'][number]) { const sx = unitToMm(r.physicalUnitsXDirection); const sy = unitToMm(r.physicalUnitsYDirection); @@ -40,14 +44,8 @@ function spatialRegionSpacing(r: CineHeader['regions'][number]) { const { physicalDeltaX: dx, physicalDeltaY: dy } = r; if (!dx || !dy || !Number.isFinite(dx) || !Number.isFinite(dy)) return null; return [ - physicalSpacing( - Math.abs(dx) * sx, - 'Ultrasound region (cm converted to mm)' - ), - physicalSpacing( - Math.abs(dy) * sy, - 'Ultrasound region (cm converted to mm)' - ), + physicalSpacing(Math.abs(dx) * sx, REGION_SOURCE), + physicalSpacing(Math.abs(dy) * sy, REGION_SOURCE), ] as const; } @@ -55,16 +53,16 @@ function pickSpacing(header: CineHeader): SpatialMetadata { const z = fallbackSpacing( 'Cine frames share one image plane; this is not a spatial frame step.' ); - for (const r of header.regions) { - const spacing = spatialRegionSpacing(r); - if (!spacing) continue; + const regionSpacing = header.regions + .map(spatialRegionSpacing) + .find((spacing) => spacing !== null); + if (regionSpacing) return { - axes: [...spacing, z], + axes: [...regionSpacing, z], notes: [ 'Physical spacing applies within the first spatial ultrasound region, not necessarily the entire image.', ], }; - } if (header.pixelSpacing) { const [rowSpacing, columnSpacing] = header.pixelSpacing; @@ -79,15 +77,7 @@ function pickSpacing(header: CineHeader): SpatialMetadata { } return { - axes: [ - fallbackSpacing( - 'No usable spatial ultrasound region or PixelSpacing is supplied.' - ), - fallbackSpacing( - 'No usable spatial ultrasound region or PixelSpacing is supplied.' - ), - z, - ], + axes: [fallbackSpacing(NO_SPACING), fallbackSpacing(NO_SPACING), z], notes: [], }; } diff --git a/src/core/cine/__tests__/DicomCineImage.spec.ts b/src/core/cine/__tests__/DicomCineImage.spec.ts index ac38e8a78..543330540 100644 --- a/src/core/cine/__tests__/DicomCineImage.spec.ts +++ b/src/core/cine/__tests__/DicomCineImage.spec.ts @@ -55,6 +55,25 @@ const load = (image: DicomCineImage) => { const scalarsOf = (image: DicomCineImage) => Array.from(image.getVtkImageData().getPointData().getScalars().getData()); +/** A clip whose first pixel read fails and whose later reads succeed. */ +const offlineOnce = () => { + const pixels = fromBlob( + new Blob([Uint8Array.from([9, 9, 9, 9, 8, 8, 8, 8])]) + ); + let reads = 0; + const source: ByteSource = { + read: (signal, range) => { + reads += 1; + if (reads === 1) + return new ReadableStream({ + start: (controller) => controller.error(new Error('offline')), + }); + return pixels.read(signal, range); + }, + }; + return { ...cineInstance(), source }; +}; + describe('DicomCineImage spacing', () => { it('uses the first spatial 2D ultrasound region instead of the first region overall', () => { const image = new DicomCineImage( @@ -145,21 +164,7 @@ describe('DicomCineImage loading', () => { }); it('reads the pixels again when a load is retried after a failed read', async () => { - const pixels = fromBlob( - new Blob([Uint8Array.from([9, 9, 9, 9, 8, 8, 8, 8])]) - ); - const reads: AbortSignal[] = []; - const source: ByteSource = { - read: (signal, range) => { - reads.push(signal); - if (reads.length === 1) - return new ReadableStream({ - start: (controller) => controller.error(new Error('offline')), - }); - return pixels.read(signal, range); - }, - }; - const image = new DicomCineImage({ ...cineInstance(), source }); + const image = new DicomCineImage(offlineOnce()); expect((await load(image)).map(({ message }) => message)).toEqual([ 'offline', @@ -170,22 +175,8 @@ describe('DicomCineImage loading', () => { }); it('makes a thumbnail once a read that failed succeeds on retry', async () => { - const pixels = fromBlob( - new Blob([Uint8Array.from([9, 9, 9, 9, 8, 8, 8, 8])]) - ); - let reads = 0; - const source: ByteSource = { - read: (signal, range) => { - reads += 1; - if (reads === 1) - return new ReadableStream({ - start: (controller) => controller.error(new Error('offline')), - }); - return pixels.read(signal, range); - }, - }; const image = new DicomCineImage( - { ...cineInstance(), source }, + offlineOnce(), undefined, ({ width, height, rgb }) => `${width}x${height}:${rgb.join(',')}` ); diff --git a/src/core/cine/__tests__/cineInstance.spec.ts b/src/core/cine/__tests__/cineInstance.spec.ts index 78f951efd..05e3da59d 100644 --- a/src/core/cine/__tests__/cineInstance.spec.ts +++ b/src/core/cine/__tests__/cineInstance.spec.ts @@ -183,7 +183,7 @@ describe('readCineHeader', () => { cineInstance({ [Tags.SamplesPerPixel]: '3', [Tags.PhotometricInterpretation]: 'RGB', - '0028|0006': '1', + [Tags.PlanarConfiguration]: '1', [Tags.FrameTime]: '33.3', }) ) diff --git a/src/core/cine/cineInstance.ts b/src/core/cine/cineInstance.ts index ecc65cc1c..18be6ea1a 100644 --- a/src/core/cine/cineInstance.ts +++ b/src/core/cine/cineInstance.ts @@ -74,7 +74,6 @@ const transferSyntaxOf = (instance: Instance) => /** What a cine clip shows and plays, from the header alone. */ export function readCineHeader(instance: Instance): CineHeader { const { dataset } = instance; - const tag = (name: string) => text(dataset, name); return { transferSyntaxUID: transferSyntaxOf(instance), rows: countOr(dataset, Tags.Rows, 0), @@ -82,7 +81,7 @@ export function readCineHeader(instance: Instance): CineHeader { numberOfFrames: countOr(dataset, Tags.NumberOfFrames, 1), samplesPerPixel: countOr(dataset, Tags.SamplesPerPixel, 1), planarConfiguration: countOr(dataset, Tags.PlanarConfiguration, 0), - photometricInterpretation: tag(Tags.PhotometricInterpretation), + photometricInterpretation: text(dataset, Tags.PhotometricInterpretation), pixelSpacing: positivePair(dataset, Tags.PixelSpacing), frameTimeMs: finiteOrNull(dataset, Tags.FrameTime), regions: ultrasoundRegionsOf(dataset), diff --git a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts index 9cc62e288..d865f1c94 100644 --- a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts +++ b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts @@ -199,27 +199,23 @@ describe('DicomVolumeImage loading', () => { }); describe('DicomVolumeImage failures', () => { - async function loadRejected(dataFor: (value: number) => ArrayLike) { - const { image, errors } = holder(decodeTo(dataFor).decoder); + it('settles after rejecting decoded values its integer buffer cannot hold', async () => { + const { decoder } = decodeTo((value) => + value === 2 + ? new Uint16Array(PIXELS_PER_SLICE).fill(5000) + : new Uint8Array(PIXELS_PER_SLICE).fill(value) + ); + const { image, errors } = holder(decoder); const eightBit = { [Tags.BitsStored]: '8' }; await show(image, volumeOf([sliceAt(1, eightBit), sliceAt(2, eightBit)])); expect(image.status.value).toBe('complete'); - expect(errors).toHaveLength(1); expect(sliceOf(image, 0)).toEqual(filledWith(1)); expect(sliceOf(image, 1)).toEqual(filledWith(0)); - return errors[0].message; - } - - it('settles after rejecting decoded values its integer buffer cannot hold', async () => { - const message = await loadRejected((value) => - value === 2 - ? new Uint16Array(PIXELS_PER_SLICE).fill(5000) - : new Uint8Array(PIXELS_PER_SLICE).fill(value) - ); - expect(message).toContain('5000'); - expect(message).toContain('Uint8Array'); + expect(errors).toHaveLength(1); + expect(errors[0].message).toContain('5000'); + expect(errors[0].message).toContain('Uint8Array'); }); it('settles once every frame of a multiframe instance loaded or failed', async () => { diff --git a/src/core/streaming/cachedStreamFetcher.ts b/src/core/streaming/cachedStreamFetcher.ts index 880dc637e..f997e6071 100644 --- a/src/core/streaming/cachedStreamFetcher.ts +++ b/src/core/streaming/cachedStreamFetcher.ts @@ -1,4 +1,3 @@ -import { HTTP_STATUS_OK, HttpNotFound } from '@/src/core/streaming/httpCodes'; import type { Fetcher } from '@/src/core/streaming/types'; type FetchFunction = typeof fetch; @@ -47,8 +46,10 @@ export class CachedStreamFetcher implements Fetcher { ...this.init, signal: request.signal, }); - if (response.status !== HTTP_STATUS_OK) - throw new HttpNotFound(this.url.toString()); + if (response.status !== 200) + throw new Error( + `The following resource could not be found: ${this.url}` + ); if (!response.body) throw new Error('Did not receive a response body'); this.contentType = response.headers.get('content-type') ?? ''; this.contentDisposition = diff --git a/src/core/streaming/dicom/octMetadata.ts b/src/core/streaming/dicom/octMetadata.ts index 46a35a91f..48ba2aa0a 100644 --- a/src/core/streaming/dicom/octMetadata.ts +++ b/src/core/streaming/dicom/octMetadata.ts @@ -31,10 +31,6 @@ const ORIENTATION = '00209116'; const POSITION = '00209113'; const SCAN_PATTERN = '00221618'; const ACQUISITION_PARAMETERS = '00221640'; -const PIXEL_SPACING = Tags.PixelSpacing; -const SLICE_SPACING = Tags.SpacingBetweenSlices; -const IMAGE_ORIENTATION = Tags.ImageOrientationPatient; -const IMAGE_POSITION = Tags.ImagePositionPatient; // The attributes en face reads off an instance, beside the ones derived below. const EN_FACE_TAGS = [ Tags.Modality, @@ -68,7 +64,7 @@ function frameGeometry(data: DicomDataset) { frameAttribute(frames[0], sequence, tag) ?? stringValue(data, tag); const positions = frames.map((frame) => - vector(frameAttribute(frame, POSITION, IMAGE_POSITION)) + vector(frameAttribute(frame, POSITION, Tags.ImagePositionPatient)) ); return { frames, @@ -76,11 +72,12 @@ function frameGeometry(data: DicomDataset) { stringValue(data, Tags.NumberOfFrames) ?? '', 10 ), - orientation: attribute(ORIENTATION, IMAGE_ORIENTATION), - spacing: attribute(MEASURES, PIXEL_SPACING), + orientation: attribute(ORIENTATION, Tags.ImageOrientationPatient), + spacing: attribute(MEASURES, Tags.PixelSpacing), positions, - origin: positions[0]?.join('\\') ?? stringValue(data, IMAGE_POSITION), - sliceSpacing: attribute(MEASURES, SLICE_SPACING), + origin: + positions[0]?.join('\\') ?? stringValue(data, Tags.ImagePositionPatient), + sliceSpacing: attribute(MEASURES, Tags.SpacingBetweenSlices), }; } @@ -109,7 +106,7 @@ function positionError(geometry: ReturnType) { return 'OCT image orientation is missing; spatial reconstruction is required.'; if ( positions.length < 2 && - (geometry.declaredFrames ?? 0) > 1 && + geometry.declaredFrames > 1 && !positiveNumber(Number(geometry.sliceSpacing)) ) return 'OCT slice spacing is unavailable; spatial reconstruction is required.'; @@ -129,14 +126,19 @@ function geometryError(geometry: ReturnType) { if (origin && !finiteVector(origin, 3)) return 'DICOM slice positions are invalid; spatial reconstruction is required.'; if ( - frameAttributeMismatch(geometry, MEASURES, PIXEL_SPACING, geometry.spacing) + frameAttributeMismatch( + geometry, + MEASURES, + Tags.PixelSpacing, + geometry.spacing + ) ) return 'OCT frames have different pixel spacing; spatial reconstruction is required.'; if ( frameAttributeMismatch( geometry, MEASURES, - SLICE_SPACING, + Tags.SpacingBetweenSlices, geometry.sliceSpacing ) ) @@ -145,7 +147,7 @@ function geometryError(geometry: ReturnType) { frameAttributeMismatch( geometry, ORIENTATION, - IMAGE_ORIENTATION, + Tags.ImageOrientationPatient, geometry.orientation ) ) diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 980783c3d..8cfb2d22c 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -66,7 +66,7 @@ type Content = const readSegmentationFile = async (file: File) => { const result = await readDicomSegmentation(file); return { - image: convertItkToVtkImage(result.outputImage), + image: convertItkToVtkImage(result.segImage), metadata: result.metaInfo, }; }; @@ -124,9 +124,7 @@ export default class DicomVolumeImage extends BaseProgressiveImage { private readonly init: Required> & Pick; - public segBuildInfo: - | (JsonCompatible & ReadOverlappingSegmentationMeta) - | null = null; + public segBuildInfo: SegmentationResult['metadata'] | null = null; constructor(init: DicomVolumeImageInit = {}) { super(); @@ -193,16 +191,13 @@ export default class DicomVolumeImage extends BaseProgressiveImage { this.events.emit('error', ensureError(error)); }) .finally(() => { - if (this.load !== controller) return; - this.load = null; - this.setLoading(false); + if (this.load === controller) this.finishLoad(); }); } stopLoad() { this.load?.abort(abortError('DICOM loading stopped')); - this.load = null; - this.setLoading(false); + this.finishLoad(); } getThumbnail(): Promise { @@ -270,7 +265,6 @@ export default class DicomVolumeImage extends BaseProgressiveImage { if (previous !== image) previous.delete(); } - // Nothing is left to read, so a later startLoad may begin a retry at once. private finishLoad() { this.load = null; this.setLoading(false); @@ -318,7 +312,8 @@ export default class DicomVolumeImage extends BaseProgressiveImage { applyVolumeUpdate(image, update); this.events.emit('extentLoaded', update.extent); } - // Consumers read complete together with not loading, as one transition. + // Consumers read complete together with not loading, as one transition, + // and a later startLoad may retry at once without waiting for the reads. if (volumeSettled(content)) this.finishLoad(); this.updateStatus(); this.settleThumbnail?.(); diff --git a/src/core/streaming/httpCodes.ts b/src/core/streaming/httpCodes.ts deleted file mode 100644 index 6e45e0c9a..000000000 --- a/src/core/streaming/httpCodes.ts +++ /dev/null @@ -1,7 +0,0 @@ -export const HTTP_STATUS_OK = 200; - -export class HttpNotFound extends Error { - constructor(url: string) { - super(`The following resource could not be found: ${url}`); - } -} diff --git a/src/enface/availability.ts b/src/enface/availability.ts index 9ef665e7b..bad6695f3 100644 --- a/src/enface/availability.ts +++ b/src/enface/availability.ts @@ -4,7 +4,7 @@ import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; import type { ProgressiveImage } from '@/src/core/progressiveImage'; -import { Tags } from '@/packages/dicom/core'; +import { Tags, type DicomDataset } from '@/packages/dicom/core'; import { OCT_GEOMETRY_ERROR, OCT_SCAN_PATTERN, @@ -46,15 +46,15 @@ function acquisitionMetadataReason(metadata: Iterable<[string, string]>) { } // An instance's dataset never changes, so each is scanned at most once. -const metadataReasons = new WeakMap(); +const datasetReasons = new WeakMap(); function acquisitionReason(image: ProgressiveImage) { if (!(image instanceof DicomVolumeImage)) return null; - for (const { dataset: metadata } of image.getInstances()) { - let reason = metadataReasons.get(metadata); + for (const { dataset } of image.getInstances()) { + let reason = datasetReasons.get(dataset); if (reason === undefined) { - reason = acquisitionMetadataReason(enFaceTags(metadata)); - metadataReasons.set(metadata, reason); + reason = acquisitionMetadataReason(enFaceTags(dataset)); + datasetReasons.set(dataset, reason); } if (reason !== null) return reason; } diff --git a/src/io/dicom.ts b/src/io/dicom.ts index 9de731b30..b9f84f764 100644 --- a/src/io/dicom.ts +++ b/src/io/dicom.ts @@ -5,25 +5,6 @@ import { import { getWorker } from '@/src/io/itk/worker'; -/** - * Filenames must be sanitized prior to being passed into itk-wasm. - * - * In particular, forward slashes cause FS errors in itk-wasm. - * @param name - * @returns - */ -function sanitizeFileName(name: string) { - return name.replace(/\//g, '_'); -} - -/** - * Returns a new File instance with a sanitized name. - * @param file - */ -function sanitizeFile(file: File) { - return new File([file], sanitizeFileName(file.name)); -} - type DicomSegmentAttributes = { SegmentLabel: string; labelID: number; @@ -40,13 +21,8 @@ type ReadOverlappingSegmentationResultWithRealMeta = }; export async function readDicomSegmentation(file: File) { - const inputImage = sanitizeFile(file); - const result = (await readOverlappingSegmentation(inputImage, { + return (await readOverlappingSegmentation(file, { webWorker: getWorker(), mergeSegments: true, })) as ReadOverlappingSegmentationResultWithRealMeta; - return { - ...result, - outputImage: result.segImage, - }; } diff --git a/src/io/import/__tests__/importDicomInstanceSources.spec.ts b/src/io/import/__tests__/importDicomInstanceSources.spec.ts index 57f3dc38d..3111bf5fe 100644 --- a/src/io/import/__tests__/importDicomInstanceSources.spec.ts +++ b/src/io/import/__tests__/importDicomInstanceSources.spec.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags, type Instance } from '@/packages/dicom/core'; +import type { Instance } from '@/packages/dicom/core'; import { buildStateIDToStoreID, importDicomInstanceSources, @@ -10,6 +10,7 @@ import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useDatasetStore } from '@/src/store/datasets'; import { useImageCacheStore } from '@/src/store/image-cache'; import { + acquisition, ALLOCATION_FAILURE, imageFactory, OTHER_SERIES_UID, @@ -204,16 +205,8 @@ describe('importDicomInstanceSources through the DICOM store', () => { it('repartitions saved provenance when a later import splits the series', () => { const datasetStore = useDatasetStore(); - const pass = (number: string, zs: number[]) => - zs.map((z, i) => - sliceFor({ - sop: `acq${number}-${i}`, - z, - tags: { [Tags.AcquisitionNumber]: number }, - }) - ); - const first = pass('1', [0, 2.5, 5]); - const second = pass('2', [0.75, 3.25, 5.75]); + const first = acquisition('1', [0, 2.5, 5]); + const second = acquisition('2', [0.75, 3.25, 5.75]); const [firstId] = idsOf(load(first).loadables); // The first pass is relabelled, which is not a volume this import loaded. diff --git a/src/io/import/__tests__/missingArchiveMember.spec.ts b/src/io/import/__tests__/missingArchiveMember.spec.ts index 89a74b7e2..3fd033806 100644 --- a/src/io/import/__tests__/missingArchiveMember.spec.ts +++ b/src/io/import/__tests__/missingArchiveMember.spec.ts @@ -64,7 +64,7 @@ describe('restore with a partially missing dataset archive', () => { ManifestSchema.parse(manifest), [], { 'ds-ct': 'store-ct' }, // the dataset resolved from its surviving files - [{ stateID: 'ds-ct', path: 'data/20/b.dcm' }] + { missingFiles: [{ stateID: 'ds-ct', path: 'data/20/b.dcm' }] } ); const warning = useMessageStore().messages.find( @@ -78,9 +78,7 @@ describe('restore with a partially missing dataset archive', () => { ManifestSchema.parse(manifest), [], {}, - [], - [], - { 'ds-ct': ['store-acq1', 'store-acq2'] } + { splitDatasets: { 'ds-ct': ['store-acq1', 'store-acq2'] } } ); const warning = useMessageStore().messages.find( diff --git a/src/io/import/__tests__/restoreCoveredErrors.spec.ts b/src/io/import/__tests__/restoreCoveredErrors.spec.ts index a2cc43d30..9c76cf90c 100644 --- a/src/io/import/__tests__/restoreCoveredErrors.spec.ts +++ b/src/io/import/__tests__/restoreCoveredErrors.spec.ts @@ -118,8 +118,10 @@ describe('importDataSources — restore-covered failures return as ok, not error await openSession(restore); - const [, , , , failedLeaves] = restore.completions[0]; - expect(failedLeaves).toEqual([{ stateID: 'ds-a', name: 'ds-a.bin' }]); + const [, , , reports] = restore.completions[0]; + expect(reports?.failedLeaves).toEqual([ + { stateID: 'ds-a', name: 'ds-a.bin' }, + ]); }); it('keeps a leaf failure as an error when the restore never completed', async () => { diff --git a/src/io/import/__tests__/restoreStateFileLeaves.spec.ts b/src/io/import/__tests__/restoreStateFileLeaves.spec.ts index 0a8b54a68..b1d0203ee 100644 --- a/src/io/import/__tests__/restoreStateFileLeaves.spec.ts +++ b/src/io/import/__tests__/restoreStateFileLeaves.spec.ts @@ -1,18 +1,21 @@ -import openUriStream from '@/src/io/import/processors/openUriStream'; -import type { ImportContext } from '@/src/io/import/common'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { setActivePinia, createPinia } from 'pinia'; import JSZip from 'jszip'; +import openUriStream from '@/src/io/import/processors/openUriStream'; import extractArchive from '@/src/io/import/processors/extractArchive'; +import { restoreStateFile } from '@/src/io/import/processors/restoreStateFile'; import { buildStateIDToStoreID } from '@/src/io/import/importDataSources'; import { asLoadableResult, + type ImportContext, type IntermediateResult, + type StateFileSetupResult, } from '@/src/io/import/common'; -import { findStateFileLeaves } from '@/src/io/import/dataSource'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { setActivePinia, createPinia } from 'pinia'; -import { restoreStateFile } from '@/src/io/import/processors/restoreStateFile'; -import { leafStateId } from '@/src/io/import/dataSource'; -import type { StateFileSetupResult } from '@/src/io/import/common'; +import { + findStateFileLeaves, + leafStateId, + type DataSource, +} from '@/src/io/import/dataSource'; import { MANIFEST_VERSION } from '@/src/io/state-file/serialize'; // --------------------------------------------------------------------------- @@ -104,6 +107,18 @@ describe('prepareLeafDataSources: composed-manifest artifacts', () => { }); }); +/** The one archive member extracted for a saved leaf. */ +const extractedMember = async (source: DataSource, context?: ImportContext) => { + const { dataSources } = (await extractArchive( + source, + context + )) as IntermediateResult; + expect(dataSources).toHaveLength(1); + const [member] = dataSources; + if (member.type !== 'file') throw new Error('Expected a file'); + return member; +}; + describe('saved archive member leaves', () => { beforeEach(() => setActivePinia(createPinia())); it.each([ @@ -146,10 +161,7 @@ describe('saved archive member leaves', () => { })) as StateFileSetupResult; const loadables = await Promise.all( setup.dataSources.map(async (source, index) => { - const result = (await extractArchive(source)) as IntermediateResult; - expect(result.dataSources).toHaveLength(1); - const [member] = result.dataSources; - if (member.type !== 'file') throw new Error('Expected a file'); + const member = await extractedMember(source); expect(await member.file.text()).toBe( index === 0 ? 'series A' : 'series B' ); @@ -204,29 +216,12 @@ it('downloads a saved source archive once and reuses extracted members', async ( if (sources[0].type !== 'file' || sources[1].type !== 'file') throw new Error('Expected archive files'); expect(sources[0].file).toBe(sources[1].file); - const first = (await extractArchive( - sources[0], - context - )) as IntermediateResult; - const second = (await extractArchive( - sources[1], - context - )) as IntermediateResult; - const again = (await extractArchive( - sources[0], - context - )) as IntermediateResult; - const a = first.dataSources[0]; - const b = second.dataSources[0]; - if ( - a.type !== 'file' || - b.type !== 'file' || - again.dataSources[0].type !== 'file' - ) - throw new Error('Expected extracted files'); + const a = await extractedMember(sources[0], context); + const b = await extractedMember(sources[1], context); + const again = await extractedMember(sources[0], context); expect(await a.file.text()).toBe('A'); expect(await b.file.text()).toBe('B'); - expect(again.dataSources[0].file).toBe(a.file); + expect(again.file).toBe(a.file); expect(findStateFileLeaves(a)).toEqual([{ stateID: 'a' }]); expect(findStateFileLeaves(b)).toEqual([{ stateID: 'b' }]); } finally { diff --git a/src/io/import/__tests__/stateFileLeaves.spec.ts b/src/io/import/__tests__/stateFileLeaves.spec.ts index 11b02800d..883a21203 100644 --- a/src/io/import/__tests__/stateFileLeaves.spec.ts +++ b/src/io/import/__tests__/stateFileLeaves.spec.ts @@ -8,7 +8,7 @@ import { buildStateIDToStoreID, findSplitStateDatasets, } from '@/src/io/import/importDataSources'; -import type { LoadableResult } from '@/src/io/import/common'; +import { asLoadableResult, type LoadableResult } from '@/src/io/import/common'; // --------------------------------------------------------------------------- // Multi-file DICOM ephemeral open: the backend's @@ -38,6 +38,9 @@ const mergedDicomSource = (stateIDs: string[]): DataSource => ({ })), }); +const loadedDicom = (dataID: string, stateIDs: string[]) => + asLoadableResult(dataID, mergedDicomSource(stateIDs), 'image'); + describe('findStateFileLeaves', () => { it('walks the parent chain of a plain source', () => { const source: DataSource = { @@ -80,12 +83,7 @@ describe('findStateFileLeaves', () => { describe('buildStateIDToStoreID', () => { it('maps every per-file dataset id of a merged DICOM volume to the ONE store id', () => { const loadables: LoadableResult[] = [ - { - type: 'data', - dataID: 'store-dicom', - dataType: 'image', - dataSource: mergedDicomSource(['ds-f1', 'ds-f2', 'ds-f3']), - }, + loadedDicom('store-dicom', ['ds-f1', 'ds-f2', 'ds-f3']), { type: 'data', dataID: 'store-seg', @@ -112,25 +110,10 @@ describe('buildStateIDToStoreID', () => { // volumes (overlapping acquisitions) has no single owner for its saved // state. Binding to either volume would attach annotations to an // arbitrary sub-volume, so the dataset must go unresolved instead. - const loadables: LoadableResult[] = [ - { - type: 'data', - dataID: 'store-acq1', - dataType: 'image', - dataSource: mergedDicomSource(['ds-split', 'ds-split']), - }, - { - type: 'data', - dataID: 'store-acq2', - dataType: 'image', - dataSource: mergedDicomSource(['ds-split']), - }, - { - type: 'data', - dataID: 'store-whole', - dataType: 'image', - dataSource: mergedDicomSource(['ds-whole']), - }, + const loadables = [ + loadedDicom('store-acq1', ['ds-split', 'ds-split']), + loadedDicom('store-acq2', ['ds-split']), + loadedDicom('store-whole', ['ds-whole']), ]; expect(buildStateIDToStoreID(loadables)).toEqual({ @@ -139,25 +122,10 @@ describe('buildStateIDToStoreID', () => { }); it('names the volumes a split dataset now loads as', () => { - const loadables: LoadableResult[] = [ - { - type: 'data', - dataID: 'store-acq1', - dataType: 'image', - dataSource: mergedDicomSource(['ds-split']), - }, - { - type: 'data', - dataID: 'store-acq2', - dataType: 'image', - dataSource: mergedDicomSource(['ds-split']), - }, - { - type: 'data', - dataID: 'store-whole', - dataType: 'image', - dataSource: mergedDicomSource(['ds-whole']), - }, + const loadables = [ + loadedDicom('store-acq1', ['ds-split']), + loadedDicom('store-acq2', ['ds-split']), + loadedDicom('store-whole', ['ds-whole']), ]; expect(findSplitStateDatasets(loadables)).toEqual({ diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 85291a9dc..505e14c36 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -82,7 +82,7 @@ const applyConfigsPostState = ( } }); -const compareSourceOrder = (a: number[], b: number[]): number => { +const compareSourceOrder = (a: number[], b: number[]) => { for (let i = 0; i < Math.min(a.length, b.length); i++) { if (a[i] !== b[i]) return a[i] - b[i]; } @@ -144,7 +144,7 @@ const sourcesOf = (instances: Instance[]) => .filter((src): src is DicomInstanceSource => src !== undefined); /** What the import needs of its caller: how to remove a dissolved dataset. */ -export type ImportInstancesHooks = Required< +type ImportInstancesHooks = Required< Pick >; @@ -238,7 +238,10 @@ async function processImportQueue( handlers: ImportHandler[], importContext: ImportContext ) { - const instanceSources: Array<{ source: DataSource; order: number[] }> = []; + const instanceSources: Array<{ + source: DicomInstanceSource; + order: number[]; + }> = []; const configResults: ConfigResult[] = []; const stateFileSetups: StateFileSetupResult[] = []; const results: ImportDataSourcesResult[] = []; @@ -355,8 +358,7 @@ async function importDataSourcesWithPolicy( const dicomInstanceSources = instanceSources .sort((a, b) => compareSourceOrder(a.order, b.order)) - .map(({ source }) => source) - .filter((src): src is DicomInstanceSource => src.type === 'dicom'); + .map(({ source }) => source); const dicomResults = importDicomResults(dicomInstanceSources); results.push(...dicomResults); @@ -396,9 +398,7 @@ async function importDataSourcesWithPolicy( setup.manifest, setup.stateFiles, stateIDToStoreID, - setup.missingFiles, - failedLeaves, - splitDatasets + { missingFiles: setup.missingFiles, failedLeaves, splitDatasets } ); setup.dataSources.forEach((src) => { findStateFileLeaves(src).forEach((leaf) => diff --git a/src/io/import/processors/__tests__/handleDicom.spec.ts b/src/io/import/processors/__tests__/handleDicom.spec.ts index 1d3163c59..ff5f2ec98 100644 --- a/src/io/import/processors/__tests__/handleDicom.spec.ts +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -18,11 +18,11 @@ import { syntheticSlice, withoutPixelData } from '@/tests/dicomSourceFixtures'; import { StopSignal } from '@/src/core/streaming/cachedStreamFetcher'; import type { Fetcher } from '@/src/core/streaming/types'; -export const dicomFile = (bytes: Uint8Array, name = 'slice.dcm') => +const dicomFile = (bytes: Uint8Array, name = 'slice.dcm') => new File([bytes as BlobPart], name, { type: FILE_EXT_TO_MIME.dcm }); /** A fetcher over bytes held in memory. */ -export const bytesFetcher = (bytes: Uint8Array) => { +const bytesFetcher = (bytes: Uint8Array) => { let abortController: AbortController | null = null; const fetcher: Fetcher = { diff --git a/src/io/import/processors/handleDicom.ts b/src/io/import/processors/handleDicom.ts index c5e86a023..d99c18b1c 100644 --- a/src/io/import/processors/handleDicom.ts +++ b/src/io/import/processors/handleDicom.ts @@ -5,7 +5,6 @@ import { IMPLICIT_VR_LITTLE_ENDIAN, type DicomLayout, type DicomRuntime, - type Instance, } from '@/packages/dicom/core'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; import { Skip } from '@/src/utils/evaluateChain'; @@ -87,11 +86,7 @@ const handleDicom: ImportHandler = async (dataSource) => { const name = getDataSourceName(dataSource); const { runtime } = useDicomRuntimeStore(); - let instance: Instance; - try { - instance = await readHeader(dataSource, runtime); - reportLayout(name, instance.layout); - } catch (error) { + const instance = await readHeader(dataSource, runtime).catch((error) => { const detail = getErrorDetail( error, 'the file could not be parsed as valid DICOM (check browser console for details)' @@ -99,7 +94,8 @@ const handleDicom: ImportHandler = async (dataSource) => { throw new Error(`Failed to read DICOM tags from ${name}: ${detail}`, { cause: error, }); - } + }); + reportLayout(name, instance.layout); const modality = getDatasetModality(instance.dataset); if (modality?.startsWith('RT')) { diff --git a/src/io/import/processors/restoreStateFile.ts b/src/io/import/processors/restoreStateFile.ts index 9d6da0840..aba3fb298 100644 --- a/src/io/import/processors/restoreStateFile.ts +++ b/src/io/import/processors/restoreStateFile.ts @@ -188,6 +188,14 @@ const defaultRestoredDataset = ( return primary ?? (first ? stateIDToStoreID[first.id] : undefined); }; +/** What the import learned that the restore reports to the user. */ +export type RestoreReports = { + missingFiles?: Array<{ stateID: string; path: string }>; + failedLeaves?: Array<{ stateID: string; name: string }>; + /** State dataset id to the store ids a replan split it into. */ + splitDatasets?: Record; +}; + type RestoreServices = { addWarning?: ReturnType['addWarning']; views?: Pick< @@ -204,9 +212,11 @@ export const createStateFileRestorer = ({ manifest: Manifest, stateFiles: FileEntry[], stateIDToStoreID: Record, - missingFiles: Array<{ stateID: string; path: string }> = [], - failedLeaves: Array<{ stateID: string; name: string }> = [], - splitDatasets: Record = {} + { + missingFiles = [], + failedLeaves = [], + splitDatasets = {}, + }: RestoreReports = {} ) { const viewStore = views ?? useViewStore(); const byId = dataSourcesById(manifest); diff --git a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts index f5972d567..ee4ab43c5 100644 --- a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts +++ b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts @@ -10,24 +10,14 @@ import { type ImportInstancesResult, } from '@/src/store/datasets-dicom'; import { + acquisition, imageFactory, OTHER_SERIES_UID, SERIES_UID, sliceFor, } from '@/src/store/__tests__/dicomImportFixtures'; -// Slices of one acquisition, interleaved with a second acquisition's slices -// along the same stretch of the slice axis. -const acquisition = (number: string, zs: number[], orientation?: string) => - zs.map((z, i) => - sliceFor({ - sop: `acq${number}-${i}`, - z, - orientation, - tags: { [Tags.AcquisitionNumber]: number }, - }) - ); - +// Two passes interleaved along the same stretch of the slice axis. const acquisitionOne = () => acquisition('1', [0, 2.5, 5]); const acquisitionTwo = () => acquisition('2', [0.75, 3.25, 5.75]); diff --git a/src/store/__tests__/datasets-dicom-cine.spec.ts b/src/store/__tests__/datasets-dicom-cine.spec.ts index 741a09d2b..8ff5e8b8a 100644 --- a/src/store/__tests__/datasets-dicom-cine.spec.ts +++ b/src/store/__tests__/datasets-dicom-cine.spec.ts @@ -28,11 +28,9 @@ const unsupported = () => [Tags.PhotometricInterpretation]: 'MONOCHROME1', }); -describe('DICOM store cine routing', () => { - beforeEach(() => { - setActivePinia(createPinia()); - }); +beforeEach(() => setActivePinia(createPinia())); +describe('DICOM store cine routing', () => { it('imports a clip the cine player does not support as a volume', () => { const { created, createImage } = imageFactory(); const clip = unsupported(); @@ -83,7 +81,6 @@ describe('DICOM store cine routing', () => { }); it('imports two same-shaped ultrasound clips as separate playable cine volumes', () => { - setActivePinia(createPinia()); const clips = ['clip-1', 'clip-2'].map((sop) => cineInstance({ [Tags.SOPInstanceUID]: sop }) ); @@ -106,7 +103,6 @@ it('imports two same-shaped ultrasound clips as separate playable cine volumes', }); it('files a clip and a volume of one study under one patient', () => { - setActivePinia(createPinia()); const { createImage } = imageFactory(); const store = useDICOMStore(); // An odd-length value is padded with a space, which the reader keeps. diff --git a/src/store/__tests__/datasets-dicom-reimport.spec.ts b/src/store/__tests__/datasets-dicom-reimport.spec.ts index 6b93d442d..8f3647ea2 100644 --- a/src/store/__tests__/datasets-dicom-reimport.spec.ts +++ b/src/store/__tests__/datasets-dicom-reimport.spec.ts @@ -177,13 +177,11 @@ describe('DICOM store incremental import', () => { expect(created[1].getInstances()[0]).toBe(resupplied); }); - const merging = () => mergingInstances(sliceFor); - it('drops the volume a replan dissolved', () => { const { createImage } = imageFactory(); const store = useDICOMStore(); const imageCacheStore = useImageCacheStore(); - const { between, straight, tilted } = merging(); + const { between, straight, tilted } = mergingInstances(sliceFor); const first = store.importInstances([straight, tilted], { createImage, diff --git a/src/store/__tests__/dicomImportFixtures.ts b/src/store/__tests__/dicomImportFixtures.ts index ef8c6ed76..cfd947c7b 100644 --- a/src/store/__tests__/dicomImportFixtures.ts +++ b/src/store/__tests__/dicomImportFixtures.ts @@ -79,6 +79,21 @@ export function sliceFor({ return instanceFor(datasetFromTags(merged), source); } +/** Slices of one acquisition pass, tagged with its Acquisition Number. */ +export const acquisition = ( + number: string, + zs: number[], + orientation?: string +) => + zs.map((z, i) => + sliceFor({ + sop: `acq${number}-${i}`, + z, + orientation, + tags: { [Tags.AcquisitionNumber]: number }, + }) + ); + /** * Orientation agreement is a tolerance, so a bucket depends on which instance * the walk meets first. `one` and `three` agree with each other and plan as a @@ -121,7 +136,7 @@ export const onlyFailure = ({ /** An instance as the import pipeline hands it on, read from a URL. */ export const sourceFor = (instance: Instance) => { const name = `${sopOf(instance)}.dcm`; - const source: DataSource = { + return { type: 'dicom', instance, parent: uriToDataSource( @@ -129,8 +144,7 @@ export const sourceFor = (instance: Instance) => { name, FILE_EXT_TO_MIME.dcm ), - }; - return source as DataSource & DicomInstanceSource; + } satisfies DataSource & DicomInstanceSource; }; /** The SOP Instance UIDs a dataset's saved provenance names, in order. */ diff --git a/src/store/__tests__/duplicateDatasetSave.spec.ts b/src/store/__tests__/duplicateDatasetSave.spec.ts index 1aed29305..4321a3acb 100644 --- a/src/store/__tests__/duplicateDatasetSave.spec.ts +++ b/src/store/__tests__/duplicateDatasetSave.spec.ts @@ -3,19 +3,40 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { setActivePinia, createPinia } from 'pinia'; import JSZip from 'jszip'; import { useDatasetStore } from '@/src/store/datasets'; -import { uriToDataSource } from '@/src/io/import/dataSource'; +import { + isRemoteDataSource, + uriToDataSource, + type DataSource, +} from '@/src/io/import/dataSource'; import { normalizeManifest, MANIFEST_VERSION, } from '@/src/io/state-file/serialize'; import type { Manifest } from '@/src/io/state-file/schema'; -import { - isRemoteDataSource, - type DataSource, -} from '@/src/io/import/dataSource'; import { Tags } from '@/packages/dicom/core'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; +/** Saves the dataset store into a fresh manifest and zip. */ +const save = async () => { + const zip = new JSZip(); + const manifest = { + version: MANIFEST_VERSION, + datasets: [], + dataSources: [], + datasetFilePath: {}, + } as Manifest; + await useDatasetStore().serialize({ zip, manifest }); + return { zip, manifest }; +}; + +/** The saved collection of the manifest's only dataset. */ +const savedCollection = (manifest: Manifest) => { + const id = manifest.datasets![0].dataSourceId; + const collection = manifest.dataSources.find((source) => source.id === id); + if (collection?.type !== 'collection') throw new Error('Expected collection'); + return collection; +}; + // --------------------------------------------------------------------------- // Regression: importing the same data twice (e.g. dragging the same DICOM // folder in again) yields the same dataID. The provenance list must not grow a @@ -34,14 +55,7 @@ describe('dataset provenance dedup on re-import', () => { store.addDataSources([{ dataID: 'vol-1', dataSource }]); store.addDataSources([{ dataID: 'vol-1', dataSource }]); - const zip = new JSZip(); - const manifest = { - version: MANIFEST_VERSION, - datasets: [], - dataSources: [], - datasetFilePath: {}, - } as Manifest; - await store.serialize({ zip, manifest }); + const { zip, manifest } = await save(); expect(manifest.datasets).toHaveLength(1); expect(() => normalizeManifest(manifest, zip)).not.toThrow(); @@ -88,13 +102,7 @@ describe('dataset provenance dedup on re-import', () => { })); store.addDataSources([{ dataID: 'series-1', dataSource: original }]); store.addDataSources([{ dataID: 'series-1', dataSource: duplicate }]); - const zip = new JSZip(); - const manifest = { - version: MANIFEST_VERSION, - datasets: [], - dataSources: [], - } as Manifest; - await store.serialize({ zip, manifest }); + const { zip, manifest } = await save(); const [filePath] = Object.values(manifest.datasetFilePath!); expect(await zip.file(filePath)!.async('string')).toBe('sop-1'); }); @@ -113,28 +121,10 @@ describe('dataset provenance dedup on re-import', () => { }, ]); - const zip = new JSZip(); - const manifest = { - version: MANIFEST_VERSION, - datasets: [], - dataSources: [], - datasetFilePath: {}, - } as Manifest; - await store.serialize({ zip, manifest }); + const { zip, manifest } = await save(); expect(manifest.datasets).toHaveLength(1); - const datasetSourceId = manifest.datasets![0].dataSourceId; - const collection = manifest.dataSources.find( - (source) => source.id === datasetSourceId - ); - expect(collection).toMatchObject({ - type: 'collection', - sources: expect.any(Array), - }); - if (collection?.type !== 'collection') { - throw new Error('Expected collection'); - } - expect(collection.sources).toHaveLength(4); + expect(savedCollection(manifest).sources).toHaveLength(4); expect(() => normalizeManifest(manifest, zip)).not.toThrow(); }); @@ -147,23 +137,9 @@ describe('dataset provenance dedup on re-import', () => { { dataID: 'series-1', dataSource: dicomBatch(['sop-1', 'sop-2']) }, ]); - const zip = new JSZip(); - const manifest = { - version: MANIFEST_VERSION, - datasets: [], - dataSources: [], - datasetFilePath: {}, - } as Manifest; - await store.serialize({ zip, manifest }); - - const datasetSourceId = manifest.datasets![0].dataSourceId; - const collection = manifest.dataSources.find( - (source) => source.id === datasetSourceId - ); - if (collection?.type !== 'collection') { - throw new Error('Expected collection'); - } - expect(collection.sources).toHaveLength(2); + const { manifest } = await save(); + + expect(savedCollection(manifest).sources).toHaveLength(2); }); it('drops a member a replan moved to another dataset', () => { @@ -221,13 +197,7 @@ it('saves one shared archive File used by distinct restored dataset leaves', asy }, })) ); - const zip = new JSZip(); - const manifest = { - version: MANIFEST_VERSION, - dataSources: [], - datasets: [], - } as Manifest; - await store.serialize({ zip, manifest }); + const { zip, manifest } = await save(); expect(manifest.datasets).toHaveLength(2); expect( manifest.dataSources.filter((source) => source.type === 'file') diff --git a/src/store/datasets-dicom.ts b/src/store/datasets-dicom.ts index a42bb877d..bdd67363c 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -443,10 +443,7 @@ export const useDICOMStore = defineStore('dicom', { _commitSeries( batch: Instance[], - context: { - createImage: (id: string) => DicomVolumeImage; - removeDissolved: (id: string) => void; - } + context: Required ): ImportInstancesResult['volumes'] { const { state, updates, removed, conflictingInstanceUids } = registerInstances(registryOf(this), batch); diff --git a/tests/fixtures/dicom-pages/enhancedFixtures.ts b/tests/fixtures/dicom-pages/enhancedFixtures.ts index 81a2bcd8f..593fa73f2 100644 --- a/tests/fixtures/dicom-pages/enhancedFixtures.ts +++ b/tests/fixtures/dicom-pages/enhancedFixtures.ts @@ -1,36 +1,27 @@ import { buildSyntheticDicom, combine, - rawElement, - sequenceItem, + ds, + sequence, + ul, } from '../../specs/syntheticDicom'; -const text = (group: number, element: number, value: readonly number[]) => { - const string = value.join('\\'); - return rawElement( - group, - element, - 'DS', - new TextEncoder().encode(string.length % 2 ? `${string} ` : string) - ); -}; - -const sequence = (group: number, element: number, items: Uint8Array[]) => - rawElement(group, element, 'SQ', combine(...items.map(sequenceItem))); +const decimals = (group: number, element: number, values: readonly number[]) => + ds(group, element, values.join('\\')); const position = (value: readonly number[]) => - sequence(0x0020, 0x9113, [text(0x0020, 0x0032, value)]); + sequence(0x0020, 0x9113, [decimals(0x0020, 0x0032, value)]); const transformation = ([slope, intercept]: readonly [number, number]) => sequence(0x0028, 0x9145, [ - combine(text(0x0028, 0x1052, [intercept]), text(0x0028, 0x1053, [slope])), + combine( + ds(0x0028, 0x1052, String(intercept)), + ds(0x0028, 0x1053, String(slope)) + ), ]); -const temporalPosition = (value: number) => { - const bytes = new Uint8Array(4); - new DataView(bytes.buffer).setUint32(0, value, true); - return sequence(0x0020, 0x9111, [rawElement(0x0020, 0x9128, 'UL', bytes)]); -}; +const temporalPosition = (value: number) => + sequence(0x0020, 0x9111, [ul(0x0020, 0x9128, value)]); type EnhancedFixtureOptions = { pixelValues: number[]; @@ -50,8 +41,8 @@ export function enhancedFixtureBytes(options: EnhancedFixtureOptions) { transforms, } = options; const shared = [ - sequence(0x0020, 0x9116, [text(0x0020, 0x0037, [1, 0, 0, 0, 1, 0])]), - sequence(0x0028, 0x9110, [text(0x0028, 0x0030, [1, 1])]), + sequence(0x0020, 0x9116, [decimals(0x0020, 0x0037, [1, 0, 0, 0, 1, 0])]), + sequence(0x0028, 0x9110, [decimals(0x0028, 0x0030, [1, 1])]), ]; if (sharedPosition) shared.unshift(position(sharedPosition)); const frames = pixelValues.map((_, index) => diff --git a/tests/fixtures/oct/dicom.ts b/tests/fixtures/oct/dicom.ts index e9854c7f7..43cd4d41c 100644 --- a/tests/fixtures/oct/dicom.ts +++ b/tests/fixtures/oct/dicom.ts @@ -1,6 +1,6 @@ import { deflateRawSync } from 'node:zlib'; import reference from './reference.json'; -import { elemShort, elemLong, LONG_FORM_VRS } from '../../specs/syntheticDicom'; +import { rawElement, sequenceItem, ul } from '../../specs/syntheticDicom'; const concat = (chunks: Uint8Array[]) => Buffer.concat(chunks); @@ -8,8 +8,7 @@ export function element(tag: string, vr: string, value: string | Uint8Array) { let payload = typeof value === 'string' ? Buffer.from(value) : value; if (payload.length % 2) payload = concat([payload, Uint8Array.of(vr === 'UI' ? 0 : 32)]); - const encode = LONG_FORM_VRS.has(vr) ? elemLong : elemShort; - return encode( + return rawElement( parseInt(tag.slice(0, 4), 16), parseInt(tag.slice(4), 16), vr, @@ -18,19 +17,7 @@ export function element(tag: string, vr: string, value: string | Uint8Array) { } export function sequence(tag: string, datasets: Uint8Array[]) { - return element( - tag, - 'SQ', - concat( - datasets.map((dataset) => { - const header = Buffer.alloc(8); - header.writeUInt16LE(0xfffe); - header.writeUInt16LE(0xe000, 2); - header.writeUInt32LE(dataset.length, 4); - return concat([header, dataset]); - }) - ) - ); + return element(tag, 'SQ', concat(datasets.map(sequenceItem))); } /** An element to encode, an SQ holding its items; bytes pass through as encoded. */ @@ -134,15 +121,13 @@ function part10( : node ); const metaBytes = encode(meta); - const length = Buffer.alloc(4); - length.writeUInt32LE(metaBytes.length); const dataset = encode(edited.filter((node) => !isFileMeta(node))); const deflateWith = deflate === true ? deflateRawSync : deflate; const body = deflateWith ? deflateWith(dataset) : dataset; return concat([ Buffer.alloc(128), Buffer.from('DICM'), - ...(groupLength || deflate ? [element('00020000', 'UL', length)] : []), + ...(groupLength || deflate ? [ul(0x0002, 0x0000, metaBytes.length)] : []), metaBytes, body, // DICOM requires an even-length deflated stream with a trailing NULL if needed. diff --git a/tests/nativePixelDicom.ts b/tests/nativePixelDicom.ts index 41d18cf97..10ed500d2 100644 --- a/tests/nativePixelDicom.ts +++ b/tests/nativePixelDicom.ts @@ -2,7 +2,11 @@ // for comparing frame decoders. Stored words are written as given, so high // bits above Bits Stored can carry anything a test wants. -import { combine, LONG_FORM_VRS } from '@/tests/specs/syntheticDicom'; +import { + combine, + LONG_FORM_VRS, + part10File, +} from '@/tests/specs/syntheticDicom'; export const IMPLICIT_LE = '1.2.840.10008.1.2'; export const EXPLICIT_LE = '1.2.840.10008.1.2.1'; @@ -26,6 +30,8 @@ const NUMBER_WIDTH: Record = { type Encoding = { explicit: boolean; littleEndian: boolean }; +const enc = new TextEncoder(); + const uint = (value: number, width: number, littleEndian: boolean) => { const bytes = new Uint8Array(width); const view = new DataView(bytes.buffer); @@ -60,7 +66,7 @@ function valueBytes(element: DataElement, encoding: Encoding): Uint8Array { const { vr, value } = element; if (typeof value === 'string') { const pad = vr === 'UI' ? '\0' : ' '; - return new TextEncoder().encode(value.length % 2 ? value + pad : value); + return enc.encode(value.length % 2 ? value + pad : value); } if (value instanceof Uint8Array) return value.length % 2 ? combine(value, new Uint8Array(1)) : value; @@ -84,14 +90,11 @@ function encodeElement(element: DataElement, encoding: Encoding) { const head = encoding.explicit ? LONG_FORM_VRS.has(element.vr) ? [ - new TextEncoder().encode(element.vr), + enc.encode(element.vr), new Uint8Array(2), uint(value.length, 4, littleEndian), ] - : [ - new TextEncoder().encode(element.vr), - uint(value.length, 2, littleEndian), - ] + : [enc.encode(element.vr), uint(value.length, 2, littleEndian)] : [uint(value.length, 4, littleEndian)]; return combine(tagBytes(element.tag, littleEndian), ...head, value); } @@ -103,39 +106,6 @@ const encodeElements = (elements: DataElement[], encoding: Encoding) => .map((element) => encodeElement(element, encoding)) ); -/** Wraps a data set in a preamble and Explicit VR Little Endian file meta. */ -function part10( - dataset: DataElement[], - transferSyntaxUid: string, - sopClassUid: string, - sopInstanceUid: string -) { - const meta = encodeElements( - [ - { tag: 0x00020001, vr: 'OB', value: new Uint8Array([0, 1]) }, - { tag: 0x00020002, vr: 'UI', value: sopClassUid }, - { tag: 0x00020003, vr: 'UI', value: sopInstanceUid }, - { tag: 0x00020010, vr: 'UI', value: transferSyntaxUid }, - ], - { explicit: true, littleEndian: true } - ); - const groupLength = encodeElement( - { tag: 0x00020000, vr: 'UL', value: [meta.length] }, - { explicit: true, littleEndian: true } - ); - const encoding = { - explicit: transferSyntaxUid !== IMPLICIT_LE, - littleEndian: transferSyntaxUid !== EXPLICIT_BE, - }; - return combine( - new Uint8Array(128), - new TextEncoder().encode('DICM'), - groupLength, - meta, - encodeElements(dataset, encoding) - ); -} - export type NativePixelOptions = { transferSyntaxUid?: string; sopClassUid?: string; @@ -174,8 +144,6 @@ export function patternWords(count: number, bitsAllocated: number, seed = 1) { }); } -const decimal = (value: number) => String(value); - const frameRescaleGroups = ( rescales: ReadonlyArray ): DataElement => ({ @@ -187,8 +155,8 @@ const frameRescaleGroups = ( vr: 'SQ', value: [ [ - { tag: 0x00281052, vr: 'DS', value: decimal(intercept) }, - { tag: 0x00281053, vr: 'DS', value: decimal(slope) }, + { tag: 0x00281052, vr: 'DS', value: String(intercept) }, + { tag: 0x00281053, vr: 'DS', value: String(slope) }, { tag: 0x00281054, vr: 'LO', value: 'US' }, ], ], @@ -259,9 +227,17 @@ export function nativePixelDicom(options: NativePixelOptions = {}) { dataset.push({ tag: 0x00280006, vr: 'US', value: [planarConfiguration] }); if (rescale) dataset.push( - { tag: 0x00281052, vr: 'DS', value: decimal(rescale[1]) }, - { tag: 0x00281053, vr: 'DS', value: decimal(rescale[0]) } + { tag: 0x00281052, vr: 'DS', value: String(rescale[1]) }, + { tag: 0x00281053, vr: 'DS', value: String(rescale[0]) } ); if (frameRescales) dataset.push(frameRescaleGroups(frameRescales)); - return part10(dataset, transferSyntaxUid, sopClassUid, sopInstanceUid); + return part10File( + sopClassUid, + sopInstanceUid, + transferSyntaxUid, + encodeElements(dataset, { + explicit: transferSyntaxUid !== IMPLICIT_LE, + littleEndian, + }) + ); } diff --git a/tests/pageobjects/volview.page.ts b/tests/pageobjects/volview.page.ts index d7fdde58c..2dcf32a33 100644 --- a/tests/pageobjects/volview.page.ts +++ b/tests/pageobjects/volview.page.ts @@ -95,24 +95,18 @@ class VolViewPage extends Page { return $$('.volume-card'); } - /** Slice counts of the volume cards, ascending. Each label carries "[N]". */ - async getVolumeCardSliceCounts() { - const cards = [...(await this.volumeCards)]; - const labels = await Promise.all(cards.map((card) => card.getText())); - return labels - .map((label) => Number(label.match(/\[(\d+)\]/)?.[1])) - .filter(Number.isFinite) - .sort((a, b) => a - b); - } - + /** Waits for the volume cards' "[N]" slice counts, ascending, to be `expected`. */ async waitForVolumeCardSliceCounts(expected: number[]) { await browser.waitUntil( async () => { - const counts = await this.getVolumeCardSliceCounts(); - return ( - counts.length === expected.length && - counts.every((count, index) => count === expected[index]) + const labels = await Promise.all( + [...(await this.volumeCards)].map((card) => card.getText()) ); + const counts = labels + .map((label) => Number(label.match(/\[(\d+)\]/)?.[1])) + .filter(Number.isFinite) + .sort((a, b) => a - b); + return counts.join() === expected.join(); }, { timeout: DOWNLOAD_TIMEOUT, diff --git a/tests/specs/dicom-import-regressions.e2e.ts b/tests/specs/dicom-import-regressions.e2e.ts index 4f92fd8ee..c8ec8d341 100644 --- a/tests/specs/dicom-import-regressions.e2e.ts +++ b/tests/specs/dicom-import-regressions.e2e.ts @@ -89,8 +89,6 @@ describe('Local DICOM import regressions', () => { imageOrientationPatient: i === 0 ? [Math.cos(0.0002), 0, Math.sin(0.0002), 0, 1, 0] : AXIAL, imagePositionPatient: [0, 0, i * 5], - rows: 4, - cols: 4, pixelValue: i, }) ); @@ -126,8 +124,6 @@ describe('Local DICOM import regressions', () => { instanceNumber: 1, imageOrientationPatient: AXIAL, imagePositionPatient: [0, 0, 0], - rows: 4, - cols: 4, pixelValue: 123, extraElements: [ rawElement(0x0043, 0x0010, 'LO', new TextEncoder().encode('TEST')), @@ -156,8 +152,6 @@ describe('Local DICOM import regressions', () => { instanceNumber: i + 1, imageOrientationPatient: AXIAL, imagePositionPatient: [0, 0, i], - rows: 4, - cols: 4, pixelValue: 10 * (i + 1), }) ); diff --git a/tests/specs/dicom-japanese-name.e2e.ts b/tests/specs/dicom-japanese-name.e2e.ts index 453919998..2cd7cd61e 100644 --- a/tests/specs/dicom-japanese-name.e2e.ts +++ b/tests/specs/dicom-japanese-name.e2e.ts @@ -6,6 +6,7 @@ import { TEMP_DIR } from '../../wdio.shared.conf'; import { volViewPage } from '../pageobjects/volview.page'; import { buildSlice, + JAPANESE_CHARACTER_SET, JAPANESE_NAME, JAPANESE_NAME_BYTES, } from './dicomElementFixtures'; @@ -23,7 +24,7 @@ describe('DICOM patient name in a non-default character set', () => { studyUid: newUid(), seriesUid: newUid(), sopUid: newUid(), - specificCharacterSet: 'ISO 2022 IR 6\\ISO 2022 IR 87', + specificCharacterSet: JAPANESE_CHARACTER_SET, patientNameBytes: JAPANESE_NAME_BYTES, }) ); diff --git a/tests/specs/dicom-module-pages.e2e.ts b/tests/specs/dicom-module-pages.e2e.ts index 7f7be1389..688554032 100644 --- a/tests/specs/dicom-module-pages.e2e.ts +++ b/tests/specs/dicom-module-pages.e2e.ts @@ -5,6 +5,9 @@ import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { openDicomPage } from '../dicomPages'; +// Every stored 5 under slope 2 and intercept -20. +const CALIBRATED_PIXELS = Array(16).fill('-10').join(', '); + describe('DICOM module pages without VolView startup', () => { let fixture: Awaited>; before(async () => { @@ -17,12 +20,8 @@ describe('DICOM module pages without VolView startup', () => { it('rejects a failed worker startup and finishes queued and later reads', async () => { await openDicomPage(`${fixture.urls.core}?scenario=worker-recovery`); await expect($('#first-error')).toHaveText('DICOM decoder worker failed'); - await expect($('#queued-pixels')).toHaveText( - Array(16).fill('-10').join(', ') - ); - await expect($('#retry-pixels')).toHaveText( - Array(16).fill('-10').join(', ') - ); + await expect($('#queued-pixels')).toHaveText(CALIBRATED_PIXELS); + await expect($('#retry-pixels')).toHaveText(CALIBRATED_PIXELS); }); it('core reads metadata and calibrated pixels from a file', async () => { @@ -30,7 +29,7 @@ describe('DICOM module pages without VolView startup', () => { await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); await expect($('#position')).toHaveText('10, 20, 30'); await expect($('#pixel-spacing')).toHaveText('2, 3'); - await expect($('#pixels')).toHaveText(Array(16).fill('-10').join(', ')); + await expect($('#pixels')).toHaveText(CALIBRATED_PIXELS); }); it('vtk places and renders the volume read over HTTP', async () => { diff --git a/tests/specs/dicom-native-parity.e2e.ts b/tests/specs/dicom-native-parity.e2e.ts index 0fc7d1fc0..d4350ffa2 100644 --- a/tests/specs/dicom-native-parity.e2e.ts +++ b/tests/specs/dicom-native-parity.e2e.ts @@ -1,6 +1,16 @@ import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import JSZip from 'jszip'; +import { + CINE_US_DATASET, + COLOR3D_JPEG_BASELINE_DICOM, + MINIMAL_DICOM, + MRA_HEAD_NECK_DATASET, + ONE_CT_SLICE_DICOM, + PROSTATEX_DATASET, + RETINAL_OCT_DICOM, + US_MULTIFRAME_DICOM, +} from '../datasets'; import { DATASET_CACHE } from '../downloadDatasets'; import { openDicomPage } from '../dicomPages'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; @@ -94,11 +104,6 @@ const synthetic: Array<[string, boolean, NativePixelOptions]> = [ ), ]; -const cached = (names: string[]) => - names.map( - (name) => [name, readFileSync(resolve(DATASET_CACHE, name))] as const - ); - /** One slice of an archive whose slices all share a pixel format. */ const firstSlice = async (zip: string) => { const archive = await JSZip.loadAsync( @@ -132,11 +137,19 @@ describe('Native frame decoding parity with GDCM', () => { let cases: string[] = []; before(async () => { const publicFiles = [ - ...cached(['CT000085.dcm', 'minimal.dcm', 'retinal-oct.dcm']), - ...cached(['US-MONO2-8-8x-echo.dcm', 'US_multiframe_30frames.dcm']), - ...cached(['color3d_jpeg_baseline.dcm']), - await firstSlice('prostate.zip'), - await firstSlice('MRA-Head_and_Neck.zip'), + ...[ + ONE_CT_SLICE_DICOM, + MINIMAL_DICOM, + RETINAL_OCT_DICOM, + CINE_US_DATASET, + US_MULTIFRAME_DICOM, + COLOR3D_JPEG_BASELINE_DICOM, + ].map( + ({ name }) => + [name, readFileSync(resolve(DATASET_CACHE, name))] as const + ), + await firstSlice(PROSTATEX_DATASET.name), + await firstSlice(MRA_HEAD_NECK_DATASET.name), ]; const files = [ ...synthetic.map( diff --git a/tests/specs/dicom-spacing-details.e2e.ts b/tests/specs/dicom-spacing-details.e2e.ts index ed6209139..abd9bcac5 100644 --- a/tests/specs/dicom-spacing-details.e2e.ts +++ b/tests/specs/dicom-spacing-details.e2e.ts @@ -29,8 +29,6 @@ function slice(options: Partial = {}) { instanceNumber: 1, imageOrientationPatient: [1, 0, 0, 0, 1, 0], imagePositionPatient: [0, 0, 0], - rows: 4, - cols: 4, pixelSpacing: [0.5, 0.25], pixelValue: 80, ...options, diff --git a/tests/specs/dicom-volume-composition.e2e.ts b/tests/specs/dicom-volume-composition.e2e.ts index bc0e42aa4..1a1502214 100644 --- a/tests/specs/dicom-volume-composition.e2e.ts +++ b/tests/specs/dicom-volume-composition.e2e.ts @@ -102,7 +102,6 @@ describe('VolView downloaded collection import', () => { await volViewPage.waitForViewsLoaded(); await waitForRenderedSlice( `composition-${scenario.id}.png`, - 0, scenario.id === 'pet-ct' ); expect(await volViewPage.getNotificationsCount()).toBe(0); diff --git a/tests/specs/dicomElementFixtures.ts b/tests/specs/dicomElementFixtures.ts index df6df01e7..e934af549 100644 --- a/tests/specs/dicomElementFixtures.ts +++ b/tests/specs/dicomElementFixtures.ts @@ -17,7 +17,7 @@ const ascii = (text: string) => new TextEncoder().encode(text); const jisX0208 = (...codes: number[]) => bytes(0x1b, 0x24, 0x42, ...codes, 0x1b, 0x28, 0x42); -const JAPANESE_CHARACTER_SET = 'ISO 2022 IR 6\\ISO 2022 IR 87'; +export const JAPANESE_CHARACTER_SET = 'ISO 2022 IR 6\\ISO 2022 IR 87'; export const JAPANESE_NAME = 'Yamada^Tarou=山田^太郎=やまだ^たろう'; export const JAPANESE_NAME_BYTES = combine( diff --git a/tests/specs/dicomRenderedSlice.ts b/tests/specs/dicomRenderedSlice.ts index d1fe5ca16..b0fb50442 100644 --- a/tests/specs/dicomRenderedSlice.ts +++ b/tests/specs/dicomRenderedSlice.ts @@ -6,14 +6,13 @@ type RenderedSlice = { width: number; height: number; data: Buffer }; // controls, so UI text cannot satisfy image assertions. const VIEW_INSET = 80; -async function captureSlice(fileName: string, viewIndex: number) { - const views = await captureViewPixels( +async function captureSlice(fileName: string) { + const [view] = await captureViewPixels( '[data-testid~="vtk-two-view"]', VIEW_INSET, fileName ); - const view = views[viewIndex]; - if (!view) throw new Error(`No slice viewport at index ${viewIndex}`); + if (!view) throw new Error('No slice viewport'); return { ...view, height: view.data.length / 4 / view.width }; } @@ -58,16 +57,12 @@ function imageChanged(before: RenderedSlice, after: RenderedSlice) { return changed > before.width * before.height * 0.002; } -export async function waitForRenderedSlice( - fileName: string, - viewIndex = 0, - color = false -) { +export async function waitForRenderedSlice(fileName: string, color = false) { await $('header').moveTo(); let image: RenderedSlice | undefined; await browser.waitUntil( async () => { - image = await captureSlice(fileName, viewIndex); + image = await captureSlice(fileName); return hasImageContent(image, color); }, { @@ -79,13 +74,12 @@ export async function waitForRenderedSlice( export async function waitForRenderedSliceChange( before: RenderedSlice, - fileName: string, - viewIndex = 0 + fileName: string ) { await $('header').moveTo(); await browser.waitUntil( async () => { - const after = await captureSlice(fileName, viewIndex); + const after = await captureSlice(fileName); return hasImageContent(after) && imageChanged(before, after); }, { diff --git a/tests/specs/imageCacheUtils.ts b/tests/specs/imageCacheUtils.ts index 93ea32cd3..10cbe0064 100644 --- a/tests/specs/imageCacheUtils.ts +++ b/tests/specs/imageCacheUtils.ts @@ -1,4 +1,4 @@ -export function getFirstCachedImageSpacing() { +function getFirstCachedImageSpacing() { return browser.execute(() => { const app = (document.querySelector('#app') as any)?.__vue_app__; const pinia = diff --git a/tests/specs/incremental-positionless-import.e2e.ts b/tests/specs/incremental-positionless-import.e2e.ts index 86c5682b8..ae3380307 100644 --- a/tests/specs/incremental-positionless-import.e2e.ts +++ b/tests/specs/incremental-positionless-import.e2e.ts @@ -8,9 +8,6 @@ // ImagePositionPatient is empty, so nothing can be said about where it sits. // Every volume must survive, the unplaceable slice must arrive as a volume of // its own, and the user must be told about it. -// -// Synthetic DICOMs are generated on the fly so the test carries no binary -// fixtures. import * as path from 'path'; import * as fs from 'fs'; import { volViewPage } from '../pageobjects/volview.page'; diff --git a/tests/specs/octTestUtils.ts b/tests/specs/octTestUtils.ts index eaeea0e3c..629e70575 100644 --- a/tests/specs/octTestUtils.ts +++ b/tests/specs/octTestUtils.ts @@ -164,8 +164,7 @@ export async function selectEnFace(viewIndex = 0) { await switcher.click(); const option = overlayOption('En face'); await option.waitForExist(); - // Source canvases render progressively; En face stays disabled until the - // complete volume has loaded. Use that view's published loading state. + // En face stays disabled until the complete volume has loaded. await volViewPage.waitForLoadingIndicator(switcher); await option.waitForClickable(); await option.click(); diff --git a/tests/specs/pet-ct-sample.e2e.ts b/tests/specs/pet-ct-sample.e2e.ts index ed35d82c1..28b98b392 100644 --- a/tests/specs/pet-ct-sample.e2e.ts +++ b/tests/specs/pet-ct-sample.e2e.ts @@ -40,15 +40,20 @@ async function useLocalSampleFiles(files: { url: string; name: string }[]) { }, files); } -async function openAxialSample() { - await volViewPage.open(); - await selectLayout('Axial Only', 1, false); +async function clickSample() { const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); + await sample.waitForExist(); await sample.execute((element) => element.scrollIntoView({ block: 'center', behavior: 'instant' }) ); await sample.waitForClickable(); await sample.click(); +} + +async function openAxialSample() { + await volViewPage.open(); + await selectLayout('Axial Only', 1, false); + await clickSample(); await volViewPage.waitForViews(); } @@ -63,6 +68,17 @@ async function displayedPetRange() { ); } +async function expectPetRange([minimum, maximum]: string[]) { + await expect($('[data-testid="layer-range-min"] input')).toHaveAttribute( + 'title', + minimum + ); + await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( + 'title', + maximum + ); +} + async function expectFullRangeDefault() { const initial = await displayedPetRange(); const contrast = $('[data-testid="layer-contrast"]'); @@ -127,14 +143,7 @@ async function editPetColors( narrowedMaximum ); await $('header').moveTo(); - await expect($('[data-testid="layer-range-min"] input')).toHaveAttribute( - 'title', - minimum - ); - await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( - 'title', - narrowedMaximum - ); + await expectPetRange([minimum, narrowedMaximum]); await browser.waitUntil( async () => { const pixels = await captureAxialPixels(); @@ -168,14 +177,8 @@ async function reopenSample( preset = 'DICOM Hot Iron' ) { await showSampleData(); - const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); - await sample.waitForExist(); - await sample.execute((element) => - element.scrollIntoView({ block: 'center', behavior: 'instant' }) - ); await browser.saveScreenshot(path.join(TEMP_DIR, 'pet-ct-sample-reload.png')); - await sample.waitForClickable(); - await sample.click(); + await clickSample(); await expect( $('.volume-card[html-title="PET WB Corrected"]') ).toBeDisplayed(); @@ -191,14 +194,7 @@ async function reopenSample( 'layer-opacity-slider', ]) await expect($$(`[data-testid="${control}"]`)).toBeElementsArrayOfSize(1); - await expect($('[data-testid="layer-range-min"] input')).toHaveAttribute( - 'title', - range[0] - ); - await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( - 'title', - range[1] - ); + await expectPetRange(range); await expect($('[data-testid="layer-colormap"]')).toHaveText( expect.stringContaining(preset) ); @@ -320,12 +316,7 @@ describe('PET/CT sample', () => { await selectLayout('Four Up', 3, true); for (let loading = 0; loading < 2; loading++) { await showSampleData(); - const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); - await sample.execute((element) => - element.scrollIntoView({ block: 'center', behavior: 'instant' }) - ); - await sample.waitForClickable(); - await sample.click(); + await clickSample(); await expect($('[data-testid~="vtk-two-view"]')).toHaveText( expect.stringContaining('CT WB') ); @@ -383,14 +374,7 @@ describe('PET/CT sample', () => { await expect( $('[data-testid="layer-opacity-slider"] [role="slider"]') ).toHaveAttribute('aria-valuenow', opacity); - await expect($('[data-testid="layer-range-min"] input')).toHaveAttribute( - 'title', - '0' - ); - await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( - 'title', - maximum - ); + await expectPetRange(['0', maximum]); await expect( $('[data-testid="layer-transparent-background"] input') ).toBeChecked(); @@ -424,18 +408,10 @@ describe('PET/CT sample', () => { initial.pixels, initial.range ); - const [minimum, narrowedMaximum] = range; await selectLayout('3D Only', 0, true); await expect($('[data-testid="layer-range-max"] input')).toBeEnabled(); await selectLayout('Axial Only', 1, false); - await expect($('[data-testid="layer-range-min"] input')).toHaveAttribute( - 'title', - minimum - ); - await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( - 'title', - narrowedMaximum - ); + await expectPetRange(range); await expect($('[data-testid="layer-colormap"]')).toHaveText( expect.stringContaining('Cool to Warm') ); @@ -500,14 +476,7 @@ describe('PET/CT sample', () => { it('uses consistent PET DICOM windows and preserves an edited range when saving and reopening', async () => { await openPetMetadataVariant('valid'); - await expect($('[data-testid="layer-range-min"] input')).toHaveAttribute( - 'title', - '0' - ); - await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( - 'title', - '5999' - ); + await expectPetRange(['0', '5999']); await setValueVueInput($('[data-testid="layer-range-min"] input'), '100'); await setValueVueInput($('[data-testid="layer-range-max"] input'), '3000'); await expect($('[data-testid="layer-range-max"] input')).toHaveAttribute( diff --git a/tests/specs/session-overlapping-imports.e2e.ts b/tests/specs/session-overlapping-imports.e2e.ts index 70af88e75..dfbb2a6b0 100644 --- a/tests/specs/session-overlapping-imports.e2e.ts +++ b/tests/specs/session-overlapping-imports.e2e.ts @@ -6,9 +6,6 @@ // into two volumes. The session saved afterwards must restore both. Deleting // one volume and saving again must restore only the survivor: a dataset the // user removed cannot come back. -// -// Synthetic DICOMs are generated on the fly so the test carries no binary -// fixtures. import * as path from 'path'; import { volViewPage } from '../pageobjects/volview.page'; import { TEMP_DIR } from '../../wdio.shared.conf'; diff --git a/tests/specs/syntheticDicom.ts b/tests/specs/syntheticDicom.ts index 8d39b677e..f2c4d5002 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -1,9 +1,5 @@ -// Minimal synthetic DICOM (Explicit VR Little Endian) for tests. -// Emits just enough tags for ITK/GDCM to categorize and load a series: -// SOP Class/Instance UIDs, Study/SeriesInstanceUID, SeriesNumber, -// AcquisitionNumber, Modality, -// Patient identifiers, ImageOrientationPatient, ImagePositionPatient, -// PixelSpacing, SliceThickness, image geometry, and constant-valued PixelData. +// Synthetic Part 10 DICOM files for tests, written in Explicit VR Little Endian +// unless a writer says otherwise. const SOP_CLASS_MR = '1.2.840.10008.5.1.4.1.1.4'; const SOP_CLASS_ULTRASOUND_MULTIFRAME = '1.2.840.10008.5.1.4.1.1.3.1'; @@ -13,9 +9,6 @@ const TS_JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; const enc = new TextEncoder(); -const padUi = (s: string) => (s.length % 2 === 0 ? s : `${s}\0`); -const padText = (s: string) => (s.length % 2 === 0 ? s : `${s} `); - const writeShort = (v: number) => { const b = new Uint8Array(2); new DataView(b.buffer).setUint16(0, v, true); @@ -28,6 +21,12 @@ const writeLong = (v: number) => { return b; }; +const writeDouble = (v: number) => { + const b = new Uint8Array(8); + new DataView(b.buffer).setFloat64(0, v, true); + return b; +}; + const tagBytes = (group: number, element: number) => { const b = new Uint8Array(4); const dv = new DataView(b.buffer); @@ -47,122 +46,108 @@ export const combine = (...arr: Uint8Array[]) => { return out; }; -// Short-form explicit VR (2-byte length): UI, CS, DA, DS, IS, LO, PN, SH, US, UL, ... -export const elemShort = ( +/** VRs whose explicit header has 2 reserved bytes and a 4-byte length. */ +export const LONG_FORM_VRS = new Set( + 'OB OD OF OL OV OW SQ SV UC UN UR UT'.split(' ') +); + +const elementHeader = ( group: number, element: number, vr: string, - value: Uint8Array + length: number ) => combine( tagBytes(group, element), enc.encode(vr), - writeShort(value.length), - value + ...(LONG_FORM_VRS.has(vr) + ? [new Uint8Array(2), writeLong(length)] + : [writeShort(length)]) ); -export const LONG_FORM_VRS = new Set([ - 'OB', - 'OD', - 'OF', - 'OL', - 'OV', - 'OW', - 'SQ', - 'SV', - 'UC', - 'UN', - 'UR', - 'UT', -]); - -// Long-form explicit VR (2-byte reserved + 4-byte length): LONG_FORM_VRS. -export const elemLong = ( +/** One Explicit VR LE element, short or long form as the VR requires. */ +export const rawElement = ( group: number, element: number, vr: string, value: Uint8Array -) => - combine( - tagBytes(group, element), - enc.encode(vr), - new Uint8Array(2), - writeLong(value.length), - value - ); +) => combine(elementHeader(group, element, vr, value.length), value); + +const textElement = + (vr: string) => (group: number, element: number, value: string) => + rawElement( + group, + element, + vr, + enc.encode(value.length % 2 ? value + (vr === 'UI' ? '\0' : ' ') : value) + ); -const ui = (g: number, e: number, v: string) => - elemShort(g, e, 'UI', enc.encode(padUi(v))); -const cs = (g: number, e: number, v: string) => - elemShort(g, e, 'CS', enc.encode(padText(v))); -const pn = (g: number, e: number, v: string) => - elemShort(g, e, 'PN', enc.encode(padText(v))); -const lo = (g: number, e: number, v: string) => - elemShort(g, e, 'LO', enc.encode(padText(v))); -const sh = (g: number, e: number, v: string) => - elemShort(g, e, 'SH', enc.encode(padText(v))); -const da = (g: number, e: number, v: string) => - elemShort(g, e, 'DA', enc.encode(padText(v))); -const is = (g: number, e: number, v: string) => - elemShort(g, e, 'IS', enc.encode(padText(v))); -const ds = (g: number, e: number, v: string) => - elemShort(g, e, 'DS', enc.encode(padText(v))); +const ui = textElement('UI'); +const cs = textElement('CS'); +const pn = textElement('PN'); +const lo = textElement('LO'); +const sh = textElement('SH'); +const da = textElement('DA'); +const is = textElement('IS'); +export const ds = textElement('DS'); const us = (g: number, e: number, v: number) => - elemShort(g, e, 'US', writeShort(v)); - -const writeDouble = (v: number) => { - const b = new Uint8Array(8); - new DataView(b.buffer).setFloat64(0, v, true); - return b; -}; - + rawElement(g, e, 'US', writeShort(v)); +export const ul = (g: number, e: number, v: number) => + rawElement(g, e, 'UL', writeLong(v)); const fd = (g: number, e: number, v: number) => - elemShort(g, e, 'FD', writeDouble(v)); + rawElement(g, e, 'FD', writeDouble(v)); // A PN whose bytes are already encoded in some Specific Character Set, padded // to DICOM's even length with a space. const pnRaw = (g: number, e: number, v: Uint8Array) => - elemShort( + rawElement( g, e, 'PN', v.length % 2 === 0 ? v : combine(v, new Uint8Array([0x20])) ); -// One Explicit VR LE element, short or long form as the VR requires. Lets a -// fixture write a VR this helper has no named writer for. -export const rawElement = ( - group: number, - element: number, - vr: string, - value: Uint8Array -) => - LONG_FORM_VRS.has(vr) - ? elemLong(group, element, vr, value) - : elemShort(group, element, vr, value); - // An AT value is the referenced tag as two little-endian unsigned shorts. export const attributeTagValue = (group: number, element: number) => tagBytes(group, element); const ITEM_GROUP = 0xfffe; const ITEM_TAG = 0xe000; -const ITEM_DELIMITER_TAG = 0xe00d; -const SEQUENCE_DELIMITER_TAG = 0xe0dd; const UNDEFINED_LENGTH = 0xffffffff; +const itemHeader = (length: number) => + combine(tagBytes(ITEM_GROUP, ITEM_TAG), writeLong(length)); + +const delimiter = (tag: number) => + combine(tagBytes(ITEM_GROUP, tag), writeLong(0)); +const ITEM_DELIMITER = delimiter(0xe00d); +const SEQUENCE_DELIMITER = delimiter(0xe0dd); + // One sequence item of defined length, holding the elements given. export const sequenceItem = (content: Uint8Array) => - combine(tagBytes(ITEM_GROUP, ITEM_TAG), writeLong(content.length), content); + combine(itemHeader(content.length), content); + +/** + * A defined-length sequence of defined-length items, so a reader that skips + * sequences and one that descends into them both stay in step. + */ +export const sequence = (group: number, element: number, items: Uint8Array[]) => + rawElement(group, element, 'SQ', combine(...items.map(sequenceItem))); // One sequence item whose length the delimiter that follows it declares. export const undefinedLengthItem = (content: Uint8Array) => + combine(itemHeader(UNDEFINED_LENGTH), content, ITEM_DELIMITER); + +const undefinedLengthElement = ( + group: number, + element: number, + vr: string, + items: Uint8Array +) => combine( - tagBytes(ITEM_GROUP, ITEM_TAG), - writeLong(UNDEFINED_LENGTH), - content, - tagBytes(ITEM_GROUP, ITEM_DELIMITER_TAG), - writeLong(0) + elementHeader(group, element, vr, UNDEFINED_LENGTH), + items, + SEQUENCE_DELIMITER ); /** @@ -174,27 +159,14 @@ export const undefinedLengthSequence = ( group: number, element: number, items: Uint8Array -) => - combine( - tagBytes(group, element), - enc.encode('SQ'), - new Uint8Array(2), - writeLong(UNDEFINED_LENGTH), - items, - tagBytes(ITEM_GROUP, SEQUENCE_DELIMITER_TAG), - writeLong(0) - ); +) => undefinedLengthElement(group, element, 'SQ', items); /** An unknown sequence retains its Implicit VR LE items inside an explicit UN. */ export const undefinedLengthUnknown = ( group: number, element: number, items: Uint8Array -) => { - const bytes = undefinedLengthSequence(group, element, items); - bytes.set(enc.encode('UN'), 4); - return bytes; -}; +) => undefinedLengthElement(group, element, 'UN', items); // Items and delimiters carry no VR in either syntax, so only the elements // inside each item change shape. Item lengths must be defined. @@ -207,7 +179,7 @@ const itemsToImplicitVr = (value: Uint8Array): Uint8Array => { const element = view.getUint16(offset + 2, true); const length = view.getUint32(offset + 4, true); const contentStart = offset + 8; - if (group !== 0xfffe) + if (group !== ITEM_GROUP) throw new Error(`Expected an item tag, got ${group.toString(16)}`); if (element !== ITEM_TAG) { out.push(value.subarray(offset, contentStart)); @@ -216,10 +188,11 @@ const itemsToImplicitVr = (value: Uint8Array): Uint8Array => { } if (length === UNDEFINED_LENGTH) throw new Error('Undefined-length items are not supported'); - const content = toImplicitVr( - value.subarray(contentStart, contentStart + length) + out.push( + sequenceItem( + toImplicitVr(value.subarray(contentStart, contentStart + length)) + ) ); - out.push(tagBytes(group, element), writeLong(content.length), content); offset = contentStart + length; } return combine(...out); @@ -243,7 +216,7 @@ export const toImplicitVr = (dataset: Uint8Array): Uint8Array => { const explicitValue = dataset.subarray(valueStart, valueStart + length); const value = vr === 'SQ' ? itemsToImplicitVr(explicitValue) : explicitValue; - out.push(combine(tagBytes(group, element), writeLong(value.length), value)); + out.push(tagBytes(group, element), writeLong(value.length), value); offset = valueStart + length; } return combine(...out); @@ -273,11 +246,6 @@ const rgbFrame = (samples: readonly number[], count: number, bits: number) => { return bytes; }; -// A single-item sequence with an explicit item length, so a reader that skips -// sequences and one that descends into them both stay in step. -const sequenceOfOneItem = (g: number, e: number, item: Uint8Array) => - elemLong(g, e, 'SQ', sequenceItem(item)); - export type SyntheticSliceOptions = { studyUid: string; seriesUid: string; @@ -335,7 +303,29 @@ export type SyntheticSliceOptions = { extraElements?: readonly Uint8Array[]; }; -export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { +/** Wraps an encoded data set in a preamble and Explicit VR LE file meta. */ +export const part10File = ( + sopClassUid: string, + sopInstanceUid: string, + transferSyntaxUid: string, + dataset: Uint8Array +) => { + const meta = combine( + rawElement(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), + ui(0x0002, 0x0002, sopClassUid), + ui(0x0002, 0x0003, sopInstanceUid), + ui(0x0002, 0x0010, transferSyntaxUid) + ); + return combine( + new Uint8Array(128), + enc.encode('DICM'), + ul(0x0002, 0x0000, meta.length), + meta, + dataset + ); +}; + +export function buildSyntheticDicom(opts: SyntheticSliceOptions) { const { studyUid, seriesUid, @@ -355,7 +345,7 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { rgbPixels, framePixelValues, rootGeometry = true, - pixelSpacing = [1, 1] as const, + pixelSpacing = [1, 1], spacingBetweenSlices, sliceThickness = 1, modality = 'MR', @@ -410,16 +400,14 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { ...(ultrasoundRegion == null ? [] : [ - sequenceOfOneItem( - 0x0018, - 0x6011, + sequence(0x0018, 0x6011, [ combine( us(0x0018, 0x6024, 3), us(0x0018, 0x6026, 3), fd(0x0018, 0x602c, ultrasoundRegion.physicalDeltaX), fd(0x0018, 0x602e, ultrasoundRegion.physicalDeltaY) - ) - ), + ), + ]), ]), ui(0x0020, 0x000d, studyUid), ui(0x0020, 0x000e, seriesUid), @@ -431,18 +419,8 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { is(0x0020, 0x0013, String(instanceNumber)), ...(rootGeometry ? [ - ds( - 0x0020, - 0x0032, - imagePositionPatient === null - ? '' - : imagePositionPatient.map((n) => n.toString()).join('\\') - ), - ds( - 0x0020, - 0x0037, - imageOrientationPatient.map((n) => n.toString()).join('\\') - ), + ds(0x0020, 0x0032, imagePositionPatient?.join('\\') ?? ''), + ds(0x0020, 0x0037, imageOrientationPatient.join('\\')), ] : []), us(0x0028, 0x0002, rgbPixels ? 3 : 1), @@ -453,9 +431,7 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { : []), us(0x0028, 0x0010, rows), us(0x0028, 0x0011, cols), - ...(rootGeometry - ? [ds(0x0028, 0x0030, pixelSpacing.map((n) => n.toString()).join('\\'))] - : []), + ...(rootGeometry ? [ds(0x0028, 0x0030, pixelSpacing.join('\\'))] : []), us(0x0028, 0x0100, bitsAllocated), us(0x0028, 0x0101, bitsStored), us(0x0028, 0x0102, highBit), @@ -465,23 +441,15 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { : [ds(0x0028, 0x1052, String(rescaleIntercept))]), ...(rescaleSlope == null ? [] : [ds(0x0028, 0x1053, String(rescaleSlope))]), ...extraElements, - elemLong(0x7fe0, 0x0010, bitsAllocated === 8 ? 'OB' : 'OW', pixels) + rawElement(0x7fe0, 0x0010, bitsAllocated === 8 ? 'OB' : 'OW', pixels) ); - const dataset = implicitVr ? toImplicitVr(explicitDataset) : explicitDataset; - - const fileMetaBody = combine( - elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), - ui(0x0002, 0x0002, sopClassUid), - ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, implicitVr ? TS_IMPLICIT_VR_LE : TS_EXPLICIT_VR_LE) - ); - const fileMeta = combine( - elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), - fileMetaBody + return part10File( + sopClassUid, + sopUid, + implicitVr ? TS_IMPLICIT_VR_LE : TS_EXPLICIT_VR_LE, + implicitVr ? toImplicitVr(explicitDataset) : explicitDataset ); - - return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); } /** The bytes a Part 10 file spends on its preamble and DICM prefix. */ @@ -517,33 +485,15 @@ export function encapsulatedPixelData({ const items = frames.map((fragments) => combine(...fragments.map(sequenceItem)) ); - const starts = items.reduce( - (offsets, _, index) => - index === 0 - ? [0] - : [...offsets, offsets[index - 1] + items[index - 1].length], - [] + const starts = items.map((_, index) => + items.slice(0, index).reduce((offset, item) => offset + item.length, 0) ); const table = offsetTable ? combine(...starts.map(writeLong)) : new Uint8Array(); - return combine( - sequenceItem(table), - ...items, - tagBytes(ITEM_GROUP, SEQUENCE_DELIMITER_TAG), - writeLong(0) - ); + return combine(sequenceItem(table), ...items, SEQUENCE_DELIMITER); } -const encapsulatedElement = (value: Uint8Array) => - combine( - tagBytes(0x7fe0, 0x0010), - enc.encode('OB'), - new Uint8Array(2), - writeLong(UNDEFINED_LENGTH), - value - ); - export type SyntheticCineOptions = { studyUid: string; seriesUid: string; @@ -562,9 +512,7 @@ export type SyntheticCineOptions = { extraElements?: readonly Uint8Array[]; }; -export function buildSyntheticCineDicom( - opts: SyntheticCineOptions -): Uint8Array { +export function buildSyntheticCineDicom(opts: SyntheticCineOptions) { const { studyUid, seriesUid, @@ -572,7 +520,7 @@ export function buildSyntheticCineDicom( numberOfFrames = 3, rows = 4, cols = 5, - pixelSpacing = [1, 1] as const, + pixelSpacing = [1, 1], patientName = 'TEST', patientId = 'TEST001', seriesNumber = 1, @@ -581,10 +529,6 @@ export function buildSyntheticCineDicom( extraElements = [], } = opts; const frames = encapsulated?.frames.length ?? numberOfFrames; - const transferSyntax = encapsulated ? TS_JPEG_BASELINE : TS_EXPLICIT_VR_LE; - - const pixelData = new Uint8Array(numberOfFrames * rows * cols); - for (let i = 0; i < pixelData.length; i++) pixelData[i] = i % 251; const dataset = combine( ui(0x0008, 0x0016, SOP_CLASS_ULTRASOUND_MULTIFRAME), @@ -606,29 +550,34 @@ export function buildSyntheticCineDicom( is(0x0028, 0x0008, String(frames)), us(0x0028, 0x0010, rows), us(0x0028, 0x0011, cols), - ds(0x0028, 0x0030, pixelSpacing.map((n) => n.toString()).join('\\')), + ds(0x0028, 0x0030, pixelSpacing.join('\\')), us(0x0028, 0x0100, 8), us(0x0028, 0x0101, 8), us(0x0028, 0x0102, 7), us(0x0028, 0x0103, 0), ...extraElements, encapsulated - ? encapsulatedElement(encapsulatedPixelData(encapsulated)) - : elemLong(0x7fe0, 0x0010, 'OB', pixelData) + ? combine( + elementHeader(0x7fe0, 0x0010, 'OB', UNDEFINED_LENGTH), + encapsulatedPixelData(encapsulated) + ) + : rawElement( + 0x7fe0, + 0x0010, + 'OB', + Uint8Array.from( + { length: numberOfFrames * rows * cols }, + (_, i) => i % 251 + ) + ) ); - const fileMetaBody = combine( - elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), - ui(0x0002, 0x0002, SOP_CLASS_ULTRASOUND_MULTIFRAME), - ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, transferSyntax) - ); - const fileMeta = combine( - elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), - fileMetaBody + return part10File( + SOP_CLASS_ULTRASOUND_MULTIFRAME, + sopUid, + encapsulated ? TS_JPEG_BASELINE : TS_EXPLICIT_VR_LE, + dataset ); - - return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); } // Pseudo-UID unique per call within a test process. All-numeric so it diff --git a/tests/specs/utils.ts b/tests/specs/utils.ts index 82e4d85eb..a4bc07d1b 100644 --- a/tests/specs/utils.ts +++ b/tests/specs/utils.ts @@ -347,7 +347,7 @@ export async function openSpacingDetails() { const ACQUISITION_SLICE_SPACING = 2.5; -export type AcquisitionPass = { +type AcquisitionPass = { number: number; firstSliceZ: number; sliceCount: number; From 39559721356e49ee53a18badf129b00eed08a118 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 15 Nov 2026 06:14:28 -0500 Subject: [PATCH 09/32] fix(dicom): address the final review findings Read the modality rescale from the Pixel Value Transformation functional group only for the IODs that define it there, as GDCM does. Other SOP classes, such as multi-frame secondary capture and ophthalmic tomography, use the top-level Rescale, so a native and a compressed copy of the same file now load with the same values and buffer type. Reject what a header gets wrong before it costs time or memory. A lone native instance that declares more frames than its Pixel Data holds fails at allocation, per-frame reads stop at the functional groups present, a Number of Frames that is not a positive integer counts as one, an element value cut short ends the header read with an error instead of a clipped value, and a Transfer Syntax UID padded with a space is still recognised. Frames split by a Basic Offset Table no longer take quadratic time. Release a pooled request when its URL read fails, not only when it ends. Restore no saved state onto a volume that two saved images now share, and name those images in the restore notice instead of placing their masks on the merged grid. Plan a series within its study, so a Series Instance UID reused in another study no longer joins its images. Export the types the public signatures name, correct two README claims, and add tests for behaviour no test protected: writes after abort, values the buffer cannot hold, retrying only failed frames, duplicate decoder units, disposal of running and idle GDCM workers, and the copy made before handing bytes to the metadata worker. --- packages/dicom/README.md | 18 ++-- .../__tests__/instanceFacts.spec.ts | 6 +- .../__tests__/instanceRegistry.spec.ts | 26 +++++ .../__tests__/multiframeGeometry.spec.ts | 12 +++ .../collections/__tests__/sliceFixture.ts | 34 ++++--- .../dicom/core/collections/instanceFacts.ts | 12 ++- .../core/collections/multiframeGeometry.ts | 6 +- .../__tests__/dicomHeaderEncodings.spec.ts | 16 +++ packages/dicom/core/header/dicomParser.ts | 9 +- packages/dicom/core/index.ts | 20 +++- .../metadata/__tests__/dcmjsParser.spec.ts | 15 ++- .../__tests__/modalityRescale.spec.ts | 98 +++++++++++++++++++ packages/dicom/core/metadata/dcmjsParser.ts | 46 +++++++-- .../dicom/core/metadata/modalityRescale.ts | 35 ++++++- .../core/pixels/__tests__/frameIndex.spec.ts | 4 +- .../core/pixels/__tests__/nativeFrame.spec.ts | 2 + .../dicom/core/pixels/encapsulatedFrames.ts | 7 +- packages/dicom/core/pixels/frameIndex.ts | 56 ++++++++--- packages/dicom/core/pixels/pixelDecoder.ts | 7 +- .../runtime/__tests__/dicomRuntime.spec.ts | 15 +++ .../runtime/__tests__/metadataReader.spec.ts | 26 ++++- .../dicom/core/runtime/createDicomRuntime.ts | 2 +- .../core/source/__tests__/byteSource.spec.ts | 29 ++++++ packages/dicom/core/source/byteSource.ts | 32 +++--- .../volume/__tests__/allocateVolume.spec.ts | 26 +++++ .../core/volume/__tests__/enhancedFixture.ts | 1 + .../core/volume/__tests__/loadFrames.spec.ts | 52 ++++++++++ .../core/volume/__tests__/loadVolume.spec.ts | 54 ++++++++++ .../core/volume/__tests__/pixelFormat.spec.ts | 24 +++++ packages/dicom/core/volume/allocateVolume.ts | 7 ++ packages/dicom/core/volume/loadVolume.ts | 16 ++- packages/dicom/core/volume/pixelFormat.ts | 15 ++- .../importDicomInstanceSources.spec.ts | 28 +++++- .../__tests__/missingArchiveMember.spec.ts | 17 ++++ src/io/import/importDataSources.ts | 77 +++++++++++---- src/io/import/processors/restoreStateFile.ts | 14 ++- .../dicom-pages/volumeCorpusReference.py | 27 ++++- tests/specs/dicom-native-parity.e2e.ts | 3 + 38 files changed, 775 insertions(+), 119 deletions(-) create mode 100644 packages/dicom/core/metadata/__tests__/modalityRescale.spec.ts diff --git a/packages/dicom/README.md b/packages/dicom/README.md index a2ffa62e6..772442970 100644 --- a/packages/dicom/README.md +++ b/packages/dicom/README.md @@ -93,8 +93,8 @@ whether the latest ranged response honoured Range. Ranged URL reads bypass the HTTP cache, since Chrome can answer a Range from an entry an earlier cancelled read left behind with status 200 and only the range's bytes. A status other than 200, 206 or 416 fails with `HTTP for `. The `fetch` it was -given sees its signal abort once a body has been read to the end, which is how -a pooled request is released. +given sees its signal abort once a body has been read to the end, so a pooled +request lets go of the pool. `readBytes(source, signal, range?)` reads a source or a range into memory. Instances keep no bytes; read the source again when the original bytes are needed. @@ -138,7 +138,7 @@ the batch touches. Each `InstanceCollectionUpdate` carries a stable `id` that starts with the Series Instance UID, the planned `collection`, `members` in planned order and, aligned with them, `provenance`: the batch's own instance wherever it -re-supplied one. `kind` is `image`, or `segmentation` when the first member's +re-supplied one with the same header facts. `kind` is `image`, or `segmentation` when the first member's Modality is SEG; a segmentation reader turns those labels into its own image. `change` says how the collection differs from what was last committed under its id: `new`, `unchanged` (same members and geometry, so an allocated volume @@ -147,7 +147,8 @@ A collection's `label` names what separated it from the rest of its series and is null when nothing did. `forgetCollection(state, id)` drops a collection and its instances, so a later -import plans them afresh. `seriesKeyOf` gives the series an instance plans in. +import plans them afresh. `seriesKeyOf` gives the series an instance plans in: +its Series Instance UID within its Study Instance UID. ## Volumes and loading @@ -219,7 +220,11 @@ ending at High Bit (fewer stored bits only in 16 bit words), big endian only for 16 bit words, one modality rescale for all frames, and no overlay, curve, Modality LUT, palette or ICC data. GDCM plans the whole instance as one unit. Both apply one modality transform to the entire instance and decline, from the -header, an instance whose frames differ in slope or intercept. Once a URL +header, an instance whose frames differ in slope or intercept. The transform +comes from the 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 reads it; other +SOP classes use the top-level Rescale Slope and Intercept. Once a URL source shows that its server ignores Range, the remaining ranged units of that instance come from one read instead of one download each. @@ -256,7 +261,8 @@ pad byte. ## Runtime `createDicomRuntime(options)` owns the request pool (`requestConcurrency`, -default 24, exposed as `readConcurrency`), two metadata parser workers +default 24, exposed as `readConcurrency`; it bounds requests waiting for their +response headers, not bodies being read), two metadata parser workers (`metadataWorkerFactory` for another asset layout; its worker exposes `readPublicDataset`) and the GDCM decoder, which runs at most `decodeConcurrency` workers at once (default half the cores, at most four; each worker carries its diff --git a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts index 914911ba1..c37a7bb1b 100644 --- a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts @@ -278,10 +278,10 @@ describe('instance facts', () => { }); describe('seriesKeyOf', () => { - it('is the series instance uid so a collection id carries it as a prefix', () => { - expect(seriesKeyOf(metadata())).toBe('1.2.3'); + it('leads with the series instance uid so a collection id carries it as a prefix', () => { + expect(seriesKeyOf(metadata())).toBe('1.2.3|1.2'); expect(seriesKeyOf(metadata({ [Tags.SeriesInstanceUID]: '1.2.3 ' }))).toBe( - '1.2.3' + '1.2.3|1.2' ); }); diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts index eaacd8d34..faf2baaa7 100644 --- a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -62,6 +62,32 @@ describe('pure instance registry', () => { expect(update.id.startsWith(SERIES_UID)).toBe(true); }); + // Anonymizers and phantom protocols can reuse one series' UIDs in another study. + it.each([ + ['its own', 'b'], + ['the same', 'a'], + ])( + 'plans a series uid reused in another study, with %s SOP uids, apart', + (_name, prefix) => { + const study = (uid: string, sop: string) => + [0, 1, 2].map((z) => + slice({ + sop: `${sop}${z}`, + z, + tags: { [Tags.StudyInstanceUID]: uid }, + }) + ); + const first = study('1.2.3.1', 'a'); + const second = study('1.2.3.2', prefix); + + const [initial, reused] = registerAll([first, second]); + + expect(reused.updates.map((update) => update.members)).toEqual([second]); + expect(reused.updates[0].id).not.toBe(initial.updates[0].id); + expect(reused.updates[0].id.startsWith(SERIES_UID)).toBe(true); + } + ); + it.each([ ['one batch', [[0, 1, 2]]], ['a late earlier slice', [[1, 2], [0]]], diff --git a/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts b/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts index 4f783ad69..2218ae828 100644 --- a/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts +++ b/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts @@ -88,6 +88,18 @@ describe('multiframe geometry', () => { } ); + it('reports more declared frames than per-frame groups as unreadable, however many are declared', () => { + const metadata = enhanced( + ctShared(), + [0, 1].map((z) => positioned(`0\\0\\${z}`)), + { '00280008': String(2 ** 32) } + ); + expect(collectionOf(metadata).reconstruction).toMatchObject({ + kind: 'irregular', + reason: 'unreadable-geometry', + }); + }); + it('does not report normal segment-major SEG frames as an irregular volume', () => { const metadata = enhanced( ctShared(), diff --git a/packages/dicom/core/collections/__tests__/sliceFixture.ts b/packages/dicom/core/collections/__tests__/sliceFixture.ts index b9cb3215a..6c6ee666c 100644 --- a/packages/dicom/core/collections/__tests__/sliceFixture.ts +++ b/packages/dicom/core/collections/__tests__/sliceFixture.ts @@ -13,7 +13,7 @@ export type SliceOptions = { orientation?: string | null; instanceNumber?: number | null; modality?: string; - // Extra tags, keyed 'gggg|eeee'. + // Extra tags, keyed 'gggg|eeee'; a fixed tag given here is replaced. tags?: Record; }; @@ -39,21 +39,23 @@ export function sliceDataset(options: SliceOptions = {}) { tags = {}, } = options; - return datasetFromTags([ - [Tags.StudyInstanceUID, '1.2.826.0.1.3680043.9.1'], - [Tags.PatientID, 'patient-1'], - [Tags.SeriesNumber, '1'], - [Tags.Modality, modality], - [Tags.Rows, rows], - [Tags.Columns, '4'], - [Tags.SamplesPerPixel, '1'], - ...present(Tags.ImageOrientationPatient, orientation), - ...present(Tags.SeriesInstanceUID, series), - ...present(Tags.SOPInstanceUID, sop), - ...present(Tags.ImagePositionPatient, z, (value) => `0\\0\\${value}`), - ...present('0020|0013', instanceNumber), - ...Object.entries(tags), - ]); + return datasetFromTags( + new Map([ + [Tags.StudyInstanceUID, '1.2.826.0.1.3680043.9.1'], + [Tags.PatientID, 'patient-1'], + [Tags.SeriesNumber, '1'], + [Tags.Modality, modality], + [Tags.Rows, rows], + [Tags.Columns, '4'], + [Tags.SamplesPerPixel, '1'], + ...present(Tags.ImageOrientationPatient, orientation), + ...present(Tags.SeriesInstanceUID, series), + ...present(Tags.SOPInstanceUID, sop), + ...present(Tags.ImagePositionPatient, z, (value) => `0\\0\\${value}`), + ...present('0020|0013', instanceNumber), + ...Object.entries(tags), + ]) + ); } /** The planner's facts for one slice, read the way a real header is. */ diff --git a/packages/dicom/core/collections/instanceFacts.ts b/packages/dicom/core/collections/instanceFacts.ts index 6f83ddc26..820e237b2 100644 --- a/packages/dicom/core/collections/instanceFacts.ts +++ b/packages/dicom/core/collections/instanceFacts.ts @@ -180,17 +180,21 @@ export function readInstanceDetails(metadata: DicomDataset) { const NO_SERIES_UID = 'no-series'; /** - * The grouping key for one instance's series. Instances of different series - * are planned independently. + * The grouping key for one instance's series, led by its Series Instance UID. + * Instances of different series are planned independently. */ export function seriesKeyOf(metadata: DicomDataset) { const seriesUid = textOf(metadata, Tags.SeriesInstanceUID); - if (seriesUid !== null) return seriesUid; + const studyUid = encodeURIComponent( + textOf(metadata, Tags.StudyInstanceUID) ?? '' + ); + // A series is identified within its study, as DICOMweb addresses it. + if (seriesUid !== null) return `${encodeURIComponent(seriesUid)}|${studyUid}`; // Escaped, so moving a separator from one part to the other changes the key. return [ NO_SERIES_UID, - encodeURIComponent(textOf(metadata, Tags.StudyInstanceUID) ?? ''), + studyUid, encodeURIComponent(textOf(metadata, Tags.PatientID) ?? ''), ].join('|'); } diff --git a/packages/dicom/core/collections/multiframeGeometry.ts b/packages/dicom/core/collections/multiframeGeometry.ts index 59f20af58..94f46fd03 100644 --- a/packages/dicom/core/collections/multiframeGeometry.ts +++ b/packages/dicom/core/collections/multiframeGeometry.ts @@ -47,8 +47,10 @@ export function multiframeGeometry(metadata: DicomDataset, count: number) { const groups = perFrameGroups(metadata); const shared = sequenceItems(metadata, SHARED_GROUPS); if (count < 2 || (shared.length === 0 && groups.length === 0)) return null; - const frames = Array.from({ length: count }, (_, index) => - readGeometryFacts(metadata, index) + // Frames past the per-frame groups read the shared or root tags alike. + const frames = Array.from( + { length: Math.min(count, groups.length + 1) }, + (_, index) => readGeometryFacts(metadata, index) ); const first = frames[0]; const direction = storageDirection(frames); diff --git a/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts b/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts index d7f6d091a..3aa3fd29d 100644 --- a/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts +++ b/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts @@ -106,6 +106,22 @@ describe('streamed header encodings', () => { } ); + it('reads a transfer syntax UID padded with a space instead of a null', async () => { + const bytes = syntheticSlice({ implicitVr: true, rows: 4, cols: 4 }); + const uid = new TextDecoder('latin1') + .decode(bytes) + .indexOf('1.2.840.10008.1.2\0'); + bytes[uid + 17] = 0x20; + const instance = await readHeader(bytes, 7); + expect(instance.transferSyntaxUid).toBe('1.2.840.10008.1.2'); + expect(instance.pixelData).toEqual({ + offset: bytes.length - 32 - 8, + valueOffset: bytes.length - 32, + length: 32, + }); + expect(getDatasetTag(instance.dataset, '00280010')).toBe('4'); + }); + it('reads past a defined-length sequence whose item is Implicit VR in an Explicit VR file', async () => { const item = toImplicitVr( concatBytes([ diff --git a/packages/dicom/core/header/dicomParser.ts b/packages/dicom/core/header/dicomParser.ts index 207e8ffa5..6218f08e9 100644 --- a/packages/dicom/core/header/dicomParser.ts +++ b/packages/dicom/core/header/dicomParser.ts @@ -1,5 +1,5 @@ import StreamingByteReader from './streamingByteReader'; -import { toAscii, asCoroutine } from '../utils'; +import { toAscii, asCoroutine, trimDicomPadding } from '../utils'; import { DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN, EXPLICIT_VR_BIG_ENDIAN, @@ -267,9 +267,10 @@ function* readFileMetaInfo( if (!transferSyntaxUidElement.data) throw new Error('Did not get data for the transfer syntax UID element'); - const transferSyntaxUid = toAscii(transferSyntaxUidElement.data, { - ignoreNulls: true, - }); + // Some writers pad the UID with a space rather than the null UI requires. + const transferSyntaxUid = trimDicomPadding( + toAscii(transferSyntaxUidElement.data, { ignoreNulls: true }) + ); // Compressed bytes can resemble meta elements. The complete reader will // locate the end of group 2 and inflate the dataset before walking it. diff --git a/packages/dicom/core/index.ts b/packages/dicom/core/index.ts index 753ccbb97..3a5179131 100644 --- a/packages/dicom/core/index.ts +++ b/packages/dicom/core/index.ts @@ -3,7 +3,9 @@ export { fromBlob, fromUrl, readBytes, + type ByteRange, type ByteSource, + type RangeSupport, } from './source/byteSource'; // Instances @@ -12,6 +14,10 @@ export { type Instance, type ReadInstanceOptions, } from './instance/readInstance'; +export type { + ImageImportPolicy, + PixelDataElement, +} from './header/readDicomHeader'; export { IMPLICIT_VR_LITTLE_ENDIAN, EXPLICIT_VR_LITTLE_ENDIAN, @@ -19,7 +25,11 @@ export { } from './metadata/dicomLayout'; // Datasets -export { readDicomDataset, type DicomDataset } from './metadata/dicomDataset'; +export { + readDicomDataset, + type DicomDataset, + type DicomElement, +} from './metadata/dicomDataset'; export { getDatasetTag, getDatasetModality } from './metadata/datasetAccess'; export { sequenceItems } from './metadata/functionalGroups'; export { trimDicomPadding } from './utils'; @@ -45,6 +55,7 @@ export { allocateVolume, type Volume } from './volume/allocateVolume'; export { loadVolume, middleSlot, + type LoadVolumeOptions, type VolumeUpdate, type Extent, } from './volume/loadVolume'; @@ -60,7 +71,11 @@ export { fallbackSpacing, type SpatialMetadata, } from './metadata/spatialMetadata'; -export { unitToMm, ultrasoundRegionsOf } from './metadata/ultrasoundRegion'; +export { + unitToMm, + ultrasoundRegionsOf, + type UltrasoundRegions, +} from './metadata/ultrasoundRegion'; // Decoders export { @@ -86,6 +101,7 @@ export { type DicomRuntime, type DicomRuntimeOptions, } from './runtime/createDicomRuntime'; +export type { DicomAssets } from './runtime/gdcmDecoder'; // The byte reader under the header parser, which the app also uses to sniff file types export { default as StreamingByteReader } from './header/streamingByteReader'; diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts index 8836a3d20..7c4171928 100644 --- a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -8,7 +8,11 @@ import { parseDicomElements } from '../dcmjsParser'; import { PART_10_HEADER_LENGTH } from '../dicomLayout'; import { concatBytes } from '../../utils'; import { buildSlice } from '@/tests/specs/dicomElementFixtures'; -import { pixelDataStart, readHeader } from '@/tests/dicomSourceFixtures'; +import { + pixelDataStart, + readHeader, + syntheticSlice, +} from '@/tests/dicomSourceFixtures'; import { rawElement, sequenceItem, @@ -174,6 +178,15 @@ describe('lenient headers with standards-defined values', () => { ); }); + it('rejects a header cut short inside an element value', async () => { + const bytes = syntheticSlice({ studyDate: '20260101' }); + const date = new TextDecoder('latin1').decode(bytes).indexOf('20260101'); + const cut = bytes.slice(0, date + 6); + const message = 'Element (0008,0020) needs 8 bytes; 6 remain'; + expect(() => readDicomDataset(cut)).toThrow(message); + await expect(readHeader(cut)).rejects.toThrow(message); + }); + it('does not recover a nested sequence past its enclosing item', async () => { const inner = rawElement( 0x0008, diff --git a/packages/dicom/core/metadata/__tests__/modalityRescale.spec.ts b/packages/dicom/core/metadata/__tests__/modalityRescale.spec.ts new file mode 100644 index 000000000..618b7b596 --- /dev/null +++ b/packages/dicom/core/metadata/__tests__/modalityRescale.spec.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; +import { + hasUniformModalityRescale, + readModalityRescale, +} from '../modalityRescale'; +import { + enhanced, + groups, + sequence, + tags, +} from '../../volume/__tests__/enhancedFixture'; + +const transform = (slope: string, intercept: string) => + groups([ + sequence('00289145', [tags({ '00281053': slope, '00281052': intercept })]), + ]); + +const multiframe = ( + sopClassUid: string, + frames = [transform('3', '-500'), transform('3', '-500')], + root: Record = { '00281053': '2', '00281052': '-1000' } +) => enhanced(groups([]), frames, { '00080016': sopClassUid, ...root }); + +const TOP_LEVEL = { rescaleSlope: 2, rescaleIntercept: -1000 }; +const FUNCTIONAL_GROUP = { rescaleSlope: 3, rescaleIntercept: -500 }; + +// Each class was read by GDCM with both rescales present. +describe('readModalityRescale', () => { + it.each([ + ['Enhanced CT', '1.2.840.10008.5.1.4.1.1.2.1'], + ['Legacy Converted Enhanced CT', '1.2.840.10008.5.1.4.1.1.2.2'], + ['Enhanced MR', '1.2.840.10008.5.1.4.1.1.4.1'], + ['Legacy Converted Enhanced MR', '1.2.840.10008.5.1.4.1.1.4.4'], + ['Enhanced PET', '1.2.840.10008.5.1.4.1.1.130'], + ['Legacy Converted Enhanced PET', '1.2.840.10008.5.1.4.1.1.128.1'], + ['X-Ray 3D Angiographic', '1.2.840.10008.5.1.4.1.1.13.1.1'], + ['X-Ray 3D Craniofacial', '1.2.840.10008.5.1.4.1.1.13.1.2'], + ['Breast Tomosynthesis', '1.2.840.10008.5.1.4.1.1.13.1.3'], + ['Breast Projection For Presentation', '1.2.840.10008.5.1.4.1.1.13.1.4'], + ['Breast Projection For Processing', '1.2.840.10008.5.1.4.1.1.13.1.5'], + ['Segmentation', '1.2.840.10008.5.1.4.1.1.66.4'], + ])('reads the functional group transform of %s', (_name, sopClassUid) => { + expect(readModalityRescale(multiframe(sopClassUid))).toEqual( + FUNCTIONAL_GROUP + ); + }); + + it.each([ + ['Multi-frame Grayscale Word SC', '1.2.840.10008.5.1.4.1.1.7.3'], + ['Ophthalmic Tomography', '1.2.840.10008.5.1.4.1.1.77.1.5.4'], + ['Enhanced US Volume', '1.2.840.10008.5.1.4.1.1.6.2'], + ['Enhanced XA', '1.2.840.10008.5.1.4.1.1.12.1.1'], + ['Enhanced MR Color', '1.2.840.10008.5.1.4.1.1.4.3'], + ['Intravascular OCT', '1.2.840.10008.5.1.4.1.1.14.1'], + ['CT', '1.2.840.10008.5.1.4.1.1.2'], + ['MR', '1.2.840.10008.5.1.4.1.1.4'], + ['NM', '1.2.840.10008.5.1.4.1.1.20'], + ['RT Dose', '1.2.840.10008.5.1.4.1.1.481.2'], + ])('reads the top-level rescale of %s', (_name, sopClassUid) => { + expect(readModalityRescale(multiframe(sopClassUid))).toEqual(TOP_LEVEL); + }); + + it('falls back to the top-level rescale of an enhanced class', () => { + const dataset = multiframe('1.2.840.10008.5.1.4.1.1.2.1', [ + groups([]), + groups([]), + ]); + expect(readModalityRescale(dataset)).toEqual(TOP_LEVEL); + }); + + it('applies no rescale when only an unread functional group has one', () => { + const dataset = multiframe('1.2.840.10008.5.1.4.1.1.7.3', undefined, {}); + expect(readModalityRescale(dataset)).toEqual({ + rescaleSlope: 1, + rescaleIntercept: 0, + }); + }); +}); + +describe('hasUniformModalityRescale', () => { + const differing = [transform('1', '0'), transform('2', '0')]; + + it('compares the frames of a class whose transform is per frame', () => { + expect( + hasUniformModalityRescale( + multiframe('1.2.840.10008.5.1.4.1.1.2.1', differing) + ) + ).toBe(false); + }); + + it('ignores functional groups GDCM does not apply', () => { + expect( + hasUniformModalityRescale( + multiframe('1.2.840.10008.5.1.4.1.1.7.3', differing) + ) + ).toBe(true); + }); +}); diff --git a/packages/dicom/core/metadata/dcmjsParser.ts b/packages/dicom/core/metadata/dcmjsParser.ts index 758c846ed..2657035d0 100644 --- a/packages/dicom/core/metadata/dcmjsParser.ts +++ b/packages/dicom/core/metadata/dcmjsParser.ts @@ -185,7 +185,7 @@ const isKnownUnknown = ( return known !== undefined && known !== 'UN'; }; -const peekSequence = (dataSet: DicomReadStream, syntax: string) => { +const peekElementHead = (dataSet: DicomReadStream, syntax: string) => { const start = dataSet.offset; const implicit = syntax === IMPLICIT_VR_LITTLE_ENDIAN; dataSet.setEndian(syntax !== EXPLICIT_VR_BIG_ENDIAN); @@ -197,6 +197,18 @@ const peekSequence = (dataSet: DicomReadStream, syntax: string) => { const length = length32 ? dataSet.readUint32() : dataSet.readUint16(); const valueStart = dataSet.offset; dataSet.offset = start; + return { group, element, vr, length, valueStart }; +}; + +type ElementHead = ReturnType; + +const sequenceOf = ({ + group, + element, + vr, + length, + valueStart, +}: ElementHead) => { const knownUnknown = isKnownUnknown(vr, group, element); return needsSequenceReader(vr, length) || knownUnknown ? { @@ -276,7 +288,7 @@ const implicitElement = (group: number, element: number, value: Uint8Array) => { const readSequence = ( dataSet: DicomReadStream, syntax: string, - sequence: NonNullable> + sequence: NonNullable> ): ParsedElement => { const { group, element, valueStart, end } = sequence; if (end !== null && end > dataSet.endOffset) @@ -384,21 +396,37 @@ const readItemDelimiter = (dataSet: DicomReadStream, syntax: string) => { return true; }; +const isPixelData = ({ group, element }: { group: number; element: number }) => + group === 0x7fe0 && element === 0x0010; + +// dcmjs reads a text value cut short by the end of the bytes as a shorter value. +const assertValueFits = ( + dataSet: DicomReadStream, + head: ElementHead, + stopAtPixelData: boolean +) => { + const { group, element, length, valueStart } = head; + if (length === UNDEFINED_LENGTH || (stopAtPixelData && isPixelData(head))) + return; + const remain = dataSet.endOffset - valueStart; + if (length > remain) + throw new Error( + `Element (${hex4(group)},${hex4(element)}) needs ${length} bytes; ${remain} remain` + ); +}; + const readNextElement = ( dataSet: DicomReadStream, syntax: string, stopAtPixelData: boolean ) => { - const sequence = peekSequence(dataSet, syntax); - if ( - sequence && - stopAtPixelData && - sequence.group === 0x7fe0 && - sequence.element === 0x0010 - ) + const head = peekElementHead(dataSet, syntax); + const sequence = sequenceOf(head); + if (sequence && stopAtPixelData && isPixelData(sequence)) return { element: null, done: true }; if (sequence) return { element: readSequence(dataSet, syntax, sequence), done: false }; + assertValueFits(dataSet, head, stopAtPixelData); const element = DicomMessage._readTag( dataSet, diff --git a/packages/dicom/core/metadata/modalityRescale.ts b/packages/dicom/core/metadata/modalityRescale.ts index 8d2acf165..4d503e118 100644 --- a/packages/dicom/core/metadata/modalityRescale.ts +++ b/packages/dicom/core/metadata/modalityRescale.ts @@ -1,14 +1,43 @@ import type { DicomDataset } from './dicomDataset'; +import { getDatasetTag } from './datasetAccess'; import { getFrameTag, perFrameGroups } from './functionalGroups'; -import { numberOr } from '../utils'; +import { numberOr, trimDicomPadding } from '../utils'; + +// GDCM applies the Pixel Value Transformation functional group only for these +// SOP classes. The others' IODs keep the modality rescale at the top level. +const FUNCTIONAL_GROUP_RESCALE = new Set([ + '1.2.840.10008.5.1.4.1.1.2.1', // Enhanced CT + '1.2.840.10008.5.1.4.1.1.2.2', // Legacy Converted Enhanced CT + '1.2.840.10008.5.1.4.1.1.4.1', // Enhanced MR + '1.2.840.10008.5.1.4.1.1.4.4', // Legacy Converted Enhanced MR + '1.2.840.10008.5.1.4.1.1.130', // Enhanced PET + '1.2.840.10008.5.1.4.1.1.128.1', // Legacy Converted Enhanced PET + '1.2.840.10008.5.1.4.1.1.13.1.1', // X-Ray 3D Angiographic + '1.2.840.10008.5.1.4.1.1.13.1.2', // X-Ray 3D Craniofacial + '1.2.840.10008.5.1.4.1.1.13.1.3', // Breast Tomosynthesis + '1.2.840.10008.5.1.4.1.1.13.1.4', // Breast Projection X-Ray For Presentation + '1.2.840.10008.5.1.4.1.1.13.1.5', // Breast Projection X-Ray For Processing + '1.2.840.10008.5.1.4.1.1.66.4', // Segmentation +]); + +const rescaleTag = ( + metadata: DicomDataset | null | undefined, + tag: string, + frameIndex: number +) => + FUNCTIONAL_GROUP_RESCALE.has( + trimDicomPadding(getDatasetTag(metadata, '00080016') ?? '') + ) + ? getFrameTag(metadata, tag, frameIndex) + : getDatasetTag(metadata, tag); export const readModalityRescale = ( metadata: DicomDataset | null | undefined, frameIndex = 0 ) => ({ // GDCM reads a zero slope as 1; matching it keeps native and GDCM pixels equal. - rescaleSlope: numberOr(getFrameTag(metadata, '00281053', frameIndex), 1) || 1, - rescaleIntercept: numberOr(getFrameTag(metadata, '00281052', frameIndex), 0), + rescaleSlope: numberOr(rescaleTag(metadata, '00281053', frameIndex), 1) || 1, + rescaleIntercept: numberOr(rescaleTag(metadata, '00281052', frameIndex), 0), }); /** Whether every frame shares the first frame's slope and intercept. */ diff --git a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts index 89aa025c7..3b4b344d8 100644 --- a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts +++ b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts @@ -61,8 +61,8 @@ describe('indexFrames', () => { ], [ 'misshapen', - { extra: [{ tag: 0x00280008, vr: 'IS', value: '0' }] }, - /Number of Frames is unusable/, + { rows: 0 }, + /Rows, Columns or Samples per Pixel is unusable/, ], ] as const)( 'reports %s Pixel Data as unindexed', diff --git a/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts b/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts index a67bd3d0a..b9cccdee4 100644 --- a/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts +++ b/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts @@ -155,6 +155,7 @@ describe('nativeCapability', () => { [ 'a uniform per-frame rescale', { + sopClassUid: '1.2.840.10008.5.1.4.1.1.2.1', frames: 2, frameRescales: [ [2, 1], @@ -213,6 +214,7 @@ describe('nativeCapability', () => { [ 'differing per-frame rescale', { + sopClassUid: '1.2.840.10008.5.1.4.1.1.2.1', frames: 2, frameRescales: [ [1, 0], diff --git a/packages/dicom/core/pixels/encapsulatedFrames.ts b/packages/dicom/core/pixels/encapsulatedFrames.ts index 9b12c5e6a..7ece9ac87 100644 --- a/packages/dicom/core/pixels/encapsulatedFrames.ts +++ b/packages/dicom/core/pixels/encapsulatedFrames.ts @@ -60,9 +60,12 @@ const joinFragments = (fragments: readonly Fragment[]) => : concatBytes(fragments.map(({ bytes }) => bytes)); function framesFromOffsets(fragments: readonly Fragment[], offsets: number[]) { + const indexAt = new Map( + fragments.map((fragment, index) => [fragment.offset, index]) + ); const starts = offsets.map((offset, frame) => { - const index = fragments.findIndex((fragment) => fragment.offset === offset); - if (index < 0) + const index = indexAt.get(offset); + if (index === undefined) throw malformed( `Basic Offset Table entry ${frame} (${offset}) starts no fragment` ); diff --git a/packages/dicom/core/pixels/frameIndex.ts b/packages/dicom/core/pixels/frameIndex.ts index 7c9c03ae9..e7313025e 100644 --- a/packages/dicom/core/pixels/frameIndex.ts +++ b/packages/dicom/core/pixels/frameIndex.ts @@ -49,8 +49,16 @@ export const shapeOf = ({ dataset }: Instance) => { const positiveInteger = (value: number) => Number.isSafeInteger(value) && value > 0; -/** Byte ranges of every frame, from the header alone. */ -export function indexFrames(instance: Instance): FrameIndex { +type NativeLayout = Readonly<{ + kind: 'native'; + littleEndian: boolean; + frameLength: number; + frames: number; + valueOffset: number; + length: number; +}>; + +function nativeLayout(instance: Instance): NativeLayout | FrameIndex { const { pixelData, transferSyntaxUid } = instance; if (!pixelData || !transferSyntaxUid) return unindexed('The header locates no Pixel Data'); @@ -65,27 +73,49 @@ export function indexFrames(instance: Instance): FrameIndex { return unindexed('Pixel Data has undefined length'); const { rows, columns, samplesPerPixel, bitsAllocated, frames } = shapeOf(instance); - if (![rows, columns, samplesPerPixel, frames].every(positiveInteger)) - return unindexed( - 'Rows, Columns, Samples per Pixel or Number of Frames is unusable' - ); + if (![rows, columns, samplesPerPixel].every(positiveInteger)) + return unindexed('Rows, Columns or Samples per Pixel is unusable'); if (!positiveInteger(bitsAllocated) || bitsAllocated % 8 !== 0) return unindexed( `Bits Allocated ${bitsAllocated} packs samples across bytes` ); - const frameLength = rows * columns * samplesPerPixel * (bitsAllocated / 8); + return { + kind: 'native', + littleEndian: encoding.littleEndian, + frameLength: rows * columns * samplesPerPixel * (bitsAllocated / 8), + frames, + valueOffset: pixelData.valueOffset, + length: pixelData.length, + }; +} + +const overrun = ({ frameLength, frames, length }: NativeLayout) => { const needed = frameLength * frames; + return needed > length + ? `Pixel Data holds ${length} bytes; its frames need ${needed}` + : null; +}; + +/** Why a native instance's Pixel Data is too short for its declared frames, or null. */ +export function nativeFramesOverrun(instance: Instance) { + const layout = nativeLayout(instance); + return layout.kind === 'native' ? overrun(layout) : null; +} + +/** Byte ranges of every frame, from the header alone. */ +export function indexFrames(instance: Instance): FrameIndex { + const layout = nativeLayout(instance); + if (layout.kind !== 'native') return layout; // Frames past the element's end would read whatever follows it. - if (needed > pixelData.length) - return unindexed( - `Pixel Data holds ${pixelData.length} bytes; its frames need ${needed}` - ); + const detail = overrun(layout); + if (detail) return unindexed(detail); + const { littleEndian, frameLength, frames, valueOffset } = layout; return { kind: 'indexed', - littleEndian: encoding.littleEndian, + littleEndian, frameLength, frames: Array.from({ length: frames }, (_, frame) => { - const start = pixelData.valueOffset + frame * frameLength; + const start = valueOffset + frame * frameLength; return { start, end: start + frameLength }; }), }; diff --git a/packages/dicom/core/pixels/pixelDecoder.ts b/packages/dicom/core/pixels/pixelDecoder.ts index e9a7b40d5..bef858148 100644 --- a/packages/dicom/core/pixels/pixelDecoder.ts +++ b/packages/dicom/core/pixels/pixelDecoder.ts @@ -49,8 +49,11 @@ export type WholeInstanceDecode = ( signal: AbortSignal ) => Awaitable; -export const frameCount = (dataset: DicomDataset) => - numberOr(getDatasetTag(dataset, Tags.NumberOfFrames), 1); +// Some writers emit Number of Frames 0 on a single-frame instance. +export const frameCount = (dataset: DicomDataset) => { + const declared = numberOr(getDatasetTag(dataset, Tags.NumberOfFrames), 1); + return Number.isSafeInteger(declared) && declared > 0 ? declared : 1; +}; /** A decoder that reads and decodes every instance whole. */ export const wholeInstanceDecoder = ( diff --git a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts index afcc9b304..d2bd7ebc6 100644 --- a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts +++ b/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts @@ -101,11 +101,26 @@ describe('DICOM runtime', () => { const running = decodeWith(gdcm); const queued = decodeWith(gdcm); + await lanes.started(1); const reason = new DOMException('disposed', 'AbortError'); gdcm.dispose(reason); await expect(running).rejects.toBe(reason); await expect(queued).rejects.toBe(reason); + expect(lanes.peak()).toBe(1); + expect(lanes.resets).toContain(reason); + }); + + it('terminates idle GDCM workers when disposed', async () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 1, lanes.createLane); + lanes.gate.resolve(); + await decodeWith(gdcm); + + const reason = new DOMException('disposed', 'AbortError'); + gdcm.dispose(reason); + + expect(lanes.resets).toEqual([reason]); }); it('terminates the GDCM worker of a decode whose signal aborts', async () => { diff --git a/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts b/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts index a7287edac..d7d4aa85f 100644 --- a/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts +++ b/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest'; -import { readDicomDataset } from '../../metadata/dicomDataset'; +import * as Comlink from 'comlink'; +import { + readDicomDataset, + readPublicDataset, +} from '../../metadata/dicomDataset'; import { createMetadataReader } from '../metadataReader'; import { buildSlice } from '@/tests/specs/dicomElementFixtures'; import { rawElement } from '@/tests/specs/syntheticDicom'; @@ -79,4 +83,24 @@ describe('metadata worker ownership', () => { name: 'AbortError', }); }); + + it('transfers a copy, so the caller keeps its bytes', async () => { + const reader = createMetadataReader({ + metadataWorkerFactory: () => { + const { port1, port2 } = new MessageChannel(); + Comlink.expose({ readPublicDataset }, port2); + return Object.assign(port1, { + terminate: () => port2.close(), + }) as unknown as Worker; + }, + }); + const bytes = buildSlice(); + const original = bytes.slice(); + + const dataset = await reader.read(bytes); + reader.dispose(); + + expect(bytes).toEqual(original); + expect(dataset).toEqual(readPublicDataset(original)); + }); }); diff --git a/packages/dicom/core/runtime/createDicomRuntime.ts b/packages/dicom/core/runtime/createDicomRuntime.ts index 9cc1316ef..e98879240 100644 --- a/packages/dicom/core/runtime/createDicomRuntime.ts +++ b/packages/dicom/core/runtime/createDicomRuntime.ts @@ -94,7 +94,7 @@ export function createDicomRuntime( signal: lifetime.signal, decodeConcurrency, decoders: (options.decoders ?? defaultDecoderTable)(gdcm.decoder), - /** Concurrent requests, which also bounds how far reads run ahead of decoding. */ + /** Requests awaiting headers at once; also how far reads run ahead of decoding. */ readConcurrency: requests.poolSize, readInstance: read, dispose, diff --git a/packages/dicom/core/source/__tests__/byteSource.spec.ts b/packages/dicom/core/source/__tests__/byteSource.spec.ts index 4b1359c23..517b72c0a 100644 --- a/packages/dicom/core/source/__tests__/byteSource.spec.ts +++ b/packages/dicom/core/source/__tests__/byteSource.spec.ts @@ -243,6 +243,35 @@ describe('URL byte source', () => { ).rejects.toThrow(message); }); + it.each([ + ['answers 404', { status: 404 }], + ['answers a 206 that starts late', { startShift: 50 }], + ['answers an unreadable Content-Range', { contentRange: 'bytes 100-' }], + ])('aborts its request when the server %s', async (_name, options) => { + const { http, source } = urlSource(options); + await expect( + readStream(source.read(signal(), { start: 100, end: 300 })) + ).rejects.toThrow(); + expect(http.signals[0]?.aborted).toBe(true); + }); + + it('aborts its request when the body fails partway', async () => { + const signals: Array = []; + const failing: typeof fetch = async (_input, init = {}) => { + signals.push(init.signal); + return new Response( + new ReadableStream({ + pull: () => Promise.reject(new Error('connection reset')), + }) + ); + }; + const source = fromUrl('https://example.test/a.dcm', { fetch: failing }); + await expect(readStream(source.read(signal()))).rejects.toThrow( + 'connection reset' + ); + expect(signals[0]?.aborted).toBe(true); + }); + it('cancels the response body when the reader cancels', async () => { const { http, source } = urlSource(); const reader = source.read(signal()).getReader(); diff --git a/packages/dicom/core/source/byteSource.ts b/packages/dicom/core/source/byteSource.ts index b93e60d16..43af15925 100644 --- a/packages/dicom/core/source/byteSource.ts +++ b/packages/dicom/core/source/byteSource.ts @@ -172,21 +172,29 @@ export const fromUrl = ( return { rangeSupport: () => rangeSupport, read: (signal, range) => { - const { controller, release } = linkedController(signal); + const { controller } = linkedController(signal); const opened = open(controller.signal, range); + // Abort is how a pooled fetch learns it is done, failed reads included. + const abort = () => controller.abort(); // Observed here so a stream nobody pulls does not reject unhandled. - opened.catch(release); + opened.catch(abort); + const pull = async ( + stream: ReadableStreamDefaultController + ) => { + const { done, value } = await (await opened).read(); + if (!done) { + stream.enqueue(value); + return; + } + abort(); + stream.close(); + }; return new ReadableStream({ - pull: async (stream) => { - const { done, value } = await (await opened).read(); - if (!done) { - stream.enqueue(value); - return; - } - // Abort is how a pooled fetch learns its body is done. - controller.abort(); - stream.close(); - }, + pull: (stream) => + pull(stream).catch((error) => { + abort(); + throw error; + }), cancel: async (reason) => { controller.abort(reason); const reader = await opened.catch(() => null); diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts index 0fa8705f1..a924dd5e9 100644 --- a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest'; import { allocateVolume } from '../allocateVolume'; import { allocated, pixelSlice } from './volumeFixture'; import { plannedUpdate } from '@/tests/dicomVolumeFixtures'; +import { readHeader } from '@/tests/dicomSourceFixtures'; +import { nativePixelDicom } from '@/tests/nativePixelDicom'; describe('allocateVolume', () => { it('allocates an empty buffer placed by the planned stack', () => { @@ -38,6 +40,30 @@ describe('allocateVolume', () => { expect(volume.data).toBeInstanceOf(type); }); + it.each(['0', '-3', '2.5'])( + 'allocates one slice for an instance declaring %s frames', + (frames) => { + const volume = allocated([ + pixelSlice(0, { tags: { '0028|0008': frames } }), + ]); + expect(volume.dimensions).toEqual([4, 4, 1]); + expect(volume.data).toHaveLength(16); + } + ); + + it('rejects a lone native instance declaring more frames than its Pixel Data holds', async () => { + const instance = await readHeader( + nativePixelDicom({ + rows: 1, + columns: 1, + extra: [{ tag: 0x00280008, vr: 'IS', value: '40000000' }], + }) + ); + expect(() => allocateVolume(plannedUpdate([instance]))).toThrow( + 'declares more frames than its Pixel Data holds: Pixel Data holds 2 bytes; its frames need 80000000' + ); + }); + it('keeps an irregular stack in order and reports why it is irregular', () => { const volume = allocated([0, 1, 3].map((z) => pixelSlice(z))); diff --git a/packages/dicom/core/volume/__tests__/enhancedFixture.ts b/packages/dicom/core/volume/__tests__/enhancedFixture.ts index 51bdf2f09..193bd3bf9 100644 --- a/packages/dicom/core/volume/__tests__/enhancedFixture.ts +++ b/packages/dicom/core/volume/__tests__/enhancedFixture.ts @@ -28,6 +28,7 @@ export function enhanced( root: Record = {} ): DicomDataset { const header = tags({ + '00080016': '1.2.840.10008.5.1.4.1.1.2.1', '00280010': '2', '00280011': '2', '00280008': String(frames.length), diff --git a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts index 5cf274515..4fc66abfa 100644 --- a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -186,6 +186,44 @@ describe('loadVolume with native frames', () => { expect(Array.from(volume.data.subarray(0, 18))).toEqual(words.slice(0, 18)); }); + it('reads only the frame that failed when the volume loads again', async () => { + const { bytes, words } = multiframe(); + const blob = blobOf(bytes); + const instance = await readInstance(blob, signal()); + const lost = instance.pixelData!.valueOffset + 2 * 12; + let dropped = false; + const { source, ranges } = recorded({ + ...blob, + read: (readSignal, range) => { + if (range?.start !== lost || dropped) + return blob.read(readSignal, range); + dropped = true; + return new ReadableStream({ + start: (controller) => controller.error(new Error('dropped')), + }); + }, + }); + const volume = allocated([{ ...instance, source }]); + const loadAgain = async () => { + const updates: VolumeUpdate[] = []; + for await (const update of loadVolume(volume, { + runtime: nativeOnly(), + signal: signal(), + })) + updates.push(update); + return updates; + }; + + const first = await loadAgain(); + ranges.length = 0; + const second = await loadAgain(); + + expect(first.filter((update) => 'error' in update)).toHaveLength(1); + expect(second.map((update) => update.slot)).toEqual([2]); + expect(ranges).toEqual([{ start: lost, end: lost + 12 }]); + expect(Array.from(volume.data)).toEqual(words); + }); + it('reports the float32-rounded range a Float32 volume stores', async () => { const { bytes, words } = multiframe({ rescale: [0.1, 0.3] }); const instance = await readInstance(blobOf(bytes), signal()); @@ -313,6 +351,15 @@ describe('loadVolume with native frames', () => { slots.push(update.slot); controller.abort(); } + // The next decode waits on a task posted before this one, on an earlier port. + await new Promise((resolve) => { + const { port1, port2 } = new MessageChannel(); + port1.onmessage = () => { + port1.close(); + resolve(); + }; + port2.postMessage(null); + }); expect(slots).toHaveLength(1); expect(decoded).toEqual(slots); @@ -380,6 +427,11 @@ describe('loadVolume with native frames', () => { (offset: number) => [0, 1, 2, 2, 3, 4].map((frame) => frameUnit(offset, frame)), ], + [ + 'a frame twice and another not at all', + (offset: number) => + [0, 0, 1, 2, 3].map((frame) => frameUnit(offset, frame)), + ], [ 'units that skip a frame', (offset: number) => [0, 1, 3, 4].map((frame) => frameUnit(offset, frame)), diff --git a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts index 65fafe6ae..1d5b7001d 100644 --- a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -143,6 +143,58 @@ describe('loadVolume', () => { expect(sliceValues(volume)).toEqual([null, null, 2, null, 4]); }); + it('fails a whole instance of 250000 frames as one failure', async () => { + const frames = 250_000; + const volume = allocated([ + pixelSlice(0, { + rows: '1', + tags: { '0028|0011': '1', '0028|0008': String(frames) }, + }), + ]); + + const updates = await loadAll( + volume, + runtimeWith(() => { + throw new Error('corrupt pixel data'); + }) + ); + + expect(updates).toEqual([ + { + slot: 0, + extent: [0, 0, 0, 0, 0, frames - 1], + error: expect.objectContaining({ + message: expect.stringMatching(/corrupt pixel data$/), + }), + }, + ]); + }); + + it('fails a slice whose decoded values the volume buffer cannot hold', async () => { + const decode = valueDecoder(); + const decoder: WholeInstanceDecode = async (request, signal) => { + const image = await decode(request, signal); + return image.data[0] === 1 + ? { ...image, data: new Int16Array(16).fill(-1) } + : image; + }; + const volume = stack(3); + + const updates = await loadAll(volume, runtimeWith(decoder)); + + expect(volume.data).toBeInstanceOf(Uint16Array); + expect(updates.find((update) => update.slot === 1)).toEqual({ + slot: 1, + extent: [0, 3, 0, 3, 1, 1], + error: expect.objectContaining({ + message: expect.stringMatching( + /^File pixel-1 \(member 1\) has pixel values the volume it belongs to cannot represent\. Its pixel values run from -1 to -1, but the volume's buffer is Uint16Array/ + ), + }), + }); + expect(sliceValues(volume)).toEqual([0, null, 2]); + }); + it('reorders reads around a focus that moves while a slice decodes', async () => { const decoded: number[] = []; const decode = valueDecoder(decoded); @@ -321,6 +373,8 @@ describe('loadVolume', () => { signal: controller.signal, }) ); + // The decode settles in microtasks, so a write it made would land by now. + await new Promise((resolve) => setTimeout(resolve)); expect(updates).toEqual([]); expect(volume.data.every((sample) => sample === 0)).toBe(true); diff --git a/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts b/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts index 829d0aa93..ae8367fb4 100644 --- a/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts +++ b/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts @@ -5,7 +5,9 @@ import { getPixelFormat, getRescaledValueRange, getVolumeBufferType, + instancePixelFormats, } from '../pixelFormat'; +import { enhanced, groups, sequence } from './enhancedFixture'; // Builds a format from exactly the tags given, with no defaults filled in, so // each test states the whole instance it is describing. @@ -262,3 +264,25 @@ describe('getVolumeBufferType', () => { expect(getVolumeBufferType([UNSIGNED_16, PUBLIC_DSC])).toBe(Float32Array); }); }); + +describe('instancePixelFormats', () => { + it('reads frames past the per-frame groups from the root, however many are declared', () => { + const metadata = enhanced( + groups([]), + [ + groups([ + sequence('00289145', [ + datasetFromTags([ + ['00281053', '.5'], + ['00281052', '-500'], + ]), + ]), + ]), + ], + { '00280008': String(2 ** 32), '00281052': '1e9' } + ); + expect(getVolumeBufferType(instancePixelFormats(metadata))).toBe( + Float64Array + ); + }); +}); diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts index 92de8da4a..89e433b59 100644 --- a/packages/dicom/core/volume/allocateVolume.ts +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -2,6 +2,7 @@ import type { Instance } from '../instance/readInstance'; import type { ImageCollectionUpdate } from '../collections/instanceRegistry'; import type { SpatialMetadata } from '../metadata/spatialMetadata'; import type { VolumeBuffer } from './pixelFormat'; +import { nativeFramesOverrun } from '../pixels/frameIndex'; import { planVolumeAllocation } from './volumeLayout'; type Triple = [number, number, number]; @@ -91,6 +92,12 @@ export function allocateVolume( previous?: Volume ) { const { collection, members } = update; + // A lone instance's frames are the volume's slices, so they must exist. + const overrun = members.length === 1 && nativeFramesOverrun(members[0]); + if (overrun) + throw new Error( + `The instance declares more frames than its Pixel Data holds: ${overrun}` + ); const { layout, warnings } = planVolumeAllocation( members, collection.orientation, diff --git a/packages/dicom/core/volume/loadVolume.ts b/packages/dicom/core/volume/loadVolume.ts index 8b46b23ee..fd19f8149 100644 --- a/packages/dicom/core/volume/loadVolume.ts +++ b/packages/dicom/core/volume/loadVolume.ts @@ -63,13 +63,19 @@ const nextTask = () => const ensureError = (error: unknown) => error instanceof Error ? error : new Error(String(error)); +// Reduced rather than spread: a lone instance can have more slices than a call takes arguments. +const lowest = (values: readonly number[]) => + values.reduce((low, value) => Math.min(low, value), Infinity); +const highest = (values: readonly number[]) => + values.reduce((high, value) => Math.max(high, value), -Infinity); + const sliceExtent = (volume: Volume, slices: readonly number[]): Extent => [ 0, volume.dimensions[0] - 1, 0, volume.dimensions[1] - 1, - Math.min(...slices), - Math.max(...slices), + lowest(slices), + highest(slices), ]; const failure = ( @@ -77,7 +83,7 @@ const failure = ( slices: readonly number[], error: unknown ): VolumeUpdate => ({ - slot: Math.min(...slices), + slot: lowest(slices), extent: sliceExtent(volume, slices), error: ensureError(error), }); @@ -294,8 +300,8 @@ function createLoader({ volume, runtime, stopped, focus, readAhead }: Loader) { return [ await readBytes(sourceOf(first), stopped, first.range ?? undefined), ]; - const start = Math.min(...batch.map((unit) => unit.range!.start)); - const end = Math.max(...batch.map((unit) => unit.range!.end!)); + const start = lowest(batch.map((unit) => unit.range!.start)); + const end = highest(batch.map((unit) => unit.range!.end!)); const bytes = await readBytes(sourceOf(first), stopped, { start, end }); return batch.map(({ range }) => bytes.subarray(range!.start - start, range!.end! - start) diff --git a/packages/dicom/core/volume/pixelFormat.ts b/packages/dicom/core/volume/pixelFormat.ts index 7a5705f5b..599451b3a 100644 --- a/packages/dicom/core/volume/pixelFormat.ts +++ b/packages/dicom/core/volume/pixelFormat.ts @@ -1,6 +1,6 @@ import type { DicomDataset } from '../metadata/dicomDataset'; import { Tags } from '../metadata/dicomTags'; -import { getFrameTag } from '../metadata/functionalGroups'; +import { getFrameTag, perFrameGroups } from '../metadata/functionalGroups'; import { readModalityRescale } from '../metadata/modalityRescale'; import { frameCount } from '../pixels/pixelDecoder'; import { numberOr } from '../utils'; @@ -193,8 +193,15 @@ export function getVolumeBufferType( : integralBufferType(usable); } -/** One format per frame, since enhanced instances calibrate frames separately. */ +/** + * One format per frame, since enhanced instances calibrate frames separately. + * Frames past the per-frame groups all read the shared or root tags, so one + * format stands for them however many frames the header declares. + */ export const instancePixelFormats = (dataset: DicomDataset) => - Array.from({ length: frameCount(dataset) }, (_, index) => - getPixelFormat(dataset, index) + Array.from( + { + length: Math.min(frameCount(dataset), perFrameGroups(dataset).length + 1), + }, + (_, index) => getPixelFormat(dataset, index) ); diff --git a/src/io/import/__tests__/importDicomInstanceSources.spec.ts b/src/io/import/__tests__/importDicomInstanceSources.spec.ts index 3111bf5fe..23dc065f5 100644 --- a/src/io/import/__tests__/importDicomInstanceSources.spec.ts +++ b/src/io/import/__tests__/importDicomInstanceSources.spec.ts @@ -3,6 +3,7 @@ import { createPinia, setActivePinia } from 'pinia'; import type { Instance } from '@/packages/dicom/core'; import { buildStateIDToStoreID, + findMergedStateDatasets, importDicomInstanceSources, } from '@/src/io/import/importDataSources'; import type { DicomInstanceSource } from '@/src/io/import/dataSource'; @@ -103,14 +104,13 @@ describe('importDicomInstanceSources with a given commit', () => { }); describe('importDicomInstanceSources through the DICOM store', () => { - const load = (instances: Instance[]) => { + const loadSources = (sources: DicomInstanceSource[]) => { const { createImage } = imageFactory(); - return importDicomInstanceSources( - instances.map(sourceFor), - (batch, hooks) => - useDICOMStore().importInstances(batch, { createImage, ...hooks }) + return importDicomInstanceSources(sources, (batch, hooks) => + useDICOMStore().importInstances(batch, { createImage, ...hooks }) ); }; + const load = (instances: Instance[]) => loadSources(instances.map(sourceFor)); const failedSops = ({ failures }: ReturnType) => failures.map(({ error, sources }) => [ @@ -223,4 +223,22 @@ describe('importDicomInstanceSources through the DICOM store', () => { second.map(sopOf) ); }); + + it('binds no saved state when two saved volumes restore as one', () => { + // Without the first pass's last slice the passes no longer overlap. + const first = acquisition('1', [0, 2.5]); + const second = acquisition('2', [4, 6.5, 9]); + + const { loadables } = loadSources([ + ...first.map((instance) => restored(instance, 'pass-1')), + ...second.map((instance) => restored(instance, 'pass-2')), + ]); + + const [mergedId] = idsOf(loadables); + expect(buildStateIDToStoreID(loadables)).toEqual({}); + expect(findMergedStateDatasets(loadables)).toEqual({ + 'pass-1': mergedId, + 'pass-2': mergedId, + }); + }); }); diff --git a/src/io/import/__tests__/missingArchiveMember.spec.ts b/src/io/import/__tests__/missingArchiveMember.spec.ts index 3fd033806..533ec84c2 100644 --- a/src/io/import/__tests__/missingArchiveMember.spec.ts +++ b/src/io/import/__tests__/missingArchiveMember.spec.ts @@ -91,6 +91,23 @@ describe('restore with a partially missing dataset archive', () => { expect(warning?.options.details).not.toMatch(/image: a\.dcm, b\.dcm\n/); }); + it('names a dataset whose files now share a volume with another as merged, not missing', async () => { + await completeStateFileRestore( + ManifestSchema.parse(manifest), + [], + {}, + { mergedDatasets: { 'ds-ct': 'store-merged' } } + ); + + const warning = useMessageStore().messages.find( + (message) => message.title === 'Some scene content could not be restored' + ); + expect(warning?.options.details).toContain( + 'image: a.dcm, b.dcm (loaded as one volume with another saved image' + ); + expect(warning?.options.details).not.toMatch(/image: a\.dcm, b\.dcm\n/); + }); + it('names the files in a collection that failed to resolve entirely', async () => { await completeStateFileRestore(ManifestSchema.parse(manifest), [], {}); diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 505e14c36..f4ba840ce 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -40,7 +40,7 @@ import openUriStream from '@/src/io/import/processors/openUriStream'; import downloadStream from '@/src/io/import/processors/downloadStream'; import { asyncSelect } from '@/src/utils/asyncSelect'; import { evaluateChain, Skip } from '@/src/utils/evaluateChain'; -import { ensureError } from '@/src/utils'; +import { ensureError, groupBy } from '@/src/utils'; import type { Instance } from '@/packages/dicom/core'; import { useDatasetStore } from '@/src/store/datasets'; import { @@ -90,18 +90,22 @@ const compareSourceOrder = (a: number[], b: number[]) => { }; // The restore-time stateID -> storeID map: every state-file leaf a loadable -// covers maps to its ONE store id. Many-to-one is the normal shape — a merged -// multi-file DICOM volume covers every member file's per-file dataset id. -// A dataset whose leaves now load as SEVERAL volumes (a series since split -// into acquisitions) has no single owner for its saved state; it is left -// unmapped so restore reports it instead of binding annotations, layers, and -// views to an arbitrary one of the volumes. +// covers maps to its ONE store id. Many-to-one is the normal shape when each +// dataset is one file: a merged multi-file DICOM volume covers every member +// file's per-file dataset id. A dataset whose leaves now load as SEVERAL +// volumes (a series since split into acquisitions), or a multi-file dataset +// whose volume now also holds another dataset's files, has a different grid +// than its saved state; it is left unmapped so restore reports it instead of +// binding annotations, layers, and views to the wrong slices. export function buildStateIDToStoreID( loadables: readonly LoadableResult[] ): Record { + const merged = findMergedStateDatasets(loadables); return Object.fromEntries( [...storeIDsByStateID(loadables)] - .filter(([, storeIDs]) => storeIDs.size === 1) + .filter( + ([stateID, storeIDs]) => storeIDs.size === 1 && !(stateID in merged) + ) .map(([stateID, storeIDs]) => [stateID, [...storeIDs][0]]) ); } @@ -121,18 +125,47 @@ export function findSplitStateDatasets( ); } -function storeIDsByStateID(loadables: readonly LoadableResult[]) { - const storeIDsByState = new Map>(); - loadables.forEach((loadable) => { - findStateFileLeaves(loadable.dataSource).forEach((leaf) => { - const storeIDs = storeIDsByState.get(leaf.stateID) ?? new Set(); - storeIDs.add(loadable.dataID); - storeIDsByState.set(leaf.stateID, storeIDs); - }); - }); - return storeIDsByState; +/** + * The state-file datasets the map above leaves out because they share one + * volume with another dataset and at least one of them is several files, with + * that volume. + */ +export function findMergedStateDatasets( + loadables: readonly LoadableResult[] +): Record { + const leaves = stateLeavesOf(loadables); + const leavesByState = groupBy(leaves, ([stateID]) => stateID); + return Object.fromEntries( + [...groupBy(leaves, ([, storeID]) => storeID).values()] + .map((pairs) => new Map(pairs)) + .filter( + (stateToStore) => + stateToStore.size > 1 && + [...stateToStore.keys()].some( + (stateID) => leavesByState.get(stateID)!.length > 1 + ) + ) + .flatMap((stateToStore) => [...stateToStore]) + ); } +const stateLeavesOf = (loadables: readonly LoadableResult[]) => + loadables.flatMap((loadable) => + findStateFileLeaves(loadable.dataSource).map( + (leaf) => [leaf.stateID, loadable.dataID] as const + ) + ); + +const storeIDsByStateID = (loadables: readonly LoadableResult[]) => + new Map( + [...groupBy(stateLeavesOf(loadables), ([stateID]) => stateID)].map( + ([stateID, pairs]) => [ + stateID, + new Set(pairs.map(([, storeID]) => storeID)), + ] + ) + ); + // An instance outlives the batch that brought it: a replan can move a member // into another collection, whose provenance must still name where its bytes // came from. @@ -389,6 +422,7 @@ async function importDataSourcesWithPolicy( const stateIDToStoreID = buildStateIDToStoreID(loadableResults); const splitDatasets = findSplitStateDatasets(loadableResults); + const mergedDatasets = findMergedStateDatasets(loadableResults); // Leaf stateIDs covered by a consolidated notice that actually ran — only // their errors may be suppressed below. const reportedStateIDs = new Set(); @@ -398,7 +432,12 @@ async function importDataSourcesWithPolicy( setup.manifest, setup.stateFiles, stateIDToStoreID, - { missingFiles: setup.missingFiles, failedLeaves, splitDatasets } + { + missingFiles: setup.missingFiles, + failedLeaves, + splitDatasets, + mergedDatasets, + } ); setup.dataSources.forEach((src) => { findStateFileLeaves(src).forEach((leaf) => diff --git a/src/io/import/processors/restoreStateFile.ts b/src/io/import/processors/restoreStateFile.ts index aba3fb298..7f2f3ceb9 100644 --- a/src/io/import/processors/restoreStateFile.ts +++ b/src/io/import/processors/restoreStateFile.ts @@ -194,6 +194,8 @@ export type RestoreReports = { failedLeaves?: Array<{ stateID: string; name: string }>; /** State dataset id to the store ids a replan split it into. */ splitDatasets?: Record; + /** State dataset id to the one store id it now shares with another. */ + mergedDatasets?: Record; }; type RestoreServices = { @@ -216,6 +218,7 @@ export const createStateFileRestorer = ({ missingFiles = [], failedLeaves = [], splitDatasets = {}, + mergedDatasets = {}, }: RestoreReports = {} ) { const viewStore = views ?? useViewStore(); @@ -279,7 +282,7 @@ export const createStateFileRestorer = ({ String(ds.id) ); const missingBases = unresolvedDatasets - .filter((ds) => !(ds.id in splitDatasets)) + .filter((ds) => !(ds.id in splitDatasets) && !(ds.id in mergedDatasets)) .map(summarize); // Saved state has no single target when its dataset becomes several volumes. const splitBases = unresolvedDatasets @@ -290,6 +293,14 @@ export const createStateFileRestorer = ({ 'volumes; the annotations, layers and view settings saved on it were ' + 'not restored)' ); + const mergedBases = unresolvedDatasets + .filter((ds) => ds.id in mergedDatasets && !(ds.id in splitDatasets)) + .map( + (ds) => + `- image: ${summarize(ds)} (loaded as one volume with another saved ` + + 'image; the annotations, layers and view settings saved on it were ' + + 'not restored)' + ); // Partially restored datasets need member notices; unresolved datasets are named above. const missingMembers = missingFiles .filter(({ stateID }) => stateID in stateIDToStoreID) @@ -314,6 +325,7 @@ export const createStateFileRestorer = ({ const missing = [ ...missingBases.map((name) => `- image: ${name}`), ...splitBases, + ...mergedBases, ...missingMembers, ...failedMembers, ...skippedLabelmaps.map( diff --git a/tests/fixtures/dicom-pages/volumeCorpusReference.py b/tests/fixtures/dicom-pages/volumeCorpusReference.py index ad8ec3b4b..e2ba25056 100644 --- a/tests/fixtures/dicom-pages/volumeCorpusReference.py +++ b/tests/fixtures/dicom-pages/volumeCorpusReference.py @@ -29,10 +29,33 @@ def macro(groups, sequence, keyword): return None +# IODs whose functional groups define Pixel Value Transformation; others keep +# Rescale Slope and Intercept at the root. +FUNCTIONAL_GROUP_RESCALE = { + '1.2.840.10008.5.1.4.1.1.2.1', # Enhanced CT + '1.2.840.10008.5.1.4.1.1.2.2', # Legacy Converted Enhanced CT + '1.2.840.10008.5.1.4.1.1.4.1', # Enhanced MR + '1.2.840.10008.5.1.4.1.1.4.4', # Legacy Converted Enhanced MR + '1.2.840.10008.5.1.4.1.1.130', # Enhanced PET + '1.2.840.10008.5.1.4.1.1.128.1', # Legacy Converted Enhanced PET + '1.2.840.10008.5.1.4.1.1.13.1.1', # X-Ray 3D Angiographic + '1.2.840.10008.5.1.4.1.1.13.1.2', # X-Ray 3D Craniofacial + '1.2.840.10008.5.1.4.1.1.13.1.3', # Breast Tomosynthesis + '1.2.840.10008.5.1.4.1.1.13.1.4', # Breast Projection X-Ray For Presentation + '1.2.840.10008.5.1.4.1.1.13.1.5', # Breast Projection X-Ray For Processing + '1.2.840.10008.5.1.4.1.1.66.4', # Segmentation +} + + def rescale(ds, frame): - """Slope and intercept of one frame: Functional Groups first, then the root.""" + """Slope and intercept of one frame: Functional Groups first where the IOD + defines them there, then the root.""" shared, per_frame = frame_groups(ds) - groups = [per_frame[frame] if per_frame else None, shared] + groups = ( + [per_frame[frame] if per_frame else None, shared] + if str(ds.get('SOPClassUID', '')) in FUNCTIONAL_GROUP_RESCALE + else [] + ) slope = macro(groups, 'PixelValueTransformationSequence', 'RescaleSlope') intercept = macro(groups, 'PixelValueTransformationSequence', 'RescaleIntercept') return ( diff --git a/tests/specs/dicom-native-parity.e2e.ts b/tests/specs/dicom-native-parity.e2e.ts index d4350ffa2..944dc215e 100644 --- a/tests/specs/dicom-native-parity.e2e.ts +++ b/tests/specs/dicom-native-parity.e2e.ts @@ -36,6 +36,7 @@ const SOP_CLASSES = { EnhancedCT: '1.2.840.10008.5.1.4.1.1.2.1', EnhancedMR: '1.2.840.10008.5.1.4.1.1.4.1', OCT: '1.2.840.10008.5.1.4.1.1.77.1.5.4', + WordSC: '1.2.840.10008.5.1.4.1.1.7.3', }; const us = (tag: number, value: number): DataElement => ({ @@ -96,6 +97,8 @@ const synthetic: Array<[string, boolean, NativePixelOptions]> = [ ['enhanced-ct-uniform', true, { sopClassUid: SOP_CLASSES.EnhancedCT, frames: 3, frameRescales: [[2, -1], [2, -1], [2, -1]] }], ['enhanced-mr-fractional', true, { sopClassUid: SOP_CLASSES.EnhancedMR, modality: 'MR', frames: 2, frameRescales: [[0.3, 1], [0.3, 1]] }], ['enhanced-ct-differing', false, { sopClassUid: SOP_CLASSES.EnhancedCT, frames: 2, frameRescales: [[1, 0], [2, 0]] }], + ['word-sc-functional-group-rescale', true, { sopClassUid: SOP_CLASSES.WordSC, frames: 2, rescale: [2, -1000], frameRescales: [[3, -500], [3, -500]] }], + ['oct-differing-functional-group-rescale', true, { sopClassUid: SOP_CLASSES.OCT, frames: 2, frameRescales: [[1, 0], [2, 0]] }], ...Object.entries(SOP_CLASSES).flatMap( ([name, sopClassUid]): Array<[string, boolean, NativePixelOptions]> => [ [`${name}-integer-rescale`, true, { sopClassUid, bitsStored: 12, rescale: [3, -7] }], From 0080aaf893858bd405898f17a55064ea60617dd0 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 15 Nov 2026 13:17:14 -0500 Subject: [PATCH 10/32] refactor(dicom): drop the Image spacing dialog Showing image information is a separate feature from the loader. The loader still reports how each axis spacing was established. --- packages/dicom/README.md | 3 +- src/components/ImageSpacingDetails.vue | 113 ------------ src/components/PatientStudyVolumeBrowser.vue | 13 +- tests/specs/dicom-import-regressions.e2e.ts | 9 +- tests/specs/dicom-spacing-details.e2e.ts | 172 ------------------- tests/specs/utils.ts | 11 -- 6 files changed, 4 insertions(+), 317 deletions(-) delete mode 100644 src/components/ImageSpacingDetails.vue delete mode 100644 tests/specs/dicom-spacing-details.e2e.ts diff --git a/packages/dicom/README.md b/packages/dicom/README.md index 772442970..274a3a8be 100644 --- a/packages/dicom/README.md +++ b/packages/dicom/README.md @@ -350,5 +350,4 @@ module through the entry points, as the app does. import over HTTP. `tests/dicomCompositionCorpus.json` records the inputs and expectations; `compositionReference.py` beside the pages checks them with pydicom and NumPy. -- `dicom-frame-reconstruction.e2e.ts` and `dicom-spacing-details.e2e.ts` check - multiframe reconstruction and spacing reports. +- `dicom-frame-reconstruction.e2e.ts` checks multiframe reconstruction. diff --git a/src/components/ImageSpacingDetails.vue b/src/components/ImageSpacingDetails.vue deleted file mode 100644 index d94d07274..000000000 --- a/src/components/ImageSpacingDetails.vue +++ /dev/null @@ -1,113 +0,0 @@ - - - diff --git a/src/components/PatientStudyVolumeBrowser.vue b/src/components/PatientStudyVolumeBrowser.vue index 14c3c6bb7..e446fa7a5 100644 --- a/src/components/PatientStudyVolumeBrowser.vue +++ b/src/components/PatientStudyVolumeBrowser.vue @@ -1,5 +1,5 @@ diff --git a/tests/fixtures/dicom-pages/core.ts b/tests/fixtures/dicom-pages/core.ts index 1efc2a912..7d7bd645f 100644 --- a/tests/fixtures/dicom-pages/core.ts +++ b/tests/fixtures/dicom-pages/core.ts @@ -3,10 +3,8 @@ import { assetUrls, createRuntime, firstUnit, - describeMetadata, failed, gdcmOnly, - loadInstance, never, report, } from './shared'; @@ -42,17 +40,4 @@ async function recoverWorker() { report('status', 'complete'); } -async function run() { - const instance = await loadInstance(); - describeMetadata(instance); - const bytes = await readBytes(instance.source, never); - const image = await firstUnit(createRuntime(gdcmOnly), instance).decode( - bytes, - never - ); - report('pixels', Array.from(image.data).join(', ')); - report('dimensions', image.size.join(', ')); - report('status', 'complete'); -} -const scenario = new URL(location.href).searchParams.get('scenario'); -(scenario === 'worker-recovery' ? recoverWorker() : run()).catch(failed); +recoverWorker().catch(failed); diff --git a/tests/fixtures/dicom-pages/server.mjs b/tests/fixtures/dicom-pages/server.mjs index e582f18f4..17970049f 100644 --- a/tests/fixtures/dicom-pages/server.mjs +++ b/tests/fixtures/dicom-pages/server.mjs @@ -8,17 +8,6 @@ const root = fileURLToPath(new URL('../../../', import.meta.url)); const fixture = fileURLToPath(new URL('.', import.meta.url)); const require = createRequire(import.meta.url); -// Pages exercise the DICOM module alone, so nothing from the app or its UI -// frameworks may enter their bundles. -const forbiddenModule = (id, kind) => { - const path = id.replaceAll('\\', '/'); - return ( - path.startsWith(`${root.replaceAll('\\', '/')}src/`) || - /\/node_modules\/(vue|pinia|@vue\/|@vueuse\/)/.test(path) || - (kind === 'core' && path.includes('/node_modules/@kitware/vtk.js/')) - ); -}; - const moduleRoot = (name) => resolve(dirname(require.resolve(name)), '..'); async function copyItkAssets(assets) { @@ -45,17 +34,6 @@ async function buildPage(kind, outDir) { base: './', logLevel: 'warn', resolve: { alias: [{ find: '@', replacement: root.replace(/\/$/, '') }] }, - plugins: [ - { - name: 'dicom-module-only', - generateBundle() { - for (const id of this.getModuleIds()) { - if (forbiddenModule(id, kind)) - this.error(`Unexpected ${kind} page dependency: ${id}`); - } - }, - }, - ], build: { outDir, emptyOutDir: true, @@ -87,7 +65,7 @@ function serveDicom(bytes, range, response) { } export async function startDicomPages({ - kinds = ['core', 'vtk'], + kinds = ['core'], fixtures = {}, } = {}) { const serveFixture = (ranged) => (request, response) => { diff --git a/tests/fixtures/dicom-pages/shared.ts b/tests/fixtures/dicom-pages/shared.ts index b7279561b..6637e28b3 100644 --- a/tests/fixtures/dicom-pages/shared.ts +++ b/tests/fixtures/dicom-pages/shared.ts @@ -3,13 +3,11 @@ import { type DicomRuntimeOptions, } from '@/packages/dicom/core/runtime/createDicomRuntime'; import { fromBlob, fromUrl } from '@/packages/dicom/core/source/byteSource'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; import { planDecode, singleDecoderTable, } from '@/packages/dicom/core/pixels/decoderTable'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { fixtureBytes } from './fixtureData'; export const assetUrls = ( pipelineWorker = './assets/itk-wasm-pipeline.min.worker.js' @@ -56,22 +54,6 @@ export function report(name: string, value: string) { document.querySelector('main')!.append(output); } -export async function loadInstance() { - const input = - new URL(location.href).searchParams.get('source') === 'http' - ? new URL('./corpus-data/fixture.dcm', document.baseURI) - : new File([fixtureBytes() as Uint8Array], 'fixture.dcm'); - return runtime.readInstance(sourceOf(input), never); -} - -export function describeMetadata({ dataset }: Instance) { - const numbers = (tag: string) => - getDatasetTag(dataset, tag)!.split('\\').map(Number).join(', '); - report('patient', getDatasetTag(dataset, '00100010')!.trim()); - report('position', numbers('00200032')); - report('pixel-spacing', numbers('00280030')); -} - export function failed(error: unknown) { report('error', error instanceof Error ? error.message : String(error)); } diff --git a/tests/fixtures/dicom-pages/vtk.html b/tests/fixtures/dicom-pages/vtk.html deleted file mode 100644 index 237d613e2..000000000 --- a/tests/fixtures/dicom-pages/vtk.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - DICOM vtk page - - - -

DICOM vtk page

-
-
- - - diff --git a/tests/fixtures/dicom-pages/vtk.ts b/tests/fixtures/dicom-pages/vtk.ts deleted file mode 100644 index ff9da257b..000000000 --- a/tests/fixtures/dicom-pages/vtk.ts +++ /dev/null @@ -1,46 +0,0 @@ -import '@kitware/vtk.js/Rendering/Profiles/Volume'; -import vtkGenericRenderWindow from '@kitware/vtk.js/Rendering/Misc/GenericRenderWindow'; -import vtkImageMapper from '@kitware/vtk.js/Rendering/Core/ImageMapper'; -import vtkImageSlice from '@kitware/vtk.js/Rendering/Core/ImageSlice'; -import { describeMetadata, failed, loadInstance, report } from './shared'; -import { loadInstanceVolume } from './loadVolume'; - -async function run() { - const instance = await loadInstance(); - describeMetadata(instance); - const { image: data } = await loadInstanceVolume(instance); - - report('dimensions', data.getDimensions().join(', ')); - report('spacing', data.getSpacing().join(', ')); - report('origin', data.getOrigin().join(', ')); - report('range', data.getPointData().getScalars().getRange().join(', ')); - const view = vtkGenericRenderWindow.newInstance({ background: [0, 0, 0] }); - view.setContainer(document.querySelector('#viewport') as HTMLElement); - view.resize(); - const mapper = vtkImageMapper.newInstance(); - mapper.setInputData(data); - mapper.setKSlice(0); - const actor = vtkImageSlice.newInstance(); - actor.setMapper(mapper); - actor.getProperty().setColorWindow(20); - actor.getProperty().setColorLevel(-10); - const renderer = view.getRenderer(); - renderer.addActor(actor); - renderer.getActiveCamera().setParallelProjection(true); - renderer.resetCamera(); - renderer.resetCameraClippingRange(); - view.getRenderWindow().render(); - report('status', 'complete'); - - window.addEventListener( - 'pagehide', - () => { - view.delete(); - actor.delete(); - mapper.delete(); - data.delete(); - }, - { once: true } - ); -} -run().catch(failed); diff --git a/tests/specs/dicom-module-pages.e2e.ts b/tests/specs/dicom-module-pages.e2e.ts index 688554032..de88ae586 100644 --- a/tests/specs/dicom-module-pages.e2e.ts +++ b/tests/specs/dicom-module-pages.e2e.ts @@ -1,51 +1,20 @@ -import { PNG } from 'pngjs'; -import { resolve } from 'node:path'; -import { TEMP_DIR } from '../../wdio.shared.conf'; -import { fixtureBytes } from '../fixtures/dicom-pages/fixtureData'; import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; import { openDicomPage } from '../dicomPages'; // Every stored 5 under slope 2 and intercept -20. const CALIBRATED_PIXELS = Array(16).fill('-10').join(', '); -describe('DICOM module pages without VolView startup', () => { +describe('DICOM decode worker without VolView startup', () => { let fixture: Awaited>; before(async () => { - fixture = await startDicomPages({ - fixtures: { 'fixture.dcm': fixtureBytes() }, - }); + fixture = await startDicomPages(); }); after(async () => fixture?.close()); it('rejects a failed worker startup and finishes queued and later reads', async () => { - await openDicomPage(`${fixture.urls.core}?scenario=worker-recovery`); + await openDicomPage(fixture.urls.core); await expect($('#first-error')).toHaveText('DICOM decoder worker failed'); await expect($('#queued-pixels')).toHaveText(CALIBRATED_PIXELS); await expect($('#retry-pixels')).toHaveText(CALIBRATED_PIXELS); }); - - it('core reads metadata and calibrated pixels from a file', async () => { - await openDicomPage(`${fixture.urls.core}?source=file`); - await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); - await expect($('#position')).toHaveText('10, 20, 30'); - await expect($('#pixel-spacing')).toHaveText('2, 3'); - await expect($('#pixels')).toHaveText(CALIBRATED_PIXELS); - }); - - it('vtk places and renders the volume read over HTTP', async () => { - await openDicomPage(`${fixture.urls.vtk}?source=http`); - await expect($('#patient')).toHaveText('EXTRACTED^DICOM'); - await expect($('#spacing')).toHaveText('3, 2, 4'); - await expect($('#origin')).toHaveText('10, 20, 30'); - await expect($('#range')).toHaveText('-10, -10'); - const screenshot = PNG.sync.read( - await $('#viewport').saveScreenshot(resolve(TEMP_DIR, 'dicom-vtk.png')) - ); - const center = - ((screenshot.height >> 1) * screenshot.width + (screenshot.width >> 1)) * - 4; - expect(screenshot.data[center]).toBeGreaterThan(110); - expect(screenshot.data[center]).toBeLessThan(145); - expect(screenshot.data[0]).toBe(0); - }); }); From 37066f1bcde6c53901dd73a7d493806f0bdf19cc Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 20 Nov 2026 10:15:52 -0500 Subject: [PATCH 20/32] refactor(dicom): keep one copy of groupBy, abortError and asCoroutine The DICOM core cannot import application code, so the app imports these helpers from the core and its own copies go. --- packages/dicom/core/collections/groupBy.ts | 2 +- src/core/cine/DicomCineImage.ts | 2 +- src/core/streaming/dicomVolumeImage.ts | 3 ++- src/io/import/importDataSources.ts | 3 ++- src/io/import/processors/updateUriType.ts | 2 +- src/store/datasets-dicom.ts | 3 ++- src/utils/index.ts | 26 ---------------------- 7 files changed, 9 insertions(+), 32 deletions(-) diff --git a/packages/dicom/core/collections/groupBy.ts b/packages/dicom/core/collections/groupBy.ts index f12ba239a..ba0f8fdfe 100644 --- a/packages/dicom/core/collections/groupBy.ts +++ b/packages/dicom/core/collections/groupBy.ts @@ -1,5 +1,5 @@ /** Groups preserve input order, both of the keys and of their members. */ -export const groupBy = (items: T[], keyOf: (item: T) => K) => { +export const groupBy = (items: readonly T[], keyOf: (item: T) => K) => { const groups = new Map(); items.forEach((item) => { const key = keyOf(item); diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index 9b6b655e8..a24b32855 100644 --- a/src/core/cine/DicomCineImage.ts +++ b/src/core/cine/DicomCineImage.ts @@ -18,7 +18,7 @@ import { } from '@/packages/dicom/core/metadata/spatialMetadata'; import { unitToMm } from '@/packages/dicom/core/metadata/ultrasoundRegion'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { abortError } from '@/src/utils'; +import { abortError } from '@/packages/dicom/core/utils'; import { type CineHeader, isNativeTransferSyntax, diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 8a90a0434..09e536f42 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -32,7 +32,8 @@ import { } from '@/src/io/dicom'; import { convertItkToVtkImage } from '@/src/io/convertItkToVtkImage'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; -import { abortError, ensureError } from '@/src/utils'; +import { ensureError } from '@/src/utils'; +import { abortError } from '@/packages/dicom/core/utils'; type DicomVolumeImageEvents = ProgressiveImageEvents & { /** A decoded region of the current image, as an inclusive extent. */ diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 3160f9094..6b1d8cdcf 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -40,7 +40,8 @@ import openUriStream from '@/src/io/import/processors/openUriStream'; import downloadStream from '@/src/io/import/processors/downloadStream'; import { asyncSelect } from '@/src/utils/asyncSelect'; import { evaluateChain, Skip } from '@/src/utils/evaluateChain'; -import { ensureError, groupBy } from '@/src/utils'; +import { ensureError } from '@/src/utils'; +import { groupBy } from '@/packages/dicom/core/collections/groupBy'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; import { useDatasetStore } from '@/src/store/datasets'; import { diff --git a/src/io/import/processors/updateUriType.ts b/src/io/import/processors/updateUriType.ts index a272ec3d8..7cc4cfbce 100644 --- a/src/io/import/processors/updateUriType.ts +++ b/src/io/import/processors/updateUriType.ts @@ -3,7 +3,7 @@ import StreamingByteReader from '@/packages/dicom/core/header/streamingByteReade import { ImportHandler, asIntermediateResult } from '@/src/io/import/common'; import { getFileMimeFromMagicStream } from '@/src/io/magic'; import { getMimeTypeFromFilename } from '@/src/io/io'; -import { asCoroutine } from '@/src/utils'; +import { asCoroutine } from '@/packages/dicom/core/utils'; const DoneSignal = Symbol('DoneSignal'); diff --git a/src/store/datasets-dicom.ts b/src/store/datasets-dicom.ts index 6ff1dc981..767562842 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -23,7 +23,8 @@ import DicomCineImage from '@/src/core/cine/DicomCineImage'; import { isCineInstance, readCineHeader } from '@/src/core/cine/cineInstance'; import { surfaceWarning, useMessageStore } from '@/src/store/messages'; import { viewedSlice } from '@/src/store/dicom-viewed-slice'; -import { ensureError, groupBy, removeFromArray } from '../utils'; +import { ensureError, removeFromArray } from '../utils'; +import { groupBy } from '@/packages/dicom/core/collections/groupBy'; export const ANONYMOUS_PATIENT = 'Anonymous'; export const ANONYMOUS_PATIENT_ID = 'ANONYMOUS'; diff --git a/src/utils/index.ts b/src/utils/index.ts index 3c7166a20..c1010e739 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -95,16 +95,6 @@ export function partition( return partitioned; } -/** Groups keep input order, both of the keys and of their members. */ -export const groupBy = (items: readonly T[], keyOf: (item: T) => string) => - items.reduce((groups, item) => { - const key = keyOf(item); - const group = groups.get(key); - if (group) group.push(item); - else groups.set(key, [item]); - return groups; - }, new Map()); - /** A cursor over `items`: each call hands out the next one, wrapping around. */ export function cycle(items: readonly T[]) { let index = 0; @@ -255,9 +245,6 @@ export function ensureError(e: unknown) { return e instanceof Error ? e : new Error(JSON.stringify(e)); } -export const abortError = (message: string) => - new DOMException(message, 'AbortError'); - export function getErrorDetail(error: unknown, fallback: string): string { return error instanceof Error && error.message ? error.message : fallback; } @@ -326,16 +313,3 @@ export function addEventListenerOnce( }; target.addEventListener(event, handler); } - -/** - * Wraps a generator as a coroutine. - * @param generator - * @param args - * @returns - */ -export function asCoroutine(gen: Generator) { - // run initial code - const result = gen.next(); - if (result.done) return () => result; - return (value: N): IteratorResult => gen.next(value); -} From 5b95dbd223311b28abcaf0da2c00b0f8de0aaec2 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 20 Nov 2026 10:03:39 -0500 Subject: [PATCH 21/32] refactor(dicom): drop the registry kind and change fields The store reads a SEG collection from its first member's Modality, as it does for cine, and a collection update says only whether its volume stands. --- .../__tests__/instanceRegistry.spec.ts | 55 +++++++++---------- .../core/collections/instanceRegistry.ts | 41 +++----------- packages/dicom/core/volume/allocateVolume.ts | 4 +- src/store/datasets-dicom.ts | 22 +++++--- tests/dicomVolumeFixtures.ts | 9 +-- tests/fixtures/dicom-pages/loadVolume.ts | 5 +- tests/unit/octFixture.ts | 1 - 7 files changed, 56 insertions(+), 81 deletions(-) diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts index b386ececb..783a7536e 100644 --- a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts +++ b/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -174,11 +174,15 @@ describe('pure instance registry', () => { expect(after.removed).toEqual([]); expect( - again.updates.map(({ id, members, change }) => [id, members[0], change]) - ).toContainEqual([idOf(clips[1]), clips[1], 'unchanged']); + again.updates.map(({ id, members, unchanged }) => [ + id, + members[0], + unchanged, + ]) + ).toContainEqual([idOf(clips[1]), clips[1], true]); expect( - again.updates.find((update) => update.members[0] === clips[0])!.change - ).toBe('new'); + again.updates.find((update) => update.members[0] === clips[0])!.unchanged + ).toBe(false); }); it('does not confuse a numeric UID with an anonymous clip identity', () => { @@ -269,10 +273,10 @@ describe('pure instance registry', () => { const [a, b] = [0, 1].map((z) => slice({ sop: `c${z}`, z })); const changes = registerAll([[a], [slice({ sop: 'c0', z: 0 })], [b]]).map( - ({ updates }) => updates.map((update) => update.change) + ({ updates }) => updates.map((update) => update.unchanged) ); - expect(changes).toEqual([['new'], ['unchanged'], ['changed']]); + expect(changes).toEqual([[false], [true], [false]]); }); it('reports a collection a sibling relabelled without calling its volume changed', () => { @@ -283,14 +287,14 @@ describe('pure instance registry', () => { expect(first.updates[0].collection.label).toBeNull(); expect( - second.updates.map(({ id, change, collection }) => [ + second.updates.map(({ id, unchanged, collection }) => [ id === first.updates[0].id, - change, + unchanged, collection.label, ]) ).toEqual([ - [true, 'unchanged', 'acquisition 1'], - [false, 'new', 'acquisition 2'], + [true, true, 'acquisition 1'], + [false, false, 'acquisition 2'], ]); expect(second.removed).toEqual([]); }); @@ -306,15 +310,15 @@ describe('pure instance registry', () => { expect( second.updates - .map(({ members, change, collection }) => [ + .map(({ members, unchanged, collection }) => [ sopsOf(members), - change, + unchanged, collection.label, ]) .sort() ).toEqual([ - [['1-0', '1-2'], 'unchanged', 'rows 4'], - [['scout'], 'new', 'rows 8'], + [['1-0', '1-2'], true, 'rows 4'], + [['scout'], false, 'rows 8'], ]); expect( third.updates.map((update) => sopsOf(update.members)) @@ -344,10 +348,12 @@ describe('pure instance registry', () => { ['blind'], ]); expect( - again.updates.map(({ id, members, change }) => [id, members, change]) - ).toEqual( - separated.updates.map(({ id, members }) => [id, members, 'unchanged']) - ); + again.updates.map(({ id, members, unchanged }) => [ + id, + members, + unchanged, + ]) + ).toEqual(separated.updates.map(({ id, members }) => [id, members, true])); }); it('reports a collection whose axes a sibling pass outvoted as changed', () => { @@ -368,20 +374,9 @@ describe('pure instance registry', () => { expect(after.collection.orientation).not.toEqual( before.collection.orientation ); - expect(after.change).toBe('changed'); + expect(after.unchanged).toBe(false); }); - it.each(['SEG', 'SEG\u0000'])( - 'reports SEG modality %j as a segmentation collection', - (modality) => { - const [image, seg] = lastUpdates([ - [slice({ sop: 'image' }), slice({ sop: 'seg', modality, rows: '8' })], - ]); - - expect([image.kind, seg.kind]).toEqual(['image', 'segmentation']); - } - ); - it('plans series independently', () => { const first = slice({ sop: 'a', series: SERIES_UID }); const second = slice({ sop: 'b', series: OTHER_SERIES_UID }); diff --git a/packages/dicom/core/collections/instanceRegistry.ts b/packages/dicom/core/collections/instanceRegistry.ts index 8378d8ab9..b4cc3d51a 100644 --- a/packages/dicom/core/collections/instanceRegistry.ts +++ b/packages/dicom/core/collections/instanceRegistry.ts @@ -1,6 +1,6 @@ import type { Instance } from '../instance/readInstance'; import { trimDicomPadding } from '../utils'; -import { getDatasetModality, getDatasetTag } from '../metadata/datasetAccess'; +import { getDatasetTag } from '../metadata/datasetAccess'; import { Tags } from '../metadata/dicomTags'; import { planDicomCollections, @@ -13,31 +13,15 @@ import { readDatasetDetails } from './datasetDetails'; import { groupBy } from './groupBy'; import type { Reconstruction } from './reconstructVolume'; -/** - * How a collection differs from what was last committed under its ID: - * `unchanged` has the same members and geometry, so its volume stands. - */ -type CollectionChange = 'new' | 'unchanged' | 'changed'; - -type CollectionUpdateFields = { +export type InstanceCollectionUpdate = { id: string; collection: DicomCollection; /** Registered instances in the collection's order, aligned with collection.members. */ members: Instance[]; /** Aligned with members: the batch's own instance wherever it re-supplied one. */ provenance: Instance[]; - change: CollectionChange; -}; - -/** - * An image volume, or a SEG object whose pixels are labels rather than an - * image. A union so that checking `kind` narrows the update for allocateVolume. - */ -export type InstanceCollectionUpdate = CollectionUpdateFields & - ({ kind: 'image' } | { kind: 'segmentation' }); - -export type ImageCollectionUpdate = InstanceCollectionUpdate & { - kind: 'image'; + /** Same members and geometry as last committed under this ID, so its volume stands. */ + unchanged: boolean; }; // An instance with no SOP Instance UID is identified by its object, so two of @@ -112,23 +96,15 @@ const sameReconstruction = (a: Reconstruction, b: Reconstruction) => reasonOf(a) === reasonOf(b) && a.sliceSpacing === b.sliceSpacing; -const unchanged = (before: Committed, after: Committed) => +const sameVolume = (before: Committed, after: Committed) => sameList(before.members, after.members) && sameList(before.orientation, after.orientation) && sameReconstruction(before.reconstruction, after.reconstruction); -const changeOf = (before: Committed | undefined, after: Committed) => { - if (!before) return 'new'; - return unchanged(before, after) ? 'unchanged' : 'changed'; -}; - const sameDescription = (before: Committed | undefined, after: Committed) => !before || (before.label === after.label && sameList(before.warnings, after.warnings)); -const kindOf = (first: Instance) => - getDatasetModality(first.dataset) === 'SEG' ? 'segmentation' : 'image'; - // The first registration of an instance wins; a re-supply only reports back. function mergeBatch(series: SeriesState, batch: Registered[]) { const instances = new Map(series.instances); @@ -182,18 +158,17 @@ function planSeries( }; const members = entries.map((entry) => entry.instance); const previous = series.committed.get(id); - const change = changeOf(previous, committed); + const unchanged = !!previous && sameVolume(previous, committed); const update: InstanceCollectionUpdate = { id, collection, members, provenance: entries.map(provenanceOf), - change, - kind: kindOf(members[0]), + unchanged, }; // A replan can move members or relabel a collection the batch brought nothing. const changed = - change !== 'unchanged' || + !unchanged || !sameDescription(previous, committed) || committed.members.some((key) => supplied.has(key)); return { committed, update, changed }; diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts index 89e433b59..7f825637e 100644 --- a/packages/dicom/core/volume/allocateVolume.ts +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -1,5 +1,5 @@ import type { Instance } from '../instance/readInstance'; -import type { ImageCollectionUpdate } from '../collections/instanceRegistry'; +import type { InstanceCollectionUpdate } from '../collections/instanceRegistry'; import type { SpatialMetadata } from '../metadata/spatialMetadata'; import type { VolumeBuffer } from './pixelFormat'; import { nativeFramesOverrun } from '../pixels/frameIndex'; @@ -88,7 +88,7 @@ function copyDecoded(volume: Volume, previous: Volume) { * again. */ export function allocateVolume( - update: Pick, + update: Pick, previous?: Volume ) { const { collection, members } = update; diff --git a/src/store/datasets-dicom.ts b/src/store/datasets-dicom.ts index 767562842..e4b46ff00 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -10,7 +10,10 @@ import { type InstanceCollectionUpdate, type RegistryState, } from '@/packages/dicom/core/collections/instanceRegistry'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; +import { + getDatasetModality, + getDatasetTag, +} from '@/packages/dicom/core/metadata/datasetAccess'; import { seriesKeyOf } from '@/packages/dicom/core/collections/instanceFacts'; import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; import { trimDicomPadding } from '@/packages/dicom/core/utils'; @@ -248,9 +251,15 @@ const cineRecord = ( }; }; -const cineMember = ({ kind, members }: InstanceCollectionUpdate) => - kind === 'image' && members.length === 1 && isCineInstance(members[0]) - ? members[0] +// A SEG object's pixels are labels rather than an image. +const isSegmentation = ({ members }: InstanceCollectionUpdate) => + getDatasetModality(members[0].dataset) === 'SEG'; + +const cineMember = (update: InstanceCollectionUpdate) => + !isSegmentation(update) && + update.members.length === 1 && + isCineInstance(update.members[0]) + ? update.members[0] : null; function cineCandidate( @@ -266,7 +275,7 @@ function cineCandidate( } function fillFor(update: InstanceCollectionUpdate, previous?: Volume) { - if (update.kind === 'segmentation') + if (isSegmentation(update)) return (image: DicomVolumeImage) => image.setSegmentation(update.members); const volume = allocateVolume(update, previous); return (image: DicomVolumeImage) => { @@ -285,8 +294,7 @@ function planCandidate(update: InstanceCollectionUpdate): Candidate { if (clip) return cineCandidate(id, clip, cached); const record = volumeRecord(update); // A re-import retries whatever failed to load. - if (cached && update.change === 'unchanged') - return { kind: 'keep', id, record }; + if (cached && update.unchanged) return { kind: 'keep', id, record }; const shown = cached instanceof DicomVolumeImage ? cached : undefined; return { kind: 'dicom', diff --git a/tests/dicomVolumeFixtures.ts b/tests/dicomVolumeFixtures.ts index a0ecc88e4..986af5be9 100644 --- a/tests/dicomVolumeFixtures.ts +++ b/tests/dicomVolumeFixtures.ts @@ -9,12 +9,9 @@ import { } from '@/packages/dicom/core/pixels/pixelDecoder'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -/** The first collection planned from these members, which must be an image. */ -export const plannedUpdate = (members: Instance[]) => { - const [update] = registerInstances(emptyRegistry, members).updates; - if (update.kind !== 'image') throw new Error(`Planned a ${update.kind}`); - return update; -}; +/** The first collection planned from these members. */ +export const plannedUpdate = (members: Instance[]) => + registerInstances(emptyRegistry, members).updates[0]; /** Runtime options that send every instance whole to `decode`. */ export const decodingWith = (decode: WholeInstanceDecode) => ({ diff --git a/tests/fixtures/dicom-pages/loadVolume.ts b/tests/fixtures/dicom-pages/loadVolume.ts index df72a1d35..1b5cdf4af 100644 --- a/tests/fixtures/dicom-pages/loadVolume.ts +++ b/tests/fixtures/dicom-pages/loadVolume.ts @@ -7,6 +7,7 @@ import { registerInstances, type InstanceCollectionUpdate, } from '@/packages/dicom/core/collections/instanceRegistry'; +import { getDatasetModality } from '@/packages/dicom/core/metadata/datasetAccess'; import { loadVolume } from '@/packages/dicom/core/volume/loadVolume'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; import { @@ -20,8 +21,8 @@ export async function loadCollection( update: InstanceCollectionUpdate, previous?: Volume ) { - if (update.kind !== 'image') - throw new Error(`Expected a volume, got ${update.kind}`); + if (getDatasetModality(update.members[0].dataset) === 'SEG') + throw new Error('Expected a volume, got a segmentation'); const volume = allocateVolume(update, previous); const image = toVtkImageData(volume); for await (const loaded of loadVolume(volume, { runtime, signal: never })) { diff --git a/tests/unit/octFixture.ts b/tests/unit/octFixture.ts index 9dd7680bd..d9374cdcd 100644 --- a/tests/unit/octFixture.ts +++ b/tests/unit/octFixture.ts @@ -29,7 +29,6 @@ export function volumeOf(instances: Instance[]) { const update = plannedUpdate(instances); if (update.members.length === instances.length) return allocateVolume(update); return allocateVolume({ - kind: 'image', members: instances, collection: { ...plannedUpdate([instances[0]]).collection, From 8b38c5ac1673f6f41f55acbf1ac95551b033a6f7 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 20 Nov 2026 10:07:14 -0500 Subject: [PATCH 22/32] refactor(dicom): read ultrasound regions from the dataset Instance no longer carries a derived ultrasoundRegions field; spacing and occupied depth read the regions from the header when the modality is US. --- .../__tests__/readInstanceSources.spec.ts | 18 +++-------- packages/dicom/core/instance/readInstance.ts | 10 ------ .../metadata/__tests__/dcmjsParser.spec.ts | 3 +- .../core/pixels/__tests__/frameIndex.spec.ts | 1 - .../volume/__tests__/allocateVolume.spec.ts | 28 +++++++++------- .../dicom/core/volume/ultrasoundSpacing.ts | 6 ++-- packages/dicom/core/volume/volumeLayout.ts | 8 ++--- src/core/cine/__tests__/cineFixtures.ts | 1 - .../__tests__/occupiedDepthSupport.spec.ts | 32 +++++++++++-------- src/enface/occupiedDepthSupport.ts | 15 ++++----- .../processors/__tests__/handleDicom.spec.ts | 12 +++---- tests/dicomDataset.ts | 1 - 12 files changed, 59 insertions(+), 76 deletions(-) diff --git a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts index c4b4682e6..b24704394 100644 --- a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts +++ b/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts @@ -4,6 +4,7 @@ import { Tags } from '../../metadata/dicomTags'; import { findElement, readDicomDataset } from '../../metadata/dicomDataset'; import { getDatasetTag } from '../../metadata/datasetAccess'; import { sequenceItems } from '../../metadata/functionalGroups'; +import { readUltrasoundRegions } from '../../metadata/ultrasoundRegion'; import { EXPLICIT_VR_LITTLE_ENDIAN, IMPLICIT_VR_LITTLE_ENDIAN, @@ -205,22 +206,13 @@ describe('readInstance over byte sources', () => { const instance = await readInstance(source, never()); expect(instance.dataset).toEqual(readDicomDataset(bytes)); - expect(instance.ultrasoundRegions?.regionCount).toBe(1); - expect(instance.ultrasoundRegions?.region?.physicalDeltaX).toBeCloseTo( - REGION.physicalDeltaX - ); - expect(instance.ultrasoundRegions?.region?.physicalDeltaY).toBeCloseTo( - REGION.physicalDeltaY - ); + const regions = readUltrasoundRegions(instance.dataset); + expect(regions.regionCount).toBe(1); + expect(regions.region?.physicalDeltaX).toBeCloseTo(REGION.physicalDeltaX); + expect(regions.region?.physicalDeltaY).toBeCloseTo(REGION.physicalDeltaY); expect(stats.reads).toBe(1); }); - it('reports no ultrasound regions for a non-ultrasound modality', async () => { - const bytes = syntheticSlice({ modality: 'MR', ultrasoundRegion: REGION }); - - expect((await readHeader(bytes)).ultrasoundRegions).toBeNull(); - }); - it('reads every tag of an object that has no Pixel Data', async () => { const bytes = withoutPixelData(syntheticSlice({ modality: 'SR' })); diff --git a/packages/dicom/core/instance/readInstance.ts b/packages/dicom/core/instance/readInstance.ts index 8b27c8cd4..cedb2dcdf 100644 --- a/packages/dicom/core/instance/readInstance.ts +++ b/packages/dicom/core/instance/readInstance.ts @@ -1,15 +1,10 @@ import type { ByteSource } from '../source/byteSource'; import { readPublicDataset, type DicomDataset } from '../metadata/dicomDataset'; import type { DicomLayout } from '../metadata/dicomLayout'; -import { getDatasetModality } from '../metadata/datasetAccess'; import { readDicomHeader, type PixelDataElement, } from '../header/readDicomHeader'; -import { - readUltrasoundRegions, - type UltrasoundRegions, -} from '../metadata/ultrasoundRegion'; import type { Awaitable } from '../utils'; /** @@ -23,7 +18,6 @@ export type Instance = Readonly<{ dataset: DicomDataset; /** How the bytes opened: with or without the Part 10 preamble and file meta. */ layout: DicomLayout | null; - ultrasoundRegions: UltrasoundRegions | null; /** As the file meta names it, or as a bare data set's first element suggests. */ transferSyntaxUid: string | null; /** Null when the header names no Pixel Data or its element head is cut short. */ @@ -50,10 +44,6 @@ export async function readInstance( source, dataset, layout, - ultrasoundRegions: - getDatasetModality(dataset) === 'US' - ? readUltrasoundRegions(dataset) - : null, transferSyntaxUid, pixelData, }); diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts index 7c4171928..8b27dffbd 100644 --- a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -1,6 +1,7 @@ import { readDicomDataset, findElement } from '../dicomDataset'; import { getDatasetTag } from '../datasetAccess'; import { getFrameTag, sequenceItems } from '../functionalGroups'; +import { readUltrasoundRegions } from '../ultrasoundRegion'; import { createDicomParser } from '../../header/dicomParser'; import { deflateRawSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; @@ -279,7 +280,7 @@ describe('lenient headers with standards-defined values', () => { ultrasoundRegion: { physicalDeltaX: 0.05, physicalDeltaY: 0.1 }, }); const instance = await readHeader(bytes); - expect(instance.ultrasoundRegions).toMatchObject({ + expect(readUltrasoundRegions(instance.dataset)).toMatchObject({ regionCount: 1, region: { physicalDeltaX: 0.05, physicalDeltaY: 0.1 }, }); diff --git a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts index 3b4b344d8..e9ca5c31f 100644 --- a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts +++ b/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts @@ -89,7 +89,6 @@ describe('indexFrames', () => { source: { read: () => new ReadableStream() }, dataset: { elements: [], specificCharacterSet: null }, layout: null, - ultrasoundRegions: null, transferSyntaxUid: EXPLICIT_LE, pixelData: null, }) diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts index a924dd5e9..62446d5a6 100644 --- a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -4,6 +4,8 @@ import { allocated, pixelSlice } from './volumeFixture'; import { plannedUpdate } from '@/tests/dicomVolumeFixtures'; import { readHeader } from '@/tests/dicomSourceFixtures'; import { nativePixelDicom } from '@/tests/nativePixelDicom'; +import { datasetFromTags } from '@/tests/dicomDataset'; +import { Tags } from '../../metadata/dicomTags'; describe('allocateVolume', () => { it('allocates an empty buffer placed by the planned stack', () => { @@ -93,18 +95,22 @@ describe('allocateVolume', () => { }); it('applies the first ultrasound region as display spacing', () => { - const ultrasound = { - ...pixelSlice(0, { modality: 'US' }), - ultrasoundRegions: { - regionCount: 1, - region: { - physicalDeltaX: 0.01, - physicalDeltaY: 0.02, - physicalUnitsXDirection: 3, - physicalUnitsYDirection: 3, - }, + const ultrasound = pixelSlice(0, { modality: 'US' }); + ultrasound.dataset.elements.push({ + ...datasetFromTags([[Tags.SequenceOfUltrasoundRegions, '']]).elements[0], + vr: 'SQ', + values: { + kind: 'sequence', + items: [ + datasetFromTags([ + [Tags.PhysicalDeltaX, '0.01'], + [Tags.PhysicalDeltaY, '0.02'], + [Tags.PhysicalUnitsXDirection, '3'], + [Tags.PhysicalUnitsYDirection, '3'], + ]), + ], }, - }; + }); const volume = allocated([ultrasound]); diff --git a/packages/dicom/core/volume/ultrasoundSpacing.ts b/packages/dicom/core/volume/ultrasoundSpacing.ts index 811d14b6e..c7ba9b79f 100644 --- a/packages/dicom/core/volume/ultrasoundSpacing.ts +++ b/packages/dicom/core/volume/ultrasoundSpacing.ts @@ -1,5 +1,5 @@ import { getDatasetModality } from '../metadata/datasetAccess'; -import { unitToMm } from '../metadata/ultrasoundRegion'; +import { readUltrasoundRegions, unitToMm } from '../metadata/ultrasoundRegion'; import { physicalSpacing, type SpatialMetadata, @@ -26,8 +26,8 @@ export function applyUltrasoundSpacing( // Ultrasound DICOMs are typically a single multi-frame instance, so the // first region table applies to the whole image. - const regions = sources[0].ultrasoundRegions; - if (!regions?.region) return unchanged; + const regions = readUltrasoundRegions(sources[0].dataset); + if (!regions.region) return unchanged; const { region } = regions; const notes = [...spatialMetadata.notes, ...regionNotes(regions.regionCount)]; diff --git a/packages/dicom/core/volume/volumeLayout.ts b/packages/dicom/core/volume/volumeLayout.ts index 96181b683..5fa01aa87 100644 --- a/packages/dicom/core/volume/volumeLayout.ts +++ b/packages/dicom/core/volume/volumeLayout.ts @@ -11,18 +11,14 @@ import { type SpatialMetadata, } from '../metadata/spatialMetadata'; import { getFrameTag } from '../metadata/functionalGroups'; -import type { UltrasoundRegions } from '../metadata/ultrasoundRegion'; import { frameCount } from '../pixels/pixelDecoder'; import { numberOr } from '../utils'; import { nmGeometry } from './nmGeometry'; import { getVolumeBufferType, instancePixelFormats } from './pixelFormat'; import { applyUltrasoundSpacing } from './ultrasoundSpacing'; -/** What allocation reads from one member: its header and ultrasound regions. */ -export type VolumeSource = { - dataset: DicomDataset; - ultrasoundRegions?: UltrasoundRegions | null; -}; +/** What allocation reads from one member: its header. */ +export type VolumeSource = { dataset: DicomDataset }; const isPositiveFiniteNumber = (value: number) => Number.isFinite(value) && value > 0; diff --git a/src/core/cine/__tests__/cineFixtures.ts b/src/core/cine/__tests__/cineFixtures.ts index 1740c02ed..2a6614c98 100644 --- a/src/core/cine/__tests__/cineFixtures.ts +++ b/src/core/cine/__tests__/cineFixtures.ts @@ -60,7 +60,6 @@ export const cineInstance = ( source: fromBlob(new Blob([pixels as BlobPart])), dataset: { ...dataset, elements: [...dataset.elements, ...elements] }, layout: { preamble: true, fileMeta: true } as const, - ultrasoundRegions: null, transferSyntaxUid, pixelData: { offset: 0, diff --git a/src/enface/__tests__/occupiedDepthSupport.spec.ts b/src/enface/__tests__/occupiedDepthSupport.spec.ts index c3a375736..88562d04a 100644 --- a/src/enface/__tests__/occupiedDepthSupport.spec.ts +++ b/src/enface/__tests__/occupiedDepthSupport.spec.ts @@ -7,7 +7,12 @@ import { createOCTFixture, volumeOf } from '@/tests/unit/octFixture'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { removeDicomTag, setDicomTag } from './dicomMetadataFixture'; +import { datasetFromTags } from '@/tests/dicomDataset'; +import { + removeDicomTag, + setDicomSequence, + setDicomTag, +} from './dicomMetadataFixture'; describe('occupied-depth support for loaded volumes', () => { const pendingReads: (() => void)[] = []; @@ -66,19 +71,18 @@ describe('occupied-depth support for loaded volumes', () => { const { dataset } = fixture.instance; removeDicomTag(dataset, Tags.PixelSpacing); setDicomTag(dataset, Tags.Modality, 'US'); - const ultrasound = Object.freeze({ - ...fixture.instance, - ultrasoundRegions: { - regionCount, - region: { - physicalUnitsXDirection: 3, - physicalUnitsYDirection: 3, - physicalDeltaX: 0.002, - physicalDeltaY: 0.00104, - }, - }, - }); - fixture.image.setVolume(volumeOf([ultrasound])); + const region = datasetFromTags([ + [Tags.PhysicalUnitsXDirection, '3'], + [Tags.PhysicalUnitsYDirection, '3'], + [Tags.PhysicalDeltaX, '0.002'], + [Tags.PhysicalDeltaY, '0.00104'], + ]); + setDicomSequence( + dataset, + Tags.SequenceOfUltrasoundRegions, + Array.from({ length: regionCount }, () => region) + ); + fixture.image.setVolume(volumeOf([fixture.instance])); const id = useImageCacheStore().addProgressiveImage(fixture.image); await untilLoaded(id); expect(fixture.image.getVtkImageData().getSpacing()[1]).toBeCloseTo( diff --git a/src/enface/occupiedDepthSupport.ts b/src/enface/occupiedDepthSupport.ts index 9289e65af..8acc7b95b 100644 --- a/src/enface/occupiedDepthSupport.ts +++ b/src/enface/occupiedDepthSupport.ts @@ -4,19 +4,18 @@ import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { unitToMm } from '@/packages/dicom/core/metadata/ultrasoundRegion'; +import { + readUltrasoundRegions, + unitToMm, +} from '@/packages/dicom/core/metadata/ultrasoundRegion'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; import { dicomSeriesGeometry } from '@/src/core/streaming/dicom/seriesGeometry'; function measurementMetadata(instance: Instance) { const tags = new Map(enFaceTags(instance.dataset)); - const regions = instance.ultrasoundRegions; - if ( - tags.get(Tags.Modality)?.trim() !== 'US' || - !regions?.region || - regions.regionCount > 1 - ) - return tags; + if (tags.get(Tags.Modality)?.trim() !== 'US') return tags; + const regions = readUltrasoundRegions(instance.dataset); + if (!regions.region || regions.regionCount > 1) return tags; const { region } = regions; const xFactor = unitToMm(region.physicalUnitsXDirection); const yFactor = unitToMm(region.physicalUnitsYDirection); diff --git a/src/io/import/processors/__tests__/handleDicom.spec.ts b/src/io/import/processors/__tests__/handleDicom.spec.ts index d2293473f..638c08cf0 100644 --- a/src/io/import/processors/__tests__/handleDicom.spec.ts +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -5,6 +5,7 @@ import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; import { readBytes } from '@/packages/dicom/core/source/byteSource'; import { readDicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { readUltrasoundRegions } from '@/packages/dicom/core/metadata/ultrasoundRegion'; import type { DataSource } from '@/src/io/import/dataSource'; import { fileToDataSource } from '@/src/io/import/dataSource'; import handleDicom from '@/src/io/import/processors/handleDicom'; @@ -169,13 +170,10 @@ describe('handleDicom', () => { const { instance } = instanceOf(await handleDicom(source(bytes))); - expect(instance.ultrasoundRegions?.regionCount).toBe(1); - expect(instance.ultrasoundRegions?.region?.physicalDeltaX).toBeCloseTo( - REGION.physicalDeltaX - ); - expect(instance.ultrasoundRegions?.region?.physicalDeltaY).toBeCloseTo( - REGION.physicalDeltaY - ); + const regions = readUltrasoundRegions(instance.dataset); + expect(regions.regionCount).toBe(1); + expect(regions.region?.physicalDeltaX).toBeCloseTo(REGION.physicalDeltaX); + expect(regions.region?.physicalDeltaY).toBeCloseTo(REGION.physicalDeltaY); } ); diff --git a/tests/dicomDataset.ts b/tests/dicomDataset.ts index b65c7a582..981f520e2 100644 --- a/tests/dicomDataset.ts +++ b/tests/dicomDataset.ts @@ -33,7 +33,6 @@ export const instanceFor = ( source, dataset, layout: null, - ultrasoundRegions: null, transferSyntaxUid: null, pixelData: null, }); From 0eb9bdca8bf5350f1d326ca0a1cbfd8119984995 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 20 Nov 2026 10:14:17 -0500 Subject: [PATCH 23/32] refactor(dicom): write tag constants in their element form Tags hold GGGGEEEE keys, so dataset lookups compare them directly and the gggg|eeee spelling no longer needs translating. --- .../collections/__tests__/sliceFixture.ts | 2 +- .../__tests__/dicomCharacterSets.spec.ts | 4 +- packages/dicom/core/metadata/datasetAccess.ts | 6 +- packages/dicom/core/metadata/dicomTags.ts | 98 +++++++++---------- .../dicom/core/metadata/functionalGroups.ts | 17 ++-- .../core/volume/__tests__/loadVolume.spec.ts | 3 +- 6 files changed, 63 insertions(+), 67 deletions(-) diff --git a/packages/dicom/core/collections/__tests__/sliceFixture.ts b/packages/dicom/core/collections/__tests__/sliceFixture.ts index 6c6ee666c..9e3124563 100644 --- a/packages/dicom/core/collections/__tests__/sliceFixture.ts +++ b/packages/dicom/core/collections/__tests__/sliceFixture.ts @@ -52,7 +52,7 @@ export function sliceDataset(options: SliceOptions = {}) { ...present(Tags.SeriesInstanceUID, series), ...present(Tags.SOPInstanceUID, sop), ...present(Tags.ImagePositionPatient, z, (value) => `0\\0\\${value}`), - ...present('0020|0013', instanceNumber), + ...present(Tags.InstanceNumber, instanceNumber), ...Object.entries(tags), ]) ); diff --git a/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts b/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts index 971efa1f7..25476b276 100644 --- a/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts +++ b/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts @@ -21,8 +21,8 @@ import { } from '@/tests/specs/dicomElementFixtures'; import { rawElement } from '@/tests/specs/syntheticDicom'; -const CURRENT_PATIENT_LOCATION = '0038|0300'; -const STUDY_COMMENTS = '0032|4000'; +const CURRENT_PATIENT_LOCATION = '00380300'; +const STUDY_COMMENTS = '00324000'; const JIS = 'ISO 2022 IR 13\\ISO 2022 IR 87'; const encodeUtf8 = (text: string) => new TextEncoder().encode(text); diff --git a/packages/dicom/core/metadata/datasetAccess.ts b/packages/dicom/core/metadata/datasetAccess.ts index b2b34b0b1..1dc97d227 100644 --- a/packages/dicom/core/metadata/datasetAccess.ts +++ b/packages/dicom/core/metadata/datasetAccess.ts @@ -1,9 +1,6 @@ import type { DicomDataset, DicomElement } from './dicomDataset'; import { trimDicomPadding } from '../utils'; -/** `ggggeeee` or `gggg|eeee`, in either case. */ -export const canonicalTag = (tag: string) => tag.replace('|', '').toUpperCase(); - /** Text and numeric values retain multiplicity; sequences and opaque bytes do not become text. */ function getElementText({ values }: DicomElement) { switch (values.kind) { @@ -21,8 +18,7 @@ export function getDatasetTag( dataset: DicomDataset | null | undefined, tag: string ) { - const requestedTag = canonicalTag(tag); - const element = dataset?.elements.find((entry) => entry.tag === requestedTag); + const element = dataset?.elements.find((entry) => entry.tag === tag); return element ? getElementText(element) : undefined; } diff --git a/packages/dicom/core/metadata/dicomTags.ts b/packages/dicom/core/metadata/dicomTags.ts index edefa324d..bac8c166b 100644 --- a/packages/dicom/core/metadata/dicomTags.ts +++ b/packages/dicom/core/metadata/dicomTags.ts @@ -1,53 +1,53 @@ export const Tags = { - SOPInstanceUID: '0008|0018', - PatientName: '0010|0010', - PatientID: '0010|0020', - PatientBirthDate: '0010|0030', - PatientSex: '0010|0040', - StudyInstanceUID: '0020|000d', - StudyDate: '0008|0020', - StudyTime: '0008|0030', - StudyID: '0020|0010', - AccessionNumber: '0008|0050', - StudyDescription: '0008|1030', - Modality: '0008|0060', - SeriesInstanceUID: '0020|000e', - SeriesNumber: '0020|0011', - SeriesDate: '0008|0021', - SeriesDescription: '0008|103e', - InstanceNumber: '0020|0013', - WindowLevel: '0028|1050', - WindowWidth: '0028|1051', - VOILUTFunction: '0028|1056', - Rows: '0028|0010', - Columns: '0028|0011', - BitsAllocated: '0028|0100', - BitsStored: '0028|0101', - PixelRepresentation: '0028|0103', - AcquisitionNumber: '0020|0012', - TemporalPositionIdentifier: '0020|0100', - EchoNumbers: '0018|0086', - DiffusionBValue: '0018|9087', - ImagePositionPatient: '0020|0032', - ImageOrientationPatient: '0020|0037', - PixelSpacing: '0028|0030', - SpacingBetweenSlices: '0018|0088', - SliceThickness: '0018|0050', - SequenceName: '0018|0024', - SamplesPerPixel: '0028|0002', - RescaleIntercept: '0028|1052', - RescaleSlope: '0028|1053', - NumberOfFrames: '0028|0008', - SOPClassUID: '0008|0016', - OphthalmicVolumetricPropertiesFlag: '0022|1622', - PhotometricInterpretation: '0028|0004', - PlanarConfiguration: '0028|0006', - FrameTime: '0018|1063', - SequenceOfUltrasoundRegions: '0018|6011', - PhysicalUnitsXDirection: '0018|6024', - PhysicalUnitsYDirection: '0018|6026', - PhysicalDeltaX: '0018|602c', - PhysicalDeltaY: '0018|602e', + SOPInstanceUID: '00080018', + PatientName: '00100010', + PatientID: '00100020', + PatientBirthDate: '00100030', + PatientSex: '00100040', + StudyInstanceUID: '0020000D', + StudyDate: '00080020', + StudyTime: '00080030', + StudyID: '00200010', + AccessionNumber: '00080050', + StudyDescription: '00081030', + Modality: '00080060', + SeriesInstanceUID: '0020000E', + SeriesNumber: '00200011', + SeriesDate: '00080021', + SeriesDescription: '0008103E', + InstanceNumber: '00200013', + WindowLevel: '00281050', + WindowWidth: '00281051', + VOILUTFunction: '00281056', + Rows: '00280010', + Columns: '00280011', + BitsAllocated: '00280100', + BitsStored: '00280101', + PixelRepresentation: '00280103', + AcquisitionNumber: '00200012', + TemporalPositionIdentifier: '00200100', + EchoNumbers: '00180086', + DiffusionBValue: '00189087', + ImagePositionPatient: '00200032', + ImageOrientationPatient: '00200037', + PixelSpacing: '00280030', + SpacingBetweenSlices: '00180088', + SliceThickness: '00180050', + SequenceName: '00180024', + SamplesPerPixel: '00280002', + RescaleIntercept: '00281052', + RescaleSlope: '00281053', + NumberOfFrames: '00280008', + SOPClassUID: '00080016', + OphthalmicVolumetricPropertiesFlag: '00221622', + PhotometricInterpretation: '00280004', + PlanarConfiguration: '00280006', + FrameTime: '00181063', + SequenceOfUltrasoundRegions: '00186011', + PhysicalUnitsXDirection: '00186024', + PhysicalUnitsYDirection: '00186026', + PhysicalDeltaX: '0018602C', + PhysicalDeltaY: '0018602E', }; // DICOM SOP Class UIDs for Ultrasound Multi-frame Image Storage. The current diff --git a/packages/dicom/core/metadata/functionalGroups.ts b/packages/dicom/core/metadata/functionalGroups.ts index 7e4fc7375..3920515f9 100644 --- a/packages/dicom/core/metadata/functionalGroups.ts +++ b/packages/dicom/core/metadata/functionalGroups.ts @@ -1,5 +1,5 @@ import { findElement, type DicomDataset } from './dicomDataset'; -import { canonicalTag, getDatasetTag } from './datasetAccess'; +import { getDatasetTag } from './datasetAccess'; import { getNmDetectorTag } from './nmReconstruction'; export const SHARED_GROUPS = '52009229'; @@ -16,7 +16,7 @@ const IMAGE_MACROS = new Map([ ]); export function sequenceItems(dataset: DicomDataset, tag: string) { - const values = findElement(dataset, canonicalTag(tag))?.values; + const values = findElement(dataset, tag)?.values; return values?.kind === 'sequence' ? values.items : []; } @@ -36,16 +36,15 @@ export function getFrameTag( frameIndex = 0 ) { if (!dataset) return undefined; - const key = canonicalTag(tag); - const macro = IMAGE_MACROS.get(key); - if (!macro) return getDatasetTag(dataset, key); + const macro = IMAGE_MACROS.get(tag); + if (!macro) return getDatasetTag(dataset, tag); const perFrame = sequenceItems(dataset, PER_FRAME_GROUPS)[frameIndex]; const shared = sequenceItems(dataset, SHARED_GROUPS)[0]; return ( - macroValue(perFrame, macro, key) ?? - macroValue(shared, macro, key) ?? - getNmDetectorTag(dataset, key) ?? - getDatasetTag(dataset, key) + macroValue(perFrame, macro, tag) ?? + macroValue(shared, macro, tag) ?? + getNmDetectorTag(dataset, tag) ?? + getDatasetTag(dataset, tag) ); } diff --git a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts index ce87fe2ba..f309545fa 100644 --- a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -22,6 +22,7 @@ import { valueDecoder, } from './volumeFixture'; import { decodingWith } from '@/tests/dicomVolumeFixtures'; +import { Tags } from '../../metadata/dicomTags'; const runtimes: DicomRuntime[] = []; afterEach(() => runtimes.splice(0).forEach((runtime) => runtime.dispose())); @@ -151,7 +152,7 @@ describe('loadVolume', () => { const volume = allocated([ pixelSlice(0, { rows: '1', - tags: { '0028|0011': '1', '0028|0008': String(frames) }, + tags: { [Tags.Columns]: '1', [Tags.NumberOfFrames]: String(frames) }, }), ]); From 735e33d1fc6768b2af0b52869b4be1a781d99143 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 20 Nov 2026 10:19:08 -0500 Subject: [PATCH 24/32] refactor(dicom): keep plain spacing values instead of spatial metadata Volumes and cine images carry only the spacing triple they display; the per-axis provenance record, notes and calibration fields had no reader. --- .../__tests__/spatialMetadata.spec.ts | 37 ++------ .../dicom/core/metadata/spatialMetadata.ts | 69 ++------------- .../volume/__tests__/allocateVolume.spec.ts | 15 +--- .../volume/__tests__/frameGeometry.spec.ts | 45 ++++------ .../volume/__tests__/volumeLayout.spec.ts | 3 +- packages/dicom/core/volume/allocateVolume.ts | 5 +- packages/dicom/core/volume/nmGeometry.ts | 7 +- .../dicom/core/volume/ultrasoundSpacing.ts | 56 +++--------- packages/dicom/core/volume/volumeLayout.ts | 86 +++---------------- src/core/cine/DicomCineImage.ts | 66 ++++---------- src/core/progressiveImage.ts | 11 +-- src/core/streaming/dicomVolumeImage.ts | 1 - src/types/image.ts | 3 - tests/fixtures/dicom-pages/corpus.ts | 7 +- tests/fixtures/dicom-pages/loadVolume.ts | 4 +- 15 files changed, 84 insertions(+), 331 deletions(-) diff --git a/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts b/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts index 7c9551c01..f6cebffd3 100644 --- a/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts +++ b/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts @@ -12,41 +12,18 @@ describe('single-value PixelSpacing display compatibility', () => { ['0.5', 0.5], ['0.0104', 0.0104], [' 2.5\u0000', 2.5], - ] as const)( - 'displays %s as square pixels without claiming calibration', - (raw, value) => { - const dataset = spacingDataset(raw); - const axes = readPixelSpacing(dataset); + ] as const)('displays %s as square pixels', (raw, value) => { + const dataset = spacingDataset(raw); - expect(axes.map((axis) => axis.value)).toEqual([value, value]); - for (const axis of axes) { - expect(axis).toMatchObject({ - unit: 'unknown', - status: 'fallback', - source: 'Single PixelSpacing value', - }); - expect(axis.reason).toContain('square pixels are assumed for display'); - } - expect(readGeometryFacts(dataset).pixelSpacing).toBeNull(); - expect(getDatasetTag(dataset, '00280030')).toBe(raw); - } - ); + expect(readPixelSpacing(dataset)).toEqual([value, value]); + expect(readGeometryFacts(dataset).pixelSpacing).toBeNull(); + expect(getDatasetTag(dataset, '00280030')).toBe(raw); + }); it.each(['0', '-0.5', 'NaN', 'Infinity', ''])( 'does not use %s as display spacing', (raw) => { - expect(readPixelSpacing(spacingDataset(raw))).toEqual([ - expect.objectContaining({ - value: 1, - unit: 'unknown', - status: 'fallback', - }), - expect.objectContaining({ - value: 1, - unit: 'unknown', - status: 'fallback', - }), - ]); + expect(readPixelSpacing(spacingDataset(raw))).toEqual([1, 1]); } ); }); diff --git a/packages/dicom/core/metadata/spatialMetadata.ts b/packages/dicom/core/metadata/spatialMetadata.ts index b67d03f6e..0922743c6 100644 --- a/packages/dicom/core/metadata/spatialMetadata.ts +++ b/packages/dicom/core/metadata/spatialMetadata.ts @@ -1,70 +1,17 @@ -import type { IrregularReason } from '../collections/reconstructVolume'; import type { DicomDataset } from './dicomDataset'; import { getFrameTag } from './functionalGroups'; import { trimDicomPadding } from '../utils'; -/** Describes the spacing actually used by the image, not independent calibration. */ -type AxisSpacing = { - value: number; - unit: 'mm' | 'unknown'; - status: 'declared' | 'derived' | 'fallback'; - source: string; - reason?: string; -}; - -export type SpatialMetadata = { - /** Image index axes, in x/y/z order. */ - axes: [AxisSpacing, AxisSpacing, AxisSpacing]; - reconstruction?: { kind: 'regular' | 'irregular'; reason?: IrregularReason }; - notes: string[]; - calibration?: { type?: string; description?: string }; -}; - -export const physicalSpacing = ( - value: number, - source: string, - status: 'declared' | 'derived' = 'declared' -): AxisSpacing => ({ value, unit: 'mm', status, source }); - -export const fallbackSpacing = (reason: string): AxisSpacing => ({ - value: 1, - unit: 'unknown', - status: 'fallback', - source: 'Display default', - reason, -}); - -export function declaredSpacing(raw: string | undefined, source: string) { - const text = trimDicomPadding(raw ?? ''); - if (!text) return fallbackSpacing(`${source} is not supplied.`); - const value = Number(text); - return Number.isFinite(value) && value > 0 - ? physicalSpacing(value, source) - : fallbackSpacing(`${source} has no usable positive spacing.`); -} - -function singletonPixelSpacing(raw: string) { - const declared = declaredSpacing(raw, 'PixelSpacing'); - if (declared.status === 'fallback') return declared; - return { - ...fallbackSpacing( - 'PixelSpacing has only one value; square pixels are assumed for display.' - ), - value: declared.value, - source: 'Single PixelSpacing value', - }; +/** A positive spacing in mm, or the 1 mm display default. */ +export function spacingOr1(raw: string | undefined) { + const value = Number(trimDicomPadding(raw ?? '')); + return Number.isFinite(value) && value > 0 ? value : 1; } -/** Preserve a usable axis even when the other axis is missing or unusable. */ +/** Column and row spacing; one value means square pixels, and each axis falls back alone. */ export function readPixelSpacing(metadata: DicomDataset | null | undefined) { const raw = trimDicomPadding(getFrameTag(metadata, '00280030') ?? ''); - const parts = raw ? raw.split('\\') : undefined; - if (parts && parts.length < 2) { - const assumed = singletonPixelSpacing(parts[0]); - return [assumed, { ...assumed }] as const; - } - return [ - declaredSpacing(parts?.[1], 'PixelSpacing'), - declaredSpacing(parts?.[0], 'PixelSpacing'), - ] as const; + const parts = raw.split('\\'); + if (parts.length < 2) return [spacingOr1(parts[0]), spacingOr1(parts[0])]; + return [spacingOr1(parts[1]), spacingOr1(parts[0])]; } diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts index 62446d5a6..c336ce1af 100644 --- a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -22,11 +22,6 @@ describe('allocateVolume', () => { expect(volume.data).toBeInstanceOf(Uint16Array); expect(volume.data).toHaveLength(48); expect([...volume.loaded]).toEqual([0, 0, 0]); - expect(volume.spatialMetadata.axes.map((axis) => axis.status)).toEqual([ - 'declared', - 'declared', - 'derived', - ]); expect(Object.isFrozen(volume)).toBe(true); }); @@ -66,14 +61,12 @@ describe('allocateVolume', () => { ); }); - it('keeps an irregular stack in order and reports why it is irregular', () => { - const volume = allocated([0, 1, 3].map((z) => pixelSlice(z))); + it('keeps an irregular stack in order', () => { + const members = [3, 0, 1].map((z) => pixelSlice(z)); + const volume = allocated(members); expect(volume.dimensions[2]).toBe(3); - expect(volume.spatialMetadata.reconstruction).toEqual({ - kind: 'irregular', - reason: 'uneven-slice-spacing', - }); + expect(volume.members).toEqual([members[1], members[2], members[0]]); }); it('takes the planned slice spacing as given', () => { diff --git a/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts b/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts index 262045596..dd27ba4ec 100644 --- a/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts +++ b/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts @@ -21,8 +21,14 @@ import { const allocate = (metadata: DicomDataset) => allocateVolume(plannedUpdate([instanceFor(metadata)])); -const reconstructionOf = (metadata: DicomDataset) => - allocate(metadata).spatialMetadata.reconstruction; +/** The planned reconstruction's kind and, when irregular, its reason. */ +const reconstructionOf = (metadata: DicomDataset) => { + const planned = plannedUpdate([instanceFor(metadata)]).collection + .reconstruction; + return planned.kind === 'irregular' + ? { kind: planned.kind, reason: planned.reason } + : { kind: planned.kind }; +}; const indexToWorld = (volume: Volume, index: number[]) => [0, 1, 2].map( @@ -43,7 +49,7 @@ describe('enhanced volume Functional Groups', () => { positioned('99.5\\-301.5\\-149'), ]); const volume = allocate(metadata); - expect(volume.spatialMetadata.reconstruction).toEqual({ kind: 'regular' }); + expect(reconstructionOf(metadata)).toEqual({ kind: 'regular' }); expect(volume.spacing).toEqual([0.388672, 0.388672, 10]); expect(indexToWorld(volume, [0, 0, 0])).toEqual([99.5, -301.5, -159]); expect(indexToWorld(volume, [0, 0, 1])).toEqual([99.5, -301.5, -149]); @@ -67,7 +73,7 @@ describe('enhanced volume Functional Groups', () => { ] ); const volume = allocate(metadata); - expect(volume.spatialMetadata.reconstruction).toEqual({ kind: 'regular' }); + expect(reconstructionOf(metadata)).toEqual({ kind: 'regular' }); expect(volume.spacing[2]).toBeCloseTo(1.33, 8); expect(indexToWorld(volume, [0, 0, 1])[0]).toBeCloseTo(-81.8877146, 7); expect(volume.direction[1]).toBeCloseTo(0.9762960207, 8); @@ -133,13 +139,12 @@ describe('enhanced volume Functional Groups', () => { ])( 'keeps %s frames in stored order and reports the reason', (reason, positions) => { - const volume = allocate( - enhanced( - ctShared(), - positions.map((z) => positioned(`0\\0\\${z}`)) - ) + const metadata = enhanced( + ctShared(), + positions.map((z) => positioned(`0\\0\\${z}`)) ); - expect(volume.spatialMetadata.reconstruction).toEqual({ + const volume = allocate(metadata); + expect(reconstructionOf(metadata)).toEqual({ kind: 'irregular', reason, }); @@ -197,7 +202,7 @@ describe('enhanced volume Functional Groups', () => { it('reports shared-plane temporal frames as irregular', () => { const metadata = sharedPlaneTemporal(); - expect(reconstructionOf(metadata)?.kind).toBe('irregular'); + expect(reconstructionOf(metadata).kind).toBe('irregular'); }); it.each([1, -1])( @@ -271,19 +276,11 @@ describe('reconstructed NM spatial volumes', () => { element.tag === tag ? tags({ [tag]: '' }).elements[0] : element ); const volume = allocate(metadata); - const { spatialMetadata } = volume; expect(volume.dimensions).toEqual([2, 2, 3]); - if (tag === '00200032') { - expect(volume.origin).toEqual([0, 0, 0]); - expect(spatialMetadata.notes.join(' ')).toContain('zero origin'); - } else if (tag === '00200037') { + if (tag === '00200032') expect(volume.origin).toEqual([0, 0, 0]); + else if (tag === '00200037') expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); - expect(spatialMetadata.notes.join(' ')).toContain('default axes'); - } else { - const axis = tag === '00280030' ? 0 : 2; - expect(volume.spacing[axis]).toBe(1); - expect(spatialMetadata.axes[axis].status).toBe('fallback'); - } + else expect(volume.spacing[tag === '00280030' ? 0 : 2]).toBe(1); if (tag !== '00180088') expect(volume.spacing[2]).toBe(4.7951998710632); } ); @@ -294,9 +291,6 @@ describe('reconstructed NM spatial volumes', () => { const volume = allocate( nmMetadata({ '00180088': String(sign * 4.7951998710632) }) ); - expect(volume.spatialMetadata.reconstruction).toEqual({ - kind: 'regular', - }); expect(volume.spacing).toEqual([ 4.7951998710632, 4.7951998710632, 4.7951998710632, ]); @@ -316,7 +310,6 @@ describe('reconstructed NM spatial volumes', () => { '00180088': '', }); const volume = allocate(metadata); - expect(volume.spatialMetadata.reconstruction).toEqual({ kind: 'regular' }); expect(volume.origin).toEqual([4, 5, 6]); expect(volume.spacing).toEqual([4.7951998710632, 4.7951998710632, 1]); expect(volume.direction).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); diff --git a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts index 64930112c..0bd76656f 100644 --- a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts +++ b/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts @@ -41,8 +41,7 @@ function layoutOf(sources: VolumeSource[], orientation: number[] | null) { return volumeLayout(sources, orientation, reconstruction); } -const spacingOf = (layout: ReturnType) => - layout.spatialMetadata.axes.map((axis) => axis.value); +const spacingOf = (layout: ReturnType) => layout.spacing; const dimensionsOf = ({ columns, diff --git a/packages/dicom/core/volume/allocateVolume.ts b/packages/dicom/core/volume/allocateVolume.ts index 7f825637e..dc47c429e 100644 --- a/packages/dicom/core/volume/allocateVolume.ts +++ b/packages/dicom/core/volume/allocateVolume.ts @@ -1,6 +1,5 @@ import type { Instance } from '../instance/readInstance'; import type { InstanceCollectionUpdate } from '../collections/instanceRegistry'; -import type { SpatialMetadata } from '../metadata/spatialMetadata'; import type { VolumeBuffer } from './pixelFormat'; import { nativeFramesOverrun } from '../pixels/frameIndex'; import { planVolumeAllocation } from './volumeLayout'; @@ -22,7 +21,6 @@ export type Volume = Readonly<{ /** Row-major 3x3: row direction, column direction, slice direction. */ direction: readonly number[]; spacing: Vector3; - spatialMetadata: SpatialMetadata; /** Allocation warnings as [title, details]. */ warnings: ReadonlyArray; data: VolumeBuffer; @@ -110,8 +108,7 @@ export function allocateVolume( components: samplesPerPixel, origin: (layout.origin ?? [0, 0, 0]) as Triple, direction: layout.direction ?? IDENTITY, - spacing: layout.spatialMetadata.axes.map((axis) => axis.value) as Triple, - spatialMetadata: layout.spatialMetadata, + spacing: layout.spacing as Triple, warnings, data: new layout.bufferType(columns * rows * slices * samplesPerPixel), loaded: new Uint8Array(slices), diff --git a/packages/dicom/core/volume/nmGeometry.ts b/packages/dicom/core/volume/nmGeometry.ts index 1302687d7..9e5e85c3e 100644 --- a/packages/dicom/core/volume/nmGeometry.ts +++ b/packages/dicom/core/volume/nmGeometry.ts @@ -15,10 +15,5 @@ export function nmGeometry(metadata: DicomDataset) { kind: 'regular', sliceSpacing: nm.sliceSpacing ? Math.abs(nm.sliceSpacing) : null, }; - return { - ...geometry, - direction, - reconstruction, - sliceSpacingSource: 'SpacingBetweenSlices', - }; + return { ...geometry, direction, reconstruction }; } diff --git a/packages/dicom/core/volume/ultrasoundSpacing.ts b/packages/dicom/core/volume/ultrasoundSpacing.ts index c7ba9b79f..22e6a007a 100644 --- a/packages/dicom/core/volume/ultrasoundSpacing.ts +++ b/packages/dicom/core/volume/ultrasoundSpacing.ts @@ -1,56 +1,35 @@ import { getDatasetModality } from '../metadata/datasetAccess'; import { readUltrasoundRegions, unitToMm } from '../metadata/ultrasoundRegion'; -import { - physicalSpacing, - type SpatialMetadata, -} from '../metadata/spatialMetadata'; import type { VolumeSource } from './volumeLayout'; const isUsableSpacing = (value: number) => Number.isFinite(value) && value !== 0; -const regionNotes = (count: number) => - count > 1 - ? [ - 'Multiple ultrasound regions are present; only the first region supplies the display spacing.', - ] - : []; - -/** The display spacing is `axes[n].value` of the returned metadata; warnings are [title, details]. */ +/** Display spacing from the first ultrasound region; warnings are [title, details]. */ export function applyUltrasoundSpacing( - spatialMetadata: SpatialMetadata, + spacing: number[], sources: readonly VolumeSource[] -): { spatialMetadata: SpatialMetadata; warnings: Array<[string, string]> } { - const unchanged = { spatialMetadata, warnings: [] }; +): { spacing: number[]; warnings: Array<[string, string]> } { + const unchanged = { spacing, warnings: [] }; if (getDatasetModality(sources[0].dataset) !== 'US') return unchanged; // Ultrasound DICOMs are typically a single multi-frame instance, so the // first region table applies to the whole image. - const regions = readUltrasoundRegions(sources[0].dataset); - if (!regions.region) return unchanged; + const { region } = readUltrasoundRegions(sources[0].dataset); + if (!region) return unchanged; - const { region } = regions; - const notes = [...spatialMetadata.notes, ...regionNotes(regions.regionCount)]; const xFactor = unitToMm(region.physicalUnitsXDirection); const yFactor = unitToMm(region.physicalUnitsYDirection); // All-or-nothing: if either axis lacks a spatial unit (e.g. one axis is // cm and the other is seconds, or unitless) the metadata can't be trusted // as a 2D physical spacing, so leave the default 1mm fallback in place. - if (xFactor === null || yFactor === null) { - notes.push( - 'The first ultrasound region does not declare two spatial axes; its calibration is not applied.' - ); - return { spatialMetadata: { ...spatialMetadata, notes }, warnings: [] }; - } + if (xFactor === null || yFactor === null) return unchanged; const spacingX = region.physicalDeltaX * xFactor; const spacingY = region.physicalDeltaY * yFactor; - if (!isUsableSpacing(spacingX) || !isUsableSpacing(spacingY)) { - notes.push( - 'The first ultrasound region has unusable physical deltas; its calibration is not applied.' - ); + if (!isUsableSpacing(spacingX) || !isUsableSpacing(spacingY)) return { - spatialMetadata: { ...spatialMetadata, notes }, + spacing, warnings: [ [ 'Invalid ultrasound calibration', @@ -58,21 +37,6 @@ export function applyUltrasoundSpacing( ], ], }; - } - notes.push( - 'Ultrasound physical spacing applies within the calibrated region, not necessarily the entire image.' - ); - return { - spatialMetadata: { - ...spatialMetadata, - axes: [ - physicalSpacing(spacingX, 'Ultrasound region (cm converted to mm)'), - physicalSpacing(spacingY, 'Ultrasound region (cm converted to mm)'), - spatialMetadata.axes[2], - ], - notes, - }, - warnings: [], - }; + return { spacing: [spacingX, spacingY, spacing[2]], warnings: [] }; } diff --git a/packages/dicom/core/volume/volumeLayout.ts b/packages/dicom/core/volume/volumeLayout.ts index 5fa01aa87..4c427c449 100644 --- a/packages/dicom/core/volume/volumeLayout.ts +++ b/packages/dicom/core/volume/volumeLayout.ts @@ -4,12 +4,7 @@ import { Tags } from '../metadata/dicomTags'; import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; import type { Reconstruction } from '../collections/reconstructVolume'; import { readDatasetDetails } from '../collections/datasetDetails'; -import { - declaredSpacing, - physicalSpacing, - readPixelSpacing, - type SpatialMetadata, -} from '../metadata/spatialMetadata'; +import { readPixelSpacing, spacingOr1 } from '../metadata/spatialMetadata'; import { getFrameTag } from '../metadata/functionalGroups'; import { frameCount } from '../pixels/pixelDecoder'; import { numberOr } from '../utils'; @@ -29,7 +24,7 @@ const frameGeometry = (sources: readonly VolumeSource[]) => { if (sources.length !== 1) return { frames: null }; const { dataset } = sources[0]; const nm = nmGeometry(dataset); - if (nm) return { frames: nm, sliceSpacingSource: nm.sliceSpacingSource }; + if (nm) return { frames: nm }; return { frames: frameCount(dataset) < 2 @@ -52,14 +47,12 @@ function allocationGeometry( reconstruction: Reconstruction ) { const { dataset } = sources[0]; - const { frames, sliceSpacingSource = 'ImagePositionPatient' } = - frameGeometry(sources); + const { frames } = frameGeometry(sources); const geometry = frames ?? readGeometryFacts(dataset); const effectiveOrientation = orientation ?? geometry.orientation; return { ...geometry, reconstruction: frames?.reconstruction ?? reconstruction, - sliceSpacingSource, direction: allocationDirection(effectiveOrientation, frames?.direction), }; } @@ -75,67 +68,15 @@ function allocationShape(sources: readonly VolumeSource[]) { }; } -function allocationNotes( - sources: readonly VolumeSource[], - geometry: ReturnType +function allocationSpacing( + dataset: DicomDataset, + { reconstruction }: ReturnType ) { - const notes = []; - if (!geometry.position) - notes.push( - 'Patient position is unavailable; the display uses a zero origin.' - ); - if (!geometry.direction) - notes.push( - 'Patient orientation is unavailable; the display uses default axes.' - ); - if ( - sources.length > 1 && - sources.some((source) => - readPixelSpacing(source.dataset).some( - (axis) => axis.status === 'fallback' - ) - ) - ) - notes.push( - 'Some slices lack usable PixelSpacing; the displayed in-plane grid uses the first slice.' - ); - return notes; -} - -function allocationCalibration(metadata: DicomDataset) { - const type = getDatasetTag(metadata, '00280A02')?.trim(); - const description = getDatasetTag(metadata, '00280A04')?.trim(); - return type || description ? { calibration: { type, description } } : {}; -} - -function allocationSpatialMetadata( - sources: readonly VolumeSource[], - geometry: ReturnType -): SpatialMetadata { - const metadata = sources[0].dataset; - const { reconstruction, sliceSpacingSource } = geometry; const sliceSpacing = reconstruction.sliceSpacing ?? 0; const z = isPositiveFiniteNumber(sliceSpacing) - ? physicalSpacing( - sliceSpacing, - sliceSpacingSource, - sliceSpacingSource === 'ImagePositionPatient' ? 'derived' : 'declared' - ) - : declaredSpacing( - getFrameTag(metadata, Tags.SpacingBetweenSlices), - 'SpacingBetweenSlices' - ); - return { - axes: [...readPixelSpacing(metadata), z], - reconstruction: { - kind: reconstruction.kind, - ...(reconstruction.kind === 'irregular' - ? { reason: reconstruction.reason } - : {}), - }, - notes: allocationNotes(sources, geometry), - ...allocationCalibration(metadata), - }; + ? sliceSpacing + : spacingOr1(getFrameTag(dataset, Tags.SpacingBetweenSlices)); + return [...readPixelSpacing(dataset), z]; } /** @@ -155,7 +96,7 @@ export function volumeLayout( ...shape, origin: geometry.position, direction: geometry.direction, - spatialMetadata: allocationSpatialMetadata(sources, geometry), + spacing: allocationSpacing(sources[0].dataset, geometry), bufferType: getVolumeBufferType( sources.flatMap((source) => instancePixelFormats(source.dataset)) ), @@ -169,9 +110,6 @@ export function planVolumeAllocation( reconstruction: Reconstruction ) { const layout = volumeLayout(sources, orientation, reconstruction); - const { spatialMetadata, warnings } = applyUltrasoundSpacing( - layout.spatialMetadata, - sources - ); - return { layout: { ...layout, spatialMetadata }, warnings }; + const { spacing, warnings } = applyUltrasoundSpacing(layout.spacing, sources); + return { layout: { ...layout, spacing }, warnings }; } diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index a24b32855..0c043298d 100644 --- a/src/core/cine/DicomCineImage.ts +++ b/src/core/cine/DicomCineImage.ts @@ -11,11 +11,6 @@ import { BaseProgressiveImage, ProgressiveImageEvents, } from '@/src/core/progressiveImage'; -import { - fallbackSpacing, - physicalSpacing, - type SpatialMetadata, -} from '@/packages/dicom/core/metadata/spatialMetadata'; import { unitToMm } from '@/packages/dicom/core/metadata/ultrasoundRegion'; import type { Instance } from '@/packages/dicom/core/instance/readInstance'; import { abortError } from '@/packages/dicom/core/utils'; @@ -33,53 +28,22 @@ import { decodeNativeFrame, } from './frameCache'; -const REGION_SOURCE = 'Ultrasound region (cm converted to mm)'; -const NO_SPACING = - 'No usable spatial ultrasound region or PixelSpacing is supplied.'; - -function spatialRegionSpacing(r: CineHeader['regions'][number]) { - const sx = unitToMm(r.physicalUnitsXDirection); - const sy = unitToMm(r.physicalUnitsYDirection); - if (sx == null || sy == null) return null; - const { physicalDeltaX: dx, physicalDeltaY: dy } = r; - if (!dx || !dy || !Number.isFinite(dx) || !Number.isFinite(dy)) return null; - return [ - physicalSpacing(Math.abs(dx) * sx, REGION_SOURCE), - physicalSpacing(Math.abs(dy) * sy, REGION_SOURCE), - ] as const; -} - -function pickSpacing(header: CineHeader): SpatialMetadata { - const z = fallbackSpacing( - 'Cine frames share one image plane; this is not a spatial frame step.' - ); - const regionSpacing = header.regions - .map(spatialRegionSpacing) - .find((spacing) => spacing !== null); - if (regionSpacing) - return { - axes: [...regionSpacing, z], - notes: [ - 'Physical spacing applies within the first spatial ultrasound region, not necessarily the entire image.', - ], - }; +function pickPixelSpacing(header: CineHeader) { + for (const r of header.regions) { + const sx = unitToMm(r.physicalUnitsXDirection); + const sy = unitToMm(r.physicalUnitsYDirection); + if (sx == null || sy == null) continue; + const { physicalDeltaX: dx, physicalDeltaY: dy } = r; + if (!dx || !dy || !Number.isFinite(dx) || !Number.isFinite(dy)) continue; + return [Math.abs(dx) * sx, Math.abs(dy) * sy]; + } if (header.pixelSpacing) { const [rowSpacing, columnSpacing] = header.pixelSpacing; - return { - axes: [ - physicalSpacing(columnSpacing, 'PixelSpacing'), - physicalSpacing(rowSpacing, 'PixelSpacing'), - z, - ], - notes: [], - }; + return [columnSpacing, rowSpacing]; } - return { - axes: [fallbackSpacing(NO_SPACING), fallbackSpacing(NO_SPACING), z], - notes: [], - }; + return [1, 1]; } /** Encodes an RGB frame as a PNG data URI, or null without a 2D canvas. */ @@ -140,10 +104,10 @@ export default class DicomCineImage extends BaseProgressiveImage { this.scalarBuffer = new Uint8Array(cols * rows * 3); const imageData = vtkImageData.newInstance(); imageData.setExtent([0, cols - 1, 0, rows - 1, 0, 0]); - this.spatialMetadata.value = pickSpacing(header); - imageData.setSpacing( - this.spatialMetadata.value.axes.map((axis) => axis.value) - ); + // Spacing falls back to 1 when no region declares a spatial unit, so + // rulers report pixels. + const [spacingX, spacingY] = pickPixelSpacing(header); + imageData.setSpacing([spacingX, spacingY, 1]); imageData.setOrigin([0, 0, 0]); imageData.setDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); diff --git a/src/core/progressiveImage.ts b/src/core/progressiveImage.ts index 16140d2fc..a5e945af3 100644 --- a/src/core/progressiveImage.ts +++ b/src/core/progressiveImage.ts @@ -1,5 +1,4 @@ -import { computed, effectScope, ref, Ref, shallowRef } from 'vue'; -import type { SpatialMetadata } from '@/packages/dicom/core/metadata/spatialMetadata'; +import { computed, effectScope, ref, Ref } from 'vue'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { ImageMetadata } from '@/src/types/image'; import { onVTKEvent } from '@/src/composables/onVTKEvent'; @@ -98,7 +97,6 @@ export function reactiveVtkImageMetadata( } export abstract class BaseProgressiveImage implements ProgressiveImage { - protected spatialMetadata = shallowRef(); public loading: Ref; public loaded: Ref; public status: Ref; @@ -120,12 +118,7 @@ export abstract class BaseProgressiveImage implements ProgressiveImage { this.vtkImageData, this.name ); - this.imageMetadata = computed(() => ({ - ...imageMetadata.value, - ...(this.spatialMetadata.value - ? { spatialMetadata: this.spatialMetadata.value } - : {}), - })); + this.imageMetadata = imageMetadata; this.cleanupListeners = () => { stop(); diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 09e536f42..65f355a79 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -162,7 +162,6 @@ export default class DicomVolumeImage extends BaseProgressiveImage { /** Shows a newly allocated volume; slices it already holds stay loaded. */ setVolume(volume: Volume) { this.replaceContent({ kind: 'volume', volume, failed: new Set() }); - this.spatialMetadata.value = volume.spatialMetadata; this.replaceImage(toVtkImageData(volume)); this.settleThumbnail?.(); } diff --git a/src/types/image.ts b/src/types/image.ts index 86d92c12f..32275068b 100644 --- a/src/types/image.ts +++ b/src/types/image.ts @@ -1,7 +1,6 @@ import { mat3, mat4, vec3 } from 'gl-matrix'; import type { Bounds } from '@kitware/vtk.js/types'; import { LPSDirections } from './lps'; -import type { SpatialMetadata } from '@/packages/dicom/core/metadata/spatialMetadata'; export type ImageMetadata = { name: string; @@ -13,6 +12,4 @@ export type ImageMetadata = { worldBounds: Bounds; worldToIndex: mat4; indexToWorld: mat4; - /** Absent when the reader has not reported how its spacing was established. */ - spatialMetadata?: SpatialMetadata; }; diff --git a/tests/fixtures/dicom-pages/corpus.ts b/tests/fixtures/dicom-pages/corpus.ts index 2117dc2b3..49c0c960d 100644 --- a/tests/fixtures/dicom-pages/corpus.ts +++ b/tests/fixtures/dicom-pages/corpus.ts @@ -14,12 +14,9 @@ async function run() { ? new File([await (await fetch(url)).blob()], 'volume.dcm') : url; const instance = await runtime.readInstance(sourceOf(input), never); - const { volume, image } = await loadInstanceVolume(instance); + const { update, image } = await loadInstanceVolume(instance); await describeVolume(image, report); - report( - 'reconstruction', - volume.spatialMetadata.reconstruction?.kind ?? 'unreported' - ); + report('reconstruction', update.collection.reconstruction.kind); report('status', 'complete'); } diff --git a/tests/fixtures/dicom-pages/loadVolume.ts b/tests/fixtures/dicom-pages/loadVolume.ts index 1b5cdf4af..5f38ec2c6 100644 --- a/tests/fixtures/dicom-pages/loadVolume.ts +++ b/tests/fixtures/dicom-pages/loadVolume.ts @@ -32,7 +32,7 @@ export async function loadCollection( return { volume, image }; } -export function loadInstanceVolume(instance: Instance) { +export async function loadInstanceVolume(instance: Instance) { const [update] = registerInstances(emptyRegistry, [instance]).updates; - return loadCollection(update); + return { update, ...(await loadCollection(update)) }; } From 49b1c17265cee96cba7fbe85c192e45b27472af8 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Fri, 20 Nov 2026 10:27:23 -0500 Subject: [PATCH 25/32] refactor(dicom): move the module to src/dicom The module is VolView source with no build of its own, so it lives under src and drops the path entries that existed only for its separate directory. --- .github/workflows/checks.yml | 2 +- eslint.config.js | 8 +++---- package.json | 10 +++------ scripts/checks/complexity.mjs | 2 +- ...tientStudyVolumeBrowser.thumbnails.spec.ts | 8 +++---- src/components/__tests__/PlayControls.spec.ts | 2 +- .../vtk/VtkBaseVolumeRepresentation.vue | 2 +- src/core/cine/DicomCineImage.ts | 6 +++--- .../cine/__tests__/DicomCineImage.spec.ts | 11 ++++------ src/core/cine/__tests__/cineFixtures.ts | 8 +++---- src/core/cine/__tests__/cineInstance.spec.ts | 6 +++--- src/core/cine/cineInstance.ts | 20 +++++++++--------- .../__tests__/dicomVolumeImage.spec.ts | 21 ++++++++----------- .../dicom/__tests__/octMetadata.spec.ts | 8 +++---- src/core/streaming/dicom/octMetadata.ts | 10 ++++----- src/core/streaming/dicom/octMetadataTags.ts | 4 ++-- src/core/streaming/dicom/seriesGeometry.ts | 2 +- src/core/streaming/dicomVolumeImage.ts | 18 ++++++++-------- {packages => src}/dicom/README.md | 0 .../__tests__/assignCollectionIds.spec.ts | 0 .../__tests__/idcSeriesFixtures.ts | 0 .../__tests__/instanceFacts.spec.ts | 0 .../__tests__/instanceFactsFixture.ts | 0 .../__tests__/instanceRegistry.spec.ts | 0 .../__tests__/multiframeGeometry.spec.ts | 0 .../__tests__/planDicomCollections.spec.ts | 0 .../__tests__/reconstructVolume.spec.ts | 0 .../collections/__tests__/sliceFixture.ts | 0 .../splitOverlappingAcquisitions.spec.ts | 0 .../core/collections/assignCollectionIds.ts | 0 .../dicom/core/collections/datasetDetails.ts | 0 .../dicom/core/collections/groupBy.ts | 0 .../dicom/core/collections/instanceFacts.ts | 0 .../dicom/core/collections/instanceKey.ts | 0 .../core/collections/instanceRegistry.ts | 0 .../core/collections/multiframeGeometry.ts | 0 .../dicom/core/collections/orientation.ts | 0 .../core/collections/planDicomCollections.ts | 0 .../core/collections/reconstructVolume.ts | 0 .../splitOverlappingAcquisitions.ts | 0 .../core/header/__tests__/byteDeque.spec.ts | 0 .../__tests__/dicomHeaderEncodings.spec.ts | 0 .../__tests__/streamingByteReader.spec.ts | 0 .../dicom/core/header/byteDeque.ts | 0 .../dicom/core/header/dicomParser.ts | 0 .../dicom/core/header/readDicomHeader.ts | 0 .../dicom/core/header/streamingByteReader.ts | 0 .../__tests__/readInstanceSources.spec.ts | 0 .../dicom/core/instance/readInstance.ts | 0 .../metadata/__tests__/dcmjsParser.spec.ts | 0 .../__tests__/dicomCharacterSets.spec.ts | 0 .../metadata/__tests__/dicomDataset.spec.ts | 0 .../metadata/__tests__/dicomLayout.spec.ts | 0 .../__tests__/modalityRescale.spec.ts | 0 .../__tests__/spatialMetadata.spec.ts | 0 .../__tests__/ultrasoundRegion.spec.ts | 0 .../dicom/core/metadata/datasetAccess.ts | 0 .../dicom/core/metadata/dcmjs.d.ts | 0 .../dicom/core/metadata/dcmjsParser.ts | 0 .../dicom/core/metadata/dicomCharacterSet.ts | 0 .../dicom/core/metadata/dicomDataset.ts | 0 .../dicom/core/metadata/dicomLayout.ts | 0 .../dicom/core/metadata/dicomTags.ts | 0 .../dicom/core/metadata/functionalGroups.ts | 0 .../dicom/core/metadata/modalityRescale.ts | 0 .../dicom/core/metadata/nmReconstruction.ts | 0 .../core/metadata/readDicomDataset.worker.ts | 0 .../dicom/core/metadata/spatialMetadata.ts | 0 .../dicom/core/metadata/ultrasoundRegion.ts | 0 .../pixels/__tests__/decoderTable.spec.ts | 0 .../__tests__/encapsulatedFrames.spec.ts | 0 .../core/pixels/__tests__/frameIndex.spec.ts | 0 .../core/pixels/__tests__/nativeFrame.spec.ts | 0 .../core/pixels/__tests__/pixelFixture.ts | 0 .../dicom/core/pixels/decoderTable.ts | 0 .../dicom/core/pixels/encapsulatedFrames.ts | 0 .../dicom/core/pixels/frameIndex.ts | 0 .../dicom/core/pixels/nativeFrame.ts | 0 .../dicom/core/pixels/pixelDecoder.ts | 0 .../runtime/__tests__/dicomRuntime.spec.ts | 0 .../runtime/__tests__/metadataReader.spec.ts | 0 .../runtime/__tests__/requestPool.spec.ts | 0 .../dicom/core/runtime/createDicomRuntime.ts | 0 .../dicom/core/runtime/gdcmDecoder.ts | 0 .../dicom/core/runtime/metadataReader.ts | 0 .../dicom/core/runtime/requestPool.ts | 0 .../core/source/__tests__/byteSource.spec.ts | 0 .../__tests__/parseContentRangeHeader.spec.ts | 0 .../dicom/core/source/byteSource.ts | 0 .../core/source/parseContentRangeHeader.ts | 0 {packages => src}/dicom/core/utils.ts | 0 .../volume/__tests__/allocateVolume.spec.ts | 0 .../core/volume/__tests__/enhancedFixture.ts | 0 .../volume/__tests__/frameGeometry.spec.ts | 0 .../core/volume/__tests__/loadFrames.spec.ts | 0 .../core/volume/__tests__/loadVolume.spec.ts | 0 .../core/volume/__tests__/pixelFormat.spec.ts | 0 .../volume/__tests__/pixelValidation.spec.ts | 0 .../core/volume/__tests__/slotOrder.spec.ts | 0 .../core/volume/__tests__/volumeFixture.ts | 0 .../volume/__tests__/volumeLayout.spec.ts | 0 .../dicom/core/volume/allocateVolume.ts | 0 .../dicom/core/volume/loadVolume.ts | 0 .../dicom/core/volume/nmGeometry.ts | 0 .../dicom/core/volume/pixelFormat.ts | 0 .../dicom/core/volume/pixelValidation.ts | 0 .../dicom/core/volume/slotOrder.ts | 0 .../dicom/core/volume/ultrasoundSpacing.ts | 0 .../dicom/core/volume/volumeLayout.ts | 0 .../dicom/vtk/__tests__/thumbnail.spec.ts | 0 .../dicom/vtk/__tests__/volumeImage.spec.ts | 0 {packages => src}/dicom/vtk/thumbnail.ts | 0 {packages => src}/dicom/vtk/volumeImage.ts | 0 src/enface/__tests__/availability.spec.ts | 2 +- src/enface/__tests__/calibration.spec.ts | 4 ++-- src/enface/__tests__/dicomMetadataFixture.ts | 2 +- src/enface/__tests__/inputCalibration.spec.ts | 2 +- .../__tests__/occupiedDepthSupport.spec.ts | 2 +- src/enface/__tests__/seriesGeometry.spec.ts | 4 ++-- src/enface/availability.ts | 4 ++-- src/enface/occupiedDepthSupport.ts | 6 +++--- src/io/import/__tests__/dataSource.spec.ts | 2 +- .../importDicomInstanceSources.spec.ts | 2 +- src/io/import/dataSource.ts | 2 +- src/io/import/importDataSources.ts | 4 ++-- .../processors/__tests__/handleDicom.spec.ts | 10 ++++----- src/io/import/processors/handleDicom.ts | 8 +++---- src/io/import/processors/updateUriType.ts | 4 ++-- src/io/magic.ts | 2 +- .../__tests__/artifactParentRestore.spec.ts | 8 +++---- .../datasets-dicom-acquisition-split.spec.ts | 2 +- .../__tests__/datasets-dicom-cine.spec.ts | 2 +- .../__tests__/datasets-dicom-geometry.spec.ts | 2 +- .../datasets-dicom-transaction.spec.ts | 2 +- src/store/__tests__/dicomImportFixtures.ts | 15 ++++++------- src/store/__tests__/dicomTagFixtures.ts | 2 +- .../__tests__/duplicateDatasetSave.spec.ts | 2 +- src/store/datasets-dicom.ts | 18 ++++++++-------- src/store/datasets.ts | 8 +++---- src/store/dicom-runtime.ts | 2 +- src/store/dicom-web/dicom-web-store.ts | 2 +- src/utils/__tests__/dicomWindowRange.spec.ts | 2 +- src/utils/dicom/windowMetadata.ts | 6 +++--- src/utils/dicomWindowRange.ts | 2 +- tests/byteSourceFixtures.ts | 2 +- tests/dicomDataset.ts | 9 +++----- tests/dicomSourceFixtures.ts | 2 +- tests/dicomVolumeFixtures.ts | 8 +++---- tests/fixtures/dicom-pages/composition.ts | 6 +++--- tests/fixtures/dicom-pages/core.ts | 2 +- tests/fixtures/dicom-pages/loadVolume.ts | 15 ++++++------- tests/fixtures/dicom-pages/parity.ts | 12 +++++------ tests/fixtures/dicom-pages/shared.ts | 8 +++---- tests/unit/octFixture.ts | 12 +++++------ tsconfig.json | 3 +-- 155 files changed, 171 insertions(+), 191 deletions(-) rename {packages => src}/dicom/README.md (100%) rename {packages => src}/dicom/core/collections/__tests__/assignCollectionIds.spec.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/idcSeriesFixtures.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/instanceFacts.spec.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/instanceFactsFixture.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/instanceRegistry.spec.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/multiframeGeometry.spec.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/planDicomCollections.spec.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/reconstructVolume.spec.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/sliceFixture.ts (100%) rename {packages => src}/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts (100%) rename {packages => src}/dicom/core/collections/assignCollectionIds.ts (100%) rename {packages => src}/dicom/core/collections/datasetDetails.ts (100%) rename {packages => src}/dicom/core/collections/groupBy.ts (100%) rename {packages => src}/dicom/core/collections/instanceFacts.ts (100%) rename {packages => src}/dicom/core/collections/instanceKey.ts (100%) rename {packages => src}/dicom/core/collections/instanceRegistry.ts (100%) rename {packages => src}/dicom/core/collections/multiframeGeometry.ts (100%) rename {packages => src}/dicom/core/collections/orientation.ts (100%) rename {packages => src}/dicom/core/collections/planDicomCollections.ts (100%) rename {packages => src}/dicom/core/collections/reconstructVolume.ts (100%) rename {packages => src}/dicom/core/collections/splitOverlappingAcquisitions.ts (100%) rename {packages => src}/dicom/core/header/__tests__/byteDeque.spec.ts (100%) rename {packages => src}/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts (100%) rename {packages => src}/dicom/core/header/__tests__/streamingByteReader.spec.ts (100%) rename {packages => src}/dicom/core/header/byteDeque.ts (100%) rename {packages => src}/dicom/core/header/dicomParser.ts (100%) rename {packages => src}/dicom/core/header/readDicomHeader.ts (100%) rename {packages => src}/dicom/core/header/streamingByteReader.ts (100%) rename {packages => src}/dicom/core/instance/__tests__/readInstanceSources.spec.ts (100%) rename {packages => src}/dicom/core/instance/readInstance.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/dcmjsParser.spec.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/dicomDataset.spec.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/dicomLayout.spec.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/modalityRescale.spec.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/spatialMetadata.spec.ts (100%) rename {packages => src}/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts (100%) rename {packages => src}/dicom/core/metadata/datasetAccess.ts (100%) rename {packages => src}/dicom/core/metadata/dcmjs.d.ts (100%) rename {packages => src}/dicom/core/metadata/dcmjsParser.ts (100%) rename {packages => src}/dicom/core/metadata/dicomCharacterSet.ts (100%) rename {packages => src}/dicom/core/metadata/dicomDataset.ts (100%) rename {packages => src}/dicom/core/metadata/dicomLayout.ts (100%) rename {packages => src}/dicom/core/metadata/dicomTags.ts (100%) rename {packages => src}/dicom/core/metadata/functionalGroups.ts (100%) rename {packages => src}/dicom/core/metadata/modalityRescale.ts (100%) rename {packages => src}/dicom/core/metadata/nmReconstruction.ts (100%) rename {packages => src}/dicom/core/metadata/readDicomDataset.worker.ts (100%) rename {packages => src}/dicom/core/metadata/spatialMetadata.ts (100%) rename {packages => src}/dicom/core/metadata/ultrasoundRegion.ts (100%) rename {packages => src}/dicom/core/pixels/__tests__/decoderTable.spec.ts (100%) rename {packages => src}/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts (100%) rename {packages => src}/dicom/core/pixels/__tests__/frameIndex.spec.ts (100%) rename {packages => src}/dicom/core/pixels/__tests__/nativeFrame.spec.ts (100%) rename {packages => src}/dicom/core/pixels/__tests__/pixelFixture.ts (100%) rename {packages => src}/dicom/core/pixels/decoderTable.ts (100%) rename {packages => src}/dicom/core/pixels/encapsulatedFrames.ts (100%) rename {packages => src}/dicom/core/pixels/frameIndex.ts (100%) rename {packages => src}/dicom/core/pixels/nativeFrame.ts (100%) rename {packages => src}/dicom/core/pixels/pixelDecoder.ts (100%) rename {packages => src}/dicom/core/runtime/__tests__/dicomRuntime.spec.ts (100%) rename {packages => src}/dicom/core/runtime/__tests__/metadataReader.spec.ts (100%) rename {packages => src}/dicom/core/runtime/__tests__/requestPool.spec.ts (100%) rename {packages => src}/dicom/core/runtime/createDicomRuntime.ts (100%) rename {packages => src}/dicom/core/runtime/gdcmDecoder.ts (100%) rename {packages => src}/dicom/core/runtime/metadataReader.ts (100%) rename {packages => src}/dicom/core/runtime/requestPool.ts (100%) rename {packages => src}/dicom/core/source/__tests__/byteSource.spec.ts (100%) rename {packages => src}/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts (100%) rename {packages => src}/dicom/core/source/byteSource.ts (100%) rename {packages => src}/dicom/core/source/parseContentRangeHeader.ts (100%) rename {packages => src}/dicom/core/utils.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/allocateVolume.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/enhancedFixture.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/frameGeometry.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/loadFrames.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/loadVolume.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/pixelFormat.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/pixelValidation.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/slotOrder.spec.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/volumeFixture.ts (100%) rename {packages => src}/dicom/core/volume/__tests__/volumeLayout.spec.ts (100%) rename {packages => src}/dicom/core/volume/allocateVolume.ts (100%) rename {packages => src}/dicom/core/volume/loadVolume.ts (100%) rename {packages => src}/dicom/core/volume/nmGeometry.ts (100%) rename {packages => src}/dicom/core/volume/pixelFormat.ts (100%) rename {packages => src}/dicom/core/volume/pixelValidation.ts (100%) rename {packages => src}/dicom/core/volume/slotOrder.ts (100%) rename {packages => src}/dicom/core/volume/ultrasoundSpacing.ts (100%) rename {packages => src}/dicom/core/volume/volumeLayout.ts (100%) rename {packages => src}/dicom/vtk/__tests__/thumbnail.spec.ts (100%) rename {packages => src}/dicom/vtk/__tests__/volumeImage.spec.ts (100%) rename {packages => src}/dicom/vtk/thumbnail.ts (100%) rename {packages => src}/dicom/vtk/volumeImage.ts (100%) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 88571e12c..07799f786 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -18,7 +18,7 @@ jobs: cache: npm - run: npm ci - name: Enforce code style - run: npx prettier --list-different "src/**/*.[jt]s" "tests/**/*.[jt]s" "src/**/*.vue" "packages/dicom/**/*.{ts,md}" + run: npx prettier --list-different "src/**/*.[jt]s" "tests/**/*.[jt]s" "src/**/*.vue" - name: Lint run: npm run lint - name: Quality ratchets diff --git a/eslint.config.js b/eslint.config.js index 79b63a2b3..ca3dbe9d5 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -291,7 +291,7 @@ export default tseslint.config( }, }, { - files: ['src/vtk/**/*.{js,ts}', 'packages/dicom/vtk/**/*.{js,ts}'], + files: ['src/vtk/**/*.{js,ts}', 'src/dicom/vtk/**/*.{js,ts}'], rules: { 'no-param-reassign': [ 'error', @@ -377,7 +377,7 @@ export default tseslint.config( // level because the ratchet only fails a file whose debt grows, so existing // files stay over these numbers without failing `npm run lint`. { - files: ['src/**/*.{js,ts,vue}', 'packages/dicom/**/*.{js,ts}'], + files: ['src/**/*.{js,ts,vue}'], ignores: [ '**/__tests__/**', 'src/**/*.{spec,test}.{js,ts}', @@ -397,7 +397,7 @@ export default tseslint.config( // ESLint matches specifiers, not resolved paths. Core and vtk files sit at // most one directory deep, so climbing two levels always leaves them. { - files: ['packages/dicom/core/**/*.{js,ts}'], + files: ['src/dicom/core/**/*.{js,ts}'], ignores: ['**/__tests__/**'], rules: { 'no-restricted-imports': [ @@ -416,7 +416,7 @@ export default tseslint.config( }, }, { - files: ['packages/dicom/vtk/**/*.{js,ts}'], + files: ['src/dicom/vtk/**/*.{js,ts}'], ignores: ['**/__tests__/**'], rules: { 'no-restricted-imports': [ diff --git a/package.json b/package.json index 9a225bec0..d6d5ad55b 100644 --- a/package.json +++ b/package.json @@ -7,11 +7,7 @@ "files": [ "dist", "src", - "backend-contract", - "packages/dicom/core/**/*.ts", - "packages/dicom/vtk/**/*.ts", - "packages/dicom/README.md", - "!packages/dicom/**/__tests__/**" + "backend-contract" ], "scripts": { "prepare": "node scripts/apply-patches.mjs", @@ -26,12 +22,12 @@ "test:e2e:chrome": "cross-env VITE_SHOW_SAMPLE_DATA=true npm run build && cross-env HEADED=0 wdio run ./wdio.chrome.conf.ts", "test:e2e:chrome:skip-build": "cross-env HEADED=0 wdio run ./wdio.chrome.conf.ts", "test:e2e:dev": "cross-env HEADED=0 VITE_SHOW_SAMPLE_DATA=true concurrently -P \"npm run dev\" \"wdio run ./wdio.dev.conf.ts --watch {@}\"", - "lint": "vue-tsc --noEmit && eslint \"src/**/*.{js,ts,vue}\" \"tests/**/*.{js,ts,mjs}\" \"scripts/**/*.mjs\" \"packages/dicom/**/*.ts\"", + "lint": "vue-tsc --noEmit && eslint \"src/**/*.{js,ts,vue}\" \"tests/**/*.{js,ts,mjs}\" \"scripts/**/*.mjs\"", "build:all": "npm run build:resample && npm run build", "build:resample": "itk-wasm -s src/io/resample/ build ", "build:resample:debug": "itk-wasm -s src/io/resample/ build -- -DCMAKE_BUILD_TYPE=Debug", "build:watch": "npm run build -- --watch", - "prettify": "prettier --write src tests packages/dicom", + "prettify": "prettier --write src tests", "docs:dev": "vitepress dev docs", "docs:build": "vitepress build docs", "docs:preview": "vitepress preview docs" diff --git a/scripts/checks/complexity.mjs b/scripts/checks/complexity.mjs index 758e00cad..977054074 100755 --- a/scripts/checks/complexity.mjs +++ b/scripts/checks/complexity.mjs @@ -11,7 +11,7 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import { git, materialize, stagedContext } from './git.mjs'; import { limits as LIMITS } from './config.mjs'; -const SOURCE = /^(src|packages\/dicom)\/.*\.(ts|js|vue)$/; +const SOURCE = /^src\/.*\.(ts|js|vue)$/; const EXCLUDED = /(__tests__|\.(spec|test)\.|\.d\.ts$|emscripten-build)/; const { base, baseRef, changed: entries, worktree } = stagedContext(); diff --git a/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts index 17567adf0..3a9bffa0c 100644 --- a/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts +++ b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts @@ -17,10 +17,10 @@ import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import { allocateVolume, type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import type { DecodedPixels } from '@/packages/dicom/core/pixels/pixelDecoder'; +} from '@/src/dicom/core/volume/allocateVolume'; +import { createDicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; +import type { DecodedPixels } from '@/src/dicom/core/pixels/pixelDecoder'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { LoadedVtkImage } from '@/src/core/progressiveImage'; import { useDICOMStore } from '@/src/store/datasets-dicom'; diff --git a/src/components/__tests__/PlayControls.spec.ts b/src/components/__tests__/PlayControls.spec.ts index 7fd4c8f68..e32123b39 100644 --- a/src/components/__tests__/PlayControls.spec.ts +++ b/src/components/__tests__/PlayControls.spec.ts @@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { ComponentPublicInstance, nextTick } from 'vue'; import PlayControls from '@/src/components/PlayControls.vue'; import { seatCineImage } from '@/src/core/cine/__tests__/cineFixtures'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; type PlayControlsProps = { viewId: string; imageId: string | null }; type PlayControlsWrapper = VueWrapper< diff --git a/src/components/vtk/VtkBaseVolumeRepresentation.vue b/src/components/vtk/VtkBaseVolumeRepresentation.vue index 2b9ff899b..1f285020c 100644 --- a/src/components/vtk/VtkBaseVolumeRepresentation.vue +++ b/src/components/vtk/VtkBaseVolumeRepresentation.vue @@ -38,7 +38,7 @@ import { useCroppingEffect } from '@/src/composables/useCroppingEffect'; import { useCropStore } from '@/src/store/tools/crop'; import { useEventListener } from '@vueuse/core'; import type DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; -import type { Extent } from '@/packages/dicom/core/volume/loadVolume'; +import type { Extent } from '@/src/dicom/core/volume/loadVolume'; interface Props { viewId: string; diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index 0c043298d..6cd26946a 100644 --- a/src/core/cine/DicomCineImage.ts +++ b/src/core/cine/DicomCineImage.ts @@ -11,9 +11,9 @@ import { BaseProgressiveImage, ProgressiveImageEvents, } from '@/src/core/progressiveImage'; -import { unitToMm } from '@/packages/dicom/core/metadata/ultrasoundRegion'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { abortError } from '@/packages/dicom/core/utils'; +import { unitToMm } from '@/src/dicom/core/metadata/ultrasoundRegion'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; +import { abortError } from '@/src/dicom/core/utils'; import { type CineHeader, isNativeTransferSyntax, diff --git a/src/core/cine/__tests__/DicomCineImage.spec.ts b/src/core/cine/__tests__/DicomCineImage.spec.ts index 785148eb9..5115adf83 100644 --- a/src/core/cine/__tests__/DicomCineImage.spec.ts +++ b/src/core/cine/__tests__/DicomCineImage.spec.ts @@ -1,11 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { - fromBlob, - type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; -import { readInstance } from '@/packages/dicom/core/instance/readInstance'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { fromBlob, type ByteSource } from '@/src/dicom/core/source/byteSource'; +import { readInstance } from '@/src/dicom/core/instance/readInstance'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; import { buildSyntheticCineDicom } from '@/tests/specs/syntheticDicom'; import { datasetFromTags } from '@/tests/dicomDataset'; import DicomCineImage from '../DicomCineImage'; diff --git a/src/core/cine/__tests__/cineFixtures.ts b/src/core/cine/__tests__/cineFixtures.ts index 2a6614c98..fd1456e8d 100644 --- a/src/core/cine/__tests__/cineFixtures.ts +++ b/src/core/cine/__tests__/cineFixtures.ts @@ -1,11 +1,11 @@ import { datasetFromTags } from '@/tests/dicomDataset'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; import { SOP_CLASS_ULTRASOUND_MULTIFRAME, Tags, -} from '@/packages/dicom/core/metadata/dicomTags'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/metadata/dicomTags'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { useImageCacheStore } from '@/src/store/image-cache'; import { seatVolume } from '@/src/store/__tests__/datasetFixtures'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; diff --git a/src/core/cine/__tests__/cineInstance.spec.ts b/src/core/cine/__tests__/cineInstance.spec.ts index 3faa2d457..ebb79852c 100644 --- a/src/core/cine/__tests__/cineInstance.spec.ts +++ b/src/core/cine/__tests__/cineInstance.spec.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import { readInstance } from '@/packages/dicom/core/instance/readInstance'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; +import { readInstance } from '@/src/dicom/core/instance/readInstance'; import { SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, Tags, -} from '@/packages/dicom/core/metadata/dicomTags'; +} from '@/src/dicom/core/metadata/dicomTags'; import { buildSyntheticCineDicom, rawElement, diff --git a/src/core/cine/cineInstance.ts b/src/core/cine/cineInstance.ts index a70219d25..abe86f7fa 100644 --- a/src/core/cine/cineInstance.ts +++ b/src/core/cine/cineInstance.ts @@ -1,19 +1,19 @@ import { EXPLICIT_VR_LITTLE_ENDIAN, IMPLICIT_VR_LITTLE_ENDIAN, -} from '@/packages/dicom/core/metadata/dicomLayout'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { indexFrames } from '@/packages/dicom/core/pixels/frameIndex'; +} from '@/src/dicom/core/metadata/dicomLayout'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import { indexFrames } from '@/src/dicom/core/pixels/frameIndex'; import { isUltrasoundMultiframeSopClass, Tags, -} from '@/packages/dicom/core/metadata/dicomTags'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; -import { splitEncapsulatedFrames } from '@/packages/dicom/core/pixels/encapsulatedFrames'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; -import { ultrasoundRegionsOf } from '@/packages/dicom/core/metadata/ultrasoundRegion'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/metadata/dicomTags'; +import { readBytes } from '@/src/dicom/core/source/byteSource'; +import { splitEncapsulatedFrames } from '@/src/dicom/core/pixels/encapsulatedFrames'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; +import { ultrasoundRegionsOf } from '@/src/dicom/core/metadata/ultrasoundRegion'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; const JPEG_BASELINE = '1.2.840.10008.1.2.4.50'; diff --git a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts index 4d8df8e3f..ab81a5f72 100644 --- a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts +++ b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts @@ -4,28 +4,25 @@ import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; import { allocateVolume, type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; +} from '@/src/dicom/core/volume/allocateVolume'; import { createDicomRuntime, type DicomRuntime, -} from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { - fromBlob, - type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; +} from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, type ByteSource } from '@/src/dicom/core/source/byteSource'; import { readInstance, type Instance, -} from '@/packages/dicom/core/instance/readInstance'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +} from '@/src/dicom/core/instance/readInstance'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import type { DecodedPixels, WholeInstanceDecode, -} from '@/packages/dicom/core/pixels/pixelDecoder'; -import type { Extent } from '@/packages/dicom/core/volume/loadVolume'; +} from '@/src/dicom/core/pixels/pixelDecoder'; +import type { Extent } from '@/src/dicom/core/volume/loadVolume'; import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; -import { sliceThumbnail } from '@/packages/dicom/vtk/volumeImage'; -import type { ThumbnailSlice } from '@/packages/dicom/vtk/thumbnail'; +import { sliceThumbnail } from '@/src/dicom/vtk/volumeImage'; +import type { ThumbnailSlice } from '@/src/dicom/vtk/thumbnail'; import { defer } from '@/src/utils'; import { nativePixelDicom } from '@/tests/nativePixelDicom'; import DicomVolumeImage, { diff --git a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts index 05e8a3e90..222cc95ff 100644 --- a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts +++ b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts @@ -1,9 +1,9 @@ import { deflateRawSync } from 'node:zlib'; import { describe, expect, it, vi } from 'vitest'; -import { fromBlob, fromUrl } from '@/packages/dicom/core/source/byteSource'; -import { readDicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import { readInstance } from '@/packages/dicom/core/instance/readInstance'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; +import { readDicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import { readInstance } from '@/src/dicom/core/instance/readInstance'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { enFaceTags } from '@/src/core/streaming/dicom/octMetadata'; import { trackedSource } from '@/tests/byteSourceFixtures'; diff --git a/src/core/streaming/dicom/octMetadata.ts b/src/core/streaming/dicom/octMetadata.ts index a1bf53da9..e93f70c67 100644 --- a/src/core/streaming/dicom/octMetadata.ts +++ b/src/core/streaming/dicom/octMetadata.ts @@ -1,8 +1,8 @@ -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { sequenceItems } from '@/packages/dicom/core/metadata/functionalGroups'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import { sequenceItems } from '@/src/dicom/core/metadata/functionalGroups'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; import { areEquals } from '@kitware/vtk.js/Common/Core/Math'; import { frameGridGeometry, diff --git a/src/core/streaming/dicom/octMetadataTags.ts b/src/core/streaming/dicom/octMetadataTags.ts index fe093f624..f287d4ed1 100644 --- a/src/core/streaming/dicom/octMetadataTags.ts +++ b/src/core/streaming/dicom/octMetadataTags.ts @@ -1,5 +1,5 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; export const OPHTHALMIC_TOMOGRAPHY_SOP = '1.2.840.10008.5.1.4.1.1.77.1.5.4'; export const OPHTHALMIC_BSCAN_ANALYSIS_SOP = '1.2.840.10008.5.1.4.1.1.77.1.5.8'; diff --git a/src/core/streaming/dicom/seriesGeometry.ts b/src/core/streaming/dicom/seriesGeometry.ts index e061510fc..e851c23f2 100644 --- a/src/core/streaming/dicom/seriesGeometry.ts +++ b/src/core/streaming/dicom/seriesGeometry.ts @@ -1,5 +1,5 @@ import { areEquals } from '@kitware/vtk.js/Common/Core/Math'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { frameGridGeometry, imageDirection, diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts index 65f355a79..f5880974f 100644 --- a/src/core/streaming/dicomVolumeImage.ts +++ b/src/core/streaming/dicomVolumeImage.ts @@ -2,26 +2,26 @@ import { computed } from 'vue'; import mitt from 'mitt'; import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import type { JsonCompatible } from '@itk-wasm/image-io'; -import { getDatasetModality } from '@/packages/dicom/core/metadata/datasetAccess'; +import { getDatasetModality } from '@/src/dicom/core/metadata/datasetAccess'; import { loadVolume, middleSlot, type Extent, type VolumeUpdate, -} from '@/packages/dicom/core/volume/loadVolume'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; -import type { DicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import type { Volume } from '@/packages/dicom/core/volume/allocateVolume'; +} from '@/src/dicom/core/volume/loadVolume'; +import { readBytes } from '@/src/dicom/core/source/byteSource'; +import type { DicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; +import type { Volume } from '@/src/dicom/core/volume/allocateVolume'; import { applyVolumeUpdate, sliceThumbnail, toVtkImageData, -} from '@/packages/dicom/vtk/volumeImage'; +} from '@/src/dicom/vtk/volumeImage'; import { encodeThumbnailToUri, type ThumbnailSlice, -} from '@/packages/dicom/vtk/thumbnail'; +} from '@/src/dicom/vtk/thumbnail'; import { BaseProgressiveImage, type ProgressiveImageEvents, @@ -33,7 +33,7 @@ import { import { convertItkToVtkImage } from '@/src/io/convertItkToVtkImage'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; import { ensureError } from '@/src/utils'; -import { abortError } from '@/packages/dicom/core/utils'; +import { abortError } from '@/src/dicom/core/utils'; type DicomVolumeImageEvents = ProgressiveImageEvents & { /** A decoded region of the current image, as an inclusive extent. */ diff --git a/packages/dicom/README.md b/src/dicom/README.md similarity index 100% rename from packages/dicom/README.md rename to src/dicom/README.md diff --git a/packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts b/src/dicom/core/collections/__tests__/assignCollectionIds.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/assignCollectionIds.spec.ts rename to src/dicom/core/collections/__tests__/assignCollectionIds.spec.ts diff --git a/packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts b/src/dicom/core/collections/__tests__/idcSeriesFixtures.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/idcSeriesFixtures.ts rename to src/dicom/core/collections/__tests__/idcSeriesFixtures.ts diff --git a/packages/dicom/core/collections/__tests__/instanceFacts.spec.ts b/src/dicom/core/collections/__tests__/instanceFacts.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/instanceFacts.spec.ts rename to src/dicom/core/collections/__tests__/instanceFacts.spec.ts diff --git a/packages/dicom/core/collections/__tests__/instanceFactsFixture.ts b/src/dicom/core/collections/__tests__/instanceFactsFixture.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/instanceFactsFixture.ts rename to src/dicom/core/collections/__tests__/instanceFactsFixture.ts diff --git a/packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/src/dicom/core/collections/__tests__/instanceRegistry.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/instanceRegistry.spec.ts rename to src/dicom/core/collections/__tests__/instanceRegistry.spec.ts diff --git a/packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts b/src/dicom/core/collections/__tests__/multiframeGeometry.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/multiframeGeometry.spec.ts rename to src/dicom/core/collections/__tests__/multiframeGeometry.spec.ts diff --git a/packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts b/src/dicom/core/collections/__tests__/planDicomCollections.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/planDicomCollections.spec.ts rename to src/dicom/core/collections/__tests__/planDicomCollections.spec.ts diff --git a/packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts b/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/reconstructVolume.spec.ts rename to src/dicom/core/collections/__tests__/reconstructVolume.spec.ts diff --git a/packages/dicom/core/collections/__tests__/sliceFixture.ts b/src/dicom/core/collections/__tests__/sliceFixture.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/sliceFixture.ts rename to src/dicom/core/collections/__tests__/sliceFixture.ts diff --git a/packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts b/src/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts similarity index 100% rename from packages/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts rename to src/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts diff --git a/packages/dicom/core/collections/assignCollectionIds.ts b/src/dicom/core/collections/assignCollectionIds.ts similarity index 100% rename from packages/dicom/core/collections/assignCollectionIds.ts rename to src/dicom/core/collections/assignCollectionIds.ts diff --git a/packages/dicom/core/collections/datasetDetails.ts b/src/dicom/core/collections/datasetDetails.ts similarity index 100% rename from packages/dicom/core/collections/datasetDetails.ts rename to src/dicom/core/collections/datasetDetails.ts diff --git a/packages/dicom/core/collections/groupBy.ts b/src/dicom/core/collections/groupBy.ts similarity index 100% rename from packages/dicom/core/collections/groupBy.ts rename to src/dicom/core/collections/groupBy.ts diff --git a/packages/dicom/core/collections/instanceFacts.ts b/src/dicom/core/collections/instanceFacts.ts similarity index 100% rename from packages/dicom/core/collections/instanceFacts.ts rename to src/dicom/core/collections/instanceFacts.ts diff --git a/packages/dicom/core/collections/instanceKey.ts b/src/dicom/core/collections/instanceKey.ts similarity index 100% rename from packages/dicom/core/collections/instanceKey.ts rename to src/dicom/core/collections/instanceKey.ts diff --git a/packages/dicom/core/collections/instanceRegistry.ts b/src/dicom/core/collections/instanceRegistry.ts similarity index 100% rename from packages/dicom/core/collections/instanceRegistry.ts rename to src/dicom/core/collections/instanceRegistry.ts diff --git a/packages/dicom/core/collections/multiframeGeometry.ts b/src/dicom/core/collections/multiframeGeometry.ts similarity index 100% rename from packages/dicom/core/collections/multiframeGeometry.ts rename to src/dicom/core/collections/multiframeGeometry.ts diff --git a/packages/dicom/core/collections/orientation.ts b/src/dicom/core/collections/orientation.ts similarity index 100% rename from packages/dicom/core/collections/orientation.ts rename to src/dicom/core/collections/orientation.ts diff --git a/packages/dicom/core/collections/planDicomCollections.ts b/src/dicom/core/collections/planDicomCollections.ts similarity index 100% rename from packages/dicom/core/collections/planDicomCollections.ts rename to src/dicom/core/collections/planDicomCollections.ts diff --git a/packages/dicom/core/collections/reconstructVolume.ts b/src/dicom/core/collections/reconstructVolume.ts similarity index 100% rename from packages/dicom/core/collections/reconstructVolume.ts rename to src/dicom/core/collections/reconstructVolume.ts diff --git a/packages/dicom/core/collections/splitOverlappingAcquisitions.ts b/src/dicom/core/collections/splitOverlappingAcquisitions.ts similarity index 100% rename from packages/dicom/core/collections/splitOverlappingAcquisitions.ts rename to src/dicom/core/collections/splitOverlappingAcquisitions.ts diff --git a/packages/dicom/core/header/__tests__/byteDeque.spec.ts b/src/dicom/core/header/__tests__/byteDeque.spec.ts similarity index 100% rename from packages/dicom/core/header/__tests__/byteDeque.spec.ts rename to src/dicom/core/header/__tests__/byteDeque.spec.ts diff --git a/packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts b/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts similarity index 100% rename from packages/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts rename to src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts diff --git a/packages/dicom/core/header/__tests__/streamingByteReader.spec.ts b/src/dicom/core/header/__tests__/streamingByteReader.spec.ts similarity index 100% rename from packages/dicom/core/header/__tests__/streamingByteReader.spec.ts rename to src/dicom/core/header/__tests__/streamingByteReader.spec.ts diff --git a/packages/dicom/core/header/byteDeque.ts b/src/dicom/core/header/byteDeque.ts similarity index 100% rename from packages/dicom/core/header/byteDeque.ts rename to src/dicom/core/header/byteDeque.ts diff --git a/packages/dicom/core/header/dicomParser.ts b/src/dicom/core/header/dicomParser.ts similarity index 100% rename from packages/dicom/core/header/dicomParser.ts rename to src/dicom/core/header/dicomParser.ts diff --git a/packages/dicom/core/header/readDicomHeader.ts b/src/dicom/core/header/readDicomHeader.ts similarity index 100% rename from packages/dicom/core/header/readDicomHeader.ts rename to src/dicom/core/header/readDicomHeader.ts diff --git a/packages/dicom/core/header/streamingByteReader.ts b/src/dicom/core/header/streamingByteReader.ts similarity index 100% rename from packages/dicom/core/header/streamingByteReader.ts rename to src/dicom/core/header/streamingByteReader.ts diff --git a/packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/src/dicom/core/instance/__tests__/readInstanceSources.spec.ts similarity index 100% rename from packages/dicom/core/instance/__tests__/readInstanceSources.spec.ts rename to src/dicom/core/instance/__tests__/readInstanceSources.spec.ts diff --git a/packages/dicom/core/instance/readInstance.ts b/src/dicom/core/instance/readInstance.ts similarity index 100% rename from packages/dicom/core/instance/readInstance.ts rename to src/dicom/core/instance/readInstance.ts diff --git a/packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/src/dicom/core/metadata/__tests__/dcmjsParser.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/dcmjsParser.spec.ts rename to src/dicom/core/metadata/__tests__/dcmjsParser.spec.ts diff --git a/packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts b/src/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts rename to src/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts diff --git a/packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/dicomDataset.spec.ts rename to src/dicom/core/metadata/__tests__/dicomDataset.spec.ts diff --git a/packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts b/src/dicom/core/metadata/__tests__/dicomLayout.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/dicomLayout.spec.ts rename to src/dicom/core/metadata/__tests__/dicomLayout.spec.ts diff --git a/packages/dicom/core/metadata/__tests__/modalityRescale.spec.ts b/src/dicom/core/metadata/__tests__/modalityRescale.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/modalityRescale.spec.ts rename to src/dicom/core/metadata/__tests__/modalityRescale.spec.ts diff --git a/packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts b/src/dicom/core/metadata/__tests__/spatialMetadata.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/spatialMetadata.spec.ts rename to src/dicom/core/metadata/__tests__/spatialMetadata.spec.ts diff --git a/packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts b/src/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts similarity index 100% rename from packages/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts rename to src/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts diff --git a/packages/dicom/core/metadata/datasetAccess.ts b/src/dicom/core/metadata/datasetAccess.ts similarity index 100% rename from packages/dicom/core/metadata/datasetAccess.ts rename to src/dicom/core/metadata/datasetAccess.ts diff --git a/packages/dicom/core/metadata/dcmjs.d.ts b/src/dicom/core/metadata/dcmjs.d.ts similarity index 100% rename from packages/dicom/core/metadata/dcmjs.d.ts rename to src/dicom/core/metadata/dcmjs.d.ts diff --git a/packages/dicom/core/metadata/dcmjsParser.ts b/src/dicom/core/metadata/dcmjsParser.ts similarity index 100% rename from packages/dicom/core/metadata/dcmjsParser.ts rename to src/dicom/core/metadata/dcmjsParser.ts diff --git a/packages/dicom/core/metadata/dicomCharacterSet.ts b/src/dicom/core/metadata/dicomCharacterSet.ts similarity index 100% rename from packages/dicom/core/metadata/dicomCharacterSet.ts rename to src/dicom/core/metadata/dicomCharacterSet.ts diff --git a/packages/dicom/core/metadata/dicomDataset.ts b/src/dicom/core/metadata/dicomDataset.ts similarity index 100% rename from packages/dicom/core/metadata/dicomDataset.ts rename to src/dicom/core/metadata/dicomDataset.ts diff --git a/packages/dicom/core/metadata/dicomLayout.ts b/src/dicom/core/metadata/dicomLayout.ts similarity index 100% rename from packages/dicom/core/metadata/dicomLayout.ts rename to src/dicom/core/metadata/dicomLayout.ts diff --git a/packages/dicom/core/metadata/dicomTags.ts b/src/dicom/core/metadata/dicomTags.ts similarity index 100% rename from packages/dicom/core/metadata/dicomTags.ts rename to src/dicom/core/metadata/dicomTags.ts diff --git a/packages/dicom/core/metadata/functionalGroups.ts b/src/dicom/core/metadata/functionalGroups.ts similarity index 100% rename from packages/dicom/core/metadata/functionalGroups.ts rename to src/dicom/core/metadata/functionalGroups.ts diff --git a/packages/dicom/core/metadata/modalityRescale.ts b/src/dicom/core/metadata/modalityRescale.ts similarity index 100% rename from packages/dicom/core/metadata/modalityRescale.ts rename to src/dicom/core/metadata/modalityRescale.ts diff --git a/packages/dicom/core/metadata/nmReconstruction.ts b/src/dicom/core/metadata/nmReconstruction.ts similarity index 100% rename from packages/dicom/core/metadata/nmReconstruction.ts rename to src/dicom/core/metadata/nmReconstruction.ts diff --git a/packages/dicom/core/metadata/readDicomDataset.worker.ts b/src/dicom/core/metadata/readDicomDataset.worker.ts similarity index 100% rename from packages/dicom/core/metadata/readDicomDataset.worker.ts rename to src/dicom/core/metadata/readDicomDataset.worker.ts diff --git a/packages/dicom/core/metadata/spatialMetadata.ts b/src/dicom/core/metadata/spatialMetadata.ts similarity index 100% rename from packages/dicom/core/metadata/spatialMetadata.ts rename to src/dicom/core/metadata/spatialMetadata.ts diff --git a/packages/dicom/core/metadata/ultrasoundRegion.ts b/src/dicom/core/metadata/ultrasoundRegion.ts similarity index 100% rename from packages/dicom/core/metadata/ultrasoundRegion.ts rename to src/dicom/core/metadata/ultrasoundRegion.ts diff --git a/packages/dicom/core/pixels/__tests__/decoderTable.spec.ts b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts similarity index 100% rename from packages/dicom/core/pixels/__tests__/decoderTable.spec.ts rename to src/dicom/core/pixels/__tests__/decoderTable.spec.ts diff --git a/packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts b/src/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts similarity index 100% rename from packages/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts rename to src/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts diff --git a/packages/dicom/core/pixels/__tests__/frameIndex.spec.ts b/src/dicom/core/pixels/__tests__/frameIndex.spec.ts similarity index 100% rename from packages/dicom/core/pixels/__tests__/frameIndex.spec.ts rename to src/dicom/core/pixels/__tests__/frameIndex.spec.ts diff --git a/packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts b/src/dicom/core/pixels/__tests__/nativeFrame.spec.ts similarity index 100% rename from packages/dicom/core/pixels/__tests__/nativeFrame.spec.ts rename to src/dicom/core/pixels/__tests__/nativeFrame.spec.ts diff --git a/packages/dicom/core/pixels/__tests__/pixelFixture.ts b/src/dicom/core/pixels/__tests__/pixelFixture.ts similarity index 100% rename from packages/dicom/core/pixels/__tests__/pixelFixture.ts rename to src/dicom/core/pixels/__tests__/pixelFixture.ts diff --git a/packages/dicom/core/pixels/decoderTable.ts b/src/dicom/core/pixels/decoderTable.ts similarity index 100% rename from packages/dicom/core/pixels/decoderTable.ts rename to src/dicom/core/pixels/decoderTable.ts diff --git a/packages/dicom/core/pixels/encapsulatedFrames.ts b/src/dicom/core/pixels/encapsulatedFrames.ts similarity index 100% rename from packages/dicom/core/pixels/encapsulatedFrames.ts rename to src/dicom/core/pixels/encapsulatedFrames.ts diff --git a/packages/dicom/core/pixels/frameIndex.ts b/src/dicom/core/pixels/frameIndex.ts similarity index 100% rename from packages/dicom/core/pixels/frameIndex.ts rename to src/dicom/core/pixels/frameIndex.ts diff --git a/packages/dicom/core/pixels/nativeFrame.ts b/src/dicom/core/pixels/nativeFrame.ts similarity index 100% rename from packages/dicom/core/pixels/nativeFrame.ts rename to src/dicom/core/pixels/nativeFrame.ts diff --git a/packages/dicom/core/pixels/pixelDecoder.ts b/src/dicom/core/pixels/pixelDecoder.ts similarity index 100% rename from packages/dicom/core/pixels/pixelDecoder.ts rename to src/dicom/core/pixels/pixelDecoder.ts diff --git a/packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts b/src/dicom/core/runtime/__tests__/dicomRuntime.spec.ts similarity index 100% rename from packages/dicom/core/runtime/__tests__/dicomRuntime.spec.ts rename to src/dicom/core/runtime/__tests__/dicomRuntime.spec.ts diff --git a/packages/dicom/core/runtime/__tests__/metadataReader.spec.ts b/src/dicom/core/runtime/__tests__/metadataReader.spec.ts similarity index 100% rename from packages/dicom/core/runtime/__tests__/metadataReader.spec.ts rename to src/dicom/core/runtime/__tests__/metadataReader.spec.ts diff --git a/packages/dicom/core/runtime/__tests__/requestPool.spec.ts b/src/dicom/core/runtime/__tests__/requestPool.spec.ts similarity index 100% rename from packages/dicom/core/runtime/__tests__/requestPool.spec.ts rename to src/dicom/core/runtime/__tests__/requestPool.spec.ts diff --git a/packages/dicom/core/runtime/createDicomRuntime.ts b/src/dicom/core/runtime/createDicomRuntime.ts similarity index 100% rename from packages/dicom/core/runtime/createDicomRuntime.ts rename to src/dicom/core/runtime/createDicomRuntime.ts diff --git a/packages/dicom/core/runtime/gdcmDecoder.ts b/src/dicom/core/runtime/gdcmDecoder.ts similarity index 100% rename from packages/dicom/core/runtime/gdcmDecoder.ts rename to src/dicom/core/runtime/gdcmDecoder.ts diff --git a/packages/dicom/core/runtime/metadataReader.ts b/src/dicom/core/runtime/metadataReader.ts similarity index 100% rename from packages/dicom/core/runtime/metadataReader.ts rename to src/dicom/core/runtime/metadataReader.ts diff --git a/packages/dicom/core/runtime/requestPool.ts b/src/dicom/core/runtime/requestPool.ts similarity index 100% rename from packages/dicom/core/runtime/requestPool.ts rename to src/dicom/core/runtime/requestPool.ts diff --git a/packages/dicom/core/source/__tests__/byteSource.spec.ts b/src/dicom/core/source/__tests__/byteSource.spec.ts similarity index 100% rename from packages/dicom/core/source/__tests__/byteSource.spec.ts rename to src/dicom/core/source/__tests__/byteSource.spec.ts diff --git a/packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts b/src/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts similarity index 100% rename from packages/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts rename to src/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts diff --git a/packages/dicom/core/source/byteSource.ts b/src/dicom/core/source/byteSource.ts similarity index 100% rename from packages/dicom/core/source/byteSource.ts rename to src/dicom/core/source/byteSource.ts diff --git a/packages/dicom/core/source/parseContentRangeHeader.ts b/src/dicom/core/source/parseContentRangeHeader.ts similarity index 100% rename from packages/dicom/core/source/parseContentRangeHeader.ts rename to src/dicom/core/source/parseContentRangeHeader.ts diff --git a/packages/dicom/core/utils.ts b/src/dicom/core/utils.ts similarity index 100% rename from packages/dicom/core/utils.ts rename to src/dicom/core/utils.ts diff --git a/packages/dicom/core/volume/__tests__/allocateVolume.spec.ts b/src/dicom/core/volume/__tests__/allocateVolume.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/allocateVolume.spec.ts rename to src/dicom/core/volume/__tests__/allocateVolume.spec.ts diff --git a/packages/dicom/core/volume/__tests__/enhancedFixture.ts b/src/dicom/core/volume/__tests__/enhancedFixture.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/enhancedFixture.ts rename to src/dicom/core/volume/__tests__/enhancedFixture.ts diff --git a/packages/dicom/core/volume/__tests__/frameGeometry.spec.ts b/src/dicom/core/volume/__tests__/frameGeometry.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/frameGeometry.spec.ts rename to src/dicom/core/volume/__tests__/frameGeometry.spec.ts diff --git a/packages/dicom/core/volume/__tests__/loadFrames.spec.ts b/src/dicom/core/volume/__tests__/loadFrames.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/loadFrames.spec.ts rename to src/dicom/core/volume/__tests__/loadFrames.spec.ts diff --git a/packages/dicom/core/volume/__tests__/loadVolume.spec.ts b/src/dicom/core/volume/__tests__/loadVolume.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/loadVolume.spec.ts rename to src/dicom/core/volume/__tests__/loadVolume.spec.ts diff --git a/packages/dicom/core/volume/__tests__/pixelFormat.spec.ts b/src/dicom/core/volume/__tests__/pixelFormat.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/pixelFormat.spec.ts rename to src/dicom/core/volume/__tests__/pixelFormat.spec.ts diff --git a/packages/dicom/core/volume/__tests__/pixelValidation.spec.ts b/src/dicom/core/volume/__tests__/pixelValidation.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/pixelValidation.spec.ts rename to src/dicom/core/volume/__tests__/pixelValidation.spec.ts diff --git a/packages/dicom/core/volume/__tests__/slotOrder.spec.ts b/src/dicom/core/volume/__tests__/slotOrder.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/slotOrder.spec.ts rename to src/dicom/core/volume/__tests__/slotOrder.spec.ts diff --git a/packages/dicom/core/volume/__tests__/volumeFixture.ts b/src/dicom/core/volume/__tests__/volumeFixture.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/volumeFixture.ts rename to src/dicom/core/volume/__tests__/volumeFixture.ts diff --git a/packages/dicom/core/volume/__tests__/volumeLayout.spec.ts b/src/dicom/core/volume/__tests__/volumeLayout.spec.ts similarity index 100% rename from packages/dicom/core/volume/__tests__/volumeLayout.spec.ts rename to src/dicom/core/volume/__tests__/volumeLayout.spec.ts diff --git a/packages/dicom/core/volume/allocateVolume.ts b/src/dicom/core/volume/allocateVolume.ts similarity index 100% rename from packages/dicom/core/volume/allocateVolume.ts rename to src/dicom/core/volume/allocateVolume.ts diff --git a/packages/dicom/core/volume/loadVolume.ts b/src/dicom/core/volume/loadVolume.ts similarity index 100% rename from packages/dicom/core/volume/loadVolume.ts rename to src/dicom/core/volume/loadVolume.ts diff --git a/packages/dicom/core/volume/nmGeometry.ts b/src/dicom/core/volume/nmGeometry.ts similarity index 100% rename from packages/dicom/core/volume/nmGeometry.ts rename to src/dicom/core/volume/nmGeometry.ts diff --git a/packages/dicom/core/volume/pixelFormat.ts b/src/dicom/core/volume/pixelFormat.ts similarity index 100% rename from packages/dicom/core/volume/pixelFormat.ts rename to src/dicom/core/volume/pixelFormat.ts diff --git a/packages/dicom/core/volume/pixelValidation.ts b/src/dicom/core/volume/pixelValidation.ts similarity index 100% rename from packages/dicom/core/volume/pixelValidation.ts rename to src/dicom/core/volume/pixelValidation.ts diff --git a/packages/dicom/core/volume/slotOrder.ts b/src/dicom/core/volume/slotOrder.ts similarity index 100% rename from packages/dicom/core/volume/slotOrder.ts rename to src/dicom/core/volume/slotOrder.ts diff --git a/packages/dicom/core/volume/ultrasoundSpacing.ts b/src/dicom/core/volume/ultrasoundSpacing.ts similarity index 100% rename from packages/dicom/core/volume/ultrasoundSpacing.ts rename to src/dicom/core/volume/ultrasoundSpacing.ts diff --git a/packages/dicom/core/volume/volumeLayout.ts b/src/dicom/core/volume/volumeLayout.ts similarity index 100% rename from packages/dicom/core/volume/volumeLayout.ts rename to src/dicom/core/volume/volumeLayout.ts diff --git a/packages/dicom/vtk/__tests__/thumbnail.spec.ts b/src/dicom/vtk/__tests__/thumbnail.spec.ts similarity index 100% rename from packages/dicom/vtk/__tests__/thumbnail.spec.ts rename to src/dicom/vtk/__tests__/thumbnail.spec.ts diff --git a/packages/dicom/vtk/__tests__/volumeImage.spec.ts b/src/dicom/vtk/__tests__/volumeImage.spec.ts similarity index 100% rename from packages/dicom/vtk/__tests__/volumeImage.spec.ts rename to src/dicom/vtk/__tests__/volumeImage.spec.ts diff --git a/packages/dicom/vtk/thumbnail.ts b/src/dicom/vtk/thumbnail.ts similarity index 100% rename from packages/dicom/vtk/thumbnail.ts rename to src/dicom/vtk/thumbnail.ts diff --git a/packages/dicom/vtk/volumeImage.ts b/src/dicom/vtk/volumeImage.ts similarity index 100% rename from packages/dicom/vtk/volumeImage.ts rename to src/dicom/vtk/volumeImage.ts diff --git a/src/enface/__tests__/availability.spec.ts b/src/enface/__tests__/availability.spec.ts index 1c1457b16..75bb3e2ed 100644 --- a/src/enface/__tests__/availability.spec.ts +++ b/src/enface/__tests__/availability.spec.ts @@ -9,7 +9,7 @@ import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { setDicomTag } from './dicomMetadataFixture'; describe('OCT view availability', () => { diff --git a/src/enface/__tests__/calibration.spec.ts b/src/enface/__tests__/calibration.spec.ts index d9ad9ab23..0935c02fe 100644 --- a/src/enface/__tests__/calibration.spec.ts +++ b/src/enface/__tests__/calibration.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; -import { toVtkImageData } from '@/packages/dicom/vtk/volumeImage'; +import { toVtkImageData } from '@/src/dicom/vtk/volumeImage'; import { volumeOf } from '@/tests/unit/octFixture'; import { OPHTHALMIC_TOMOGRAPHY_SOP } from '@/src/core/streaming/dicom/octMetadataTags'; import { measureOccupiedDepth } from '@/src/segmentation/measurements/occupiedDepth'; diff --git a/src/enface/__tests__/dicomMetadataFixture.ts b/src/enface/__tests__/dicomMetadataFixture.ts index e4307aee2..884472c26 100644 --- a/src/enface/__tests__/dicomMetadataFixture.ts +++ b/src/enface/__tests__/dicomMetadataFixture.ts @@ -1,4 +1,4 @@ -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; import { datasetFromTags } from '@/tests/dicomDataset'; const keyOf = (tag: string) => tag.replace('|', '').toUpperCase(); diff --git a/src/enface/__tests__/inputCalibration.spec.ts b/src/enface/__tests__/inputCalibration.spec.ts index 31a00e94a..8f9aa27f9 100644 --- a/src/enface/__tests__/inputCalibration.spec.ts +++ b/src/enface/__tests__/inputCalibration.spec.ts @@ -3,7 +3,7 @@ import { mount } from '@vue/test-utils'; import { createPinia, setActivePinia } from 'pinia'; import { computed, defineComponent, h, markRaw, nextTick, ref } from 'vue'; import { createVuetify } from 'vuetify'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { CurrentImageInjectionKey } from '@/src/composables/useCurrentImage'; import { untilLoaded } from '@/src/composables/untilLoaded'; import { useImageCacheStore } from '@/src/store/image-cache'; diff --git a/src/enface/__tests__/occupiedDepthSupport.spec.ts b/src/enface/__tests__/occupiedDepthSupport.spec.ts index 88562d04a..03f14cf33 100644 --- a/src/enface/__tests__/occupiedDepthSupport.spec.ts +++ b/src/enface/__tests__/occupiedDepthSupport.spec.ts @@ -6,7 +6,7 @@ import { getOccupiedDepthSupport } from '@/src/enface/occupiedDepthSupport'; import { createOCTFixture, volumeOf } from '@/tests/unit/octFixture'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { datasetFromTags } from '@/tests/dicomDataset'; import { removeDicomTag, diff --git a/src/enface/__tests__/seriesGeometry.spec.ts b/src/enface/__tests__/seriesGeometry.spec.ts index 52d08940b..9398ffe65 100644 --- a/src/enface/__tests__/seriesGeometry.spec.ts +++ b/src/enface/__tests__/seriesGeometry.spec.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { useImageCacheStore } from '@/src/store/image-cache'; import { untilLoaded } from '@/src/composables/untilLoaded'; import { diff --git a/src/enface/availability.ts b/src/enface/availability.ts index 6fdda0f99..4183eb753 100644 --- a/src/enface/availability.ts +++ b/src/enface/availability.ts @@ -4,8 +4,8 @@ import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; import type { ProgressiveImage } from '@/src/core/progressiveImage'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; import { OCT_GEOMETRY_ERROR, OCT_SCAN_PATTERN, diff --git a/src/enface/occupiedDepthSupport.ts b/src/enface/occupiedDepthSupport.ts index 8acc7b95b..203023223 100644 --- a/src/enface/occupiedDepthSupport.ts +++ b/src/enface/occupiedDepthSupport.ts @@ -3,12 +3,12 @@ import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { readUltrasoundRegions, unitToMm, -} from '@/packages/dicom/core/metadata/ultrasoundRegion'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/metadata/ultrasoundRegion'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { dicomSeriesGeometry } from '@/src/core/streaming/dicom/seriesGeometry'; function measurementMetadata(instance: Instance) { diff --git a/src/io/import/__tests__/dataSource.spec.ts b/src/io/import/__tests__/dataSource.spec.ts index 1e5af3345..f63b5d25d 100644 --- a/src/io/import/__tests__/dataSource.spec.ts +++ b/src/io/import/__tests__/dataSource.spec.ts @@ -3,7 +3,7 @@ import { getDataSourceName, isRemoteDataSource, } from '@/src/io/import/dataSource'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; describe('isRemoteDatasource', () => { it('should work', () => { diff --git a/src/io/import/__tests__/importDicomInstanceSources.spec.ts b/src/io/import/__tests__/importDicomInstanceSources.spec.ts index 902a3b828..27f8b6868 100644 --- a/src/io/import/__tests__/importDicomInstanceSources.spec.ts +++ b/src/io/import/__tests__/importDicomInstanceSources.spec.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { buildStateIDToStoreID, importDicomInstanceSources, diff --git a/src/io/import/dataSource.ts b/src/io/import/dataSource.ts index 2660104ab..db43b4896 100644 --- a/src/io/import/dataSource.ts +++ b/src/io/import/dataSource.ts @@ -1,4 +1,4 @@ -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import type { Fetcher } from '@/src/core/streaming/types'; import { Maybe } from '@/src/types'; diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index 6b1d8cdcf..0c5523a23 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -41,8 +41,8 @@ import downloadStream from '@/src/io/import/processors/downloadStream'; import { asyncSelect } from '@/src/utils/asyncSelect'; import { evaluateChain, Skip } from '@/src/utils/evaluateChain'; import { ensureError } from '@/src/utils'; -import { groupBy } from '@/packages/dicom/core/collections/groupBy'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import { groupBy } from '@/src/dicom/core/collections/groupBy'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { useDatasetStore } from '@/src/store/datasets'; import { useDICOMStore, diff --git a/src/io/import/processors/__tests__/handleDicom.spec.ts b/src/io/import/processors/__tests__/handleDicom.spec.ts index 638c08cf0..6c1e637f8 100644 --- a/src/io/import/processors/__tests__/handleDicom.spec.ts +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; -import { readDicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { readUltrasoundRegions } from '@/packages/dicom/core/metadata/ultrasoundRegion'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import { readBytes } from '@/src/dicom/core/source/byteSource'; +import { readDicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { readUltrasoundRegions } from '@/src/dicom/core/metadata/ultrasoundRegion'; import type { DataSource } from '@/src/io/import/dataSource'; import { fileToDataSource } from '@/src/io/import/dataSource'; import handleDicom from '@/src/io/import/processors/handleDicom'; diff --git a/src/io/import/processors/handleDicom.ts b/src/io/import/processors/handleDicom.ts index 343f2c25e..dcc403763 100644 --- a/src/io/import/processors/handleDicom.ts +++ b/src/io/import/processors/handleDicom.ts @@ -1,10 +1,10 @@ -import { fromBlob, fromUrl } from '@/packages/dicom/core/source/byteSource'; -import { getDatasetModality } from '@/packages/dicom/core/metadata/datasetAccess'; +import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; +import { getDatasetModality } from '@/src/dicom/core/metadata/datasetAccess'; import { IMPLICIT_VR_LITTLE_ENDIAN, type DicomLayout, -} from '@/packages/dicom/core/metadata/dicomLayout'; -import type { DicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; +} from '@/src/dicom/core/metadata/dicomLayout'; +import type { DicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; import { Skip } from '@/src/utils/evaluateChain'; import { diff --git a/src/io/import/processors/updateUriType.ts b/src/io/import/processors/updateUriType.ts index 7cc4cfbce..e6a456fb5 100644 --- a/src/io/import/processors/updateUriType.ts +++ b/src/io/import/processors/updateUriType.ts @@ -1,9 +1,9 @@ import { Skip } from '@/src/utils/evaluateChain'; -import StreamingByteReader from '@/packages/dicom/core/header/streamingByteReader'; +import StreamingByteReader from '@/src/dicom/core/header/streamingByteReader'; import { ImportHandler, asIntermediateResult } from '@/src/io/import/common'; import { getFileMimeFromMagicStream } from '@/src/io/magic'; import { getMimeTypeFromFilename } from '@/src/io/io'; -import { asCoroutine } from '@/packages/dicom/core/utils'; +import { asCoroutine } from '@/src/dicom/core/utils'; const DoneSignal = Symbol('DoneSignal'); diff --git a/src/io/magic.ts b/src/io/magic.ts index 1970bd5d0..6f61539c7 100644 --- a/src/io/magic.ts +++ b/src/io/magic.ts @@ -1,4 +1,4 @@ -import StreamingByteReader from '@/packages/dicom/core/header/streamingByteReader'; +import StreamingByteReader from '@/src/dicom/core/header/streamingByteReader'; import { Maybe } from '../types'; interface MagicDatabase { diff --git a/src/segmentation/__tests__/artifactParentRestore.spec.ts b/src/segmentation/__tests__/artifactParentRestore.spec.ts index 41c8a6c42..891541883 100644 --- a/src/segmentation/__tests__/artifactParentRestore.spec.ts +++ b/src/segmentation/__tests__/artifactParentRestore.spec.ts @@ -6,10 +6,10 @@ import { flushPromises } from '@vue/test-utils'; import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; -import { allocateVolume } from '@/packages/dicom/core/volume/allocateVolume'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { allocateVolume } from '@/src/dicom/core/volume/allocateVolume'; +import { createDicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import { LoadedVtkImage } from '@/src/core/progressiveImage'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; diff --git a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts index 6c715f3cd..8dfe8c29c 100644 --- a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts +++ b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { useImageCacheStore } from '@/src/store/image-cache'; import { useMessageStore } from '@/src/store/messages'; import { diff --git a/src/store/__tests__/datasets-dicom-cine.spec.ts b/src/store/__tests__/datasets-dicom-cine.spec.ts index cd8d22fcf..0c5071050 100644 --- a/src/store/__tests__/datasets-dicom-cine.spec.ts +++ b/src/store/__tests__/datasets-dicom-cine.spec.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { cineInstance, TS_JPEG_BASELINE, diff --git a/src/store/__tests__/datasets-dicom-geometry.spec.ts b/src/store/__tests__/datasets-dicom-geometry.spec.ts index 7689a52be..c744c089f 100644 --- a/src/store/__tests__/datasets-dicom-geometry.spec.ts +++ b/src/store/__tests__/datasets-dicom-geometry.spec.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { useDICOMStore } from '@/src/store/datasets-dicom'; import { useMessageStore } from '@/src/store/messages'; import { diff --git a/src/store/__tests__/datasets-dicom-transaction.spec.ts b/src/store/__tests__/datasets-dicom-transaction.spec.ts index 5f2174e15..7fe8a8e9e 100644 --- a/src/store/__tests__/datasets-dicom-transaction.spec.ts +++ b/src/store/__tests__/datasets-dicom-transaction.spec.ts @@ -1,4 +1,4 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; diff --git a/src/store/__tests__/dicomImportFixtures.ts b/src/store/__tests__/dicomImportFixtures.ts index 6b402f4f0..4f6e73ce9 100644 --- a/src/store/__tests__/dicomImportFixtures.ts +++ b/src/store/__tests__/dicomImportFixtures.ts @@ -1,13 +1,10 @@ import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { - fromBlob, - type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import type { WholeInstanceDecode } from '@/packages/dicom/core/pixels/pixelDecoder'; +import { createDicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, type ByteSource } from '@/src/dicom/core/source/byteSource'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; +import type { WholeInstanceDecode } from '@/src/dicom/core/pixels/pixelDecoder'; import { onTestFinished, expect } from 'vitest'; import { decodingWith } from '@/tests/dicomVolumeFixtures'; import { tilt } from '@/tests/dicomOrientationFixtures'; diff --git a/src/store/__tests__/dicomTagFixtures.ts b/src/store/__tests__/dicomTagFixtures.ts index 47c31130f..ee158cb73 100644 --- a/src/store/__tests__/dicomTagFixtures.ts +++ b/src/store/__tests__/dicomTagFixtures.ts @@ -1,4 +1,4 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; /** * The tags one synthetic instance carries, in the order the DICOM store reads diff --git a/src/store/__tests__/duplicateDatasetSave.spec.ts b/src/store/__tests__/duplicateDatasetSave.spec.ts index 36fea9953..f87e5207d 100644 --- a/src/store/__tests__/duplicateDatasetSave.spec.ts +++ b/src/store/__tests__/duplicateDatasetSave.spec.ts @@ -13,7 +13,7 @@ import { MANIFEST_VERSION, } from '@/src/io/state-file/serialize'; import type { Manifest } from '@/src/io/state-file/schema'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; /** Saves the dataset store into a fresh manifest and zip. */ diff --git a/src/store/datasets-dicom.ts b/src/store/datasets-dicom.ts index e4b46ff00..2bd63a47b 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -2,23 +2,23 @@ import { defineStore } from 'pinia'; import { allocateVolume, type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; +} from '@/src/dicom/core/volume/allocateVolume'; import { emptyRegistry, forgetCollection, registerInstances, type InstanceCollectionUpdate, type RegistryState, -} from '@/packages/dicom/core/collections/instanceRegistry'; +} from '@/src/dicom/core/collections/instanceRegistry'; import { getDatasetModality, getDatasetTag, -} from '@/packages/dicom/core/metadata/datasetAccess'; -import { seriesKeyOf } from '@/packages/dicom/core/collections/instanceFacts'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/metadata/datasetAccess'; +import { seriesKeyOf } from '@/src/dicom/core/collections/instanceFacts'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { useImageCacheStore } from '@/src/store/image-cache'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { ProgressiveImage } from '@/src/core/progressiveImage'; @@ -27,7 +27,7 @@ import { isCineInstance, readCineHeader } from '@/src/core/cine/cineInstance'; import { surfaceWarning, useMessageStore } from '@/src/store/messages'; import { viewedSlice } from '@/src/store/dicom-viewed-slice'; import { ensureError, removeFromArray } from '../utils'; -import { groupBy } from '@/packages/dicom/core/collections/groupBy'; +import { groupBy } from '@/src/dicom/core/collections/groupBy'; export const ANONYMOUS_PATIENT = 'Anonymous'; export const ANONYMOUS_PATIENT_ID = 'ANONYMOUS'; diff --git a/src/store/datasets.ts b/src/store/datasets.ts index adfdc4c6f..d4039966e 100644 --- a/src/store/datasets.ts +++ b/src/store/datasets.ts @@ -9,10 +9,10 @@ import { useLayersStore } from '@/src/store/datasets-layers'; import { useModelStore } from '@/src/store/datasets-models'; import { useViewConfigStore } from '@/src/store/view-configs'; import { useImageStatsStore } from '@/src/store/image-stats'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; export const DataType = { Image: 'Image', diff --git a/src/store/dicom-runtime.ts b/src/store/dicom-runtime.ts index 67f7bedb5..338125499 100644 --- a/src/store/dicom-runtime.ts +++ b/src/store/dicom-runtime.ts @@ -1,6 +1,6 @@ import { defineStore } from 'pinia'; import { markRaw, onScopeDispose } from 'vue'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; +import { createDicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; import { $fetch } from '@/src/utils/fetch'; import itkConfig from '@/src/io/itk/itkConfig'; diff --git a/src/store/dicom-web/dicom-web-store.ts b/src/store/dicom-web/dicom-web-store.ts index 26b5ead7b..e5fb023aa 100644 --- a/src/store/dicom-web/dicom-web-store.ts +++ b/src/store/dicom-web/dicom-web-store.ts @@ -26,7 +26,7 @@ import { isVolumeResult, type ImportDataSourcesResult, } from '@/src/io/import/common'; -import { trimDicomPadding } from '@/packages/dicom/core/utils'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; const DICOM_WEB_URL_PARAM = 'dicomweb'; diff --git a/src/utils/__tests__/dicomWindowRange.spec.ts b/src/utils/__tests__/dicomWindowRange.spec.ts index e6a8f0f3b..f278af565 100644 --- a/src/utils/__tests__/dicomWindowRange.spec.ts +++ b/src/utils/__tests__/dicomWindowRange.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { getConsistentDicomWindowRange } from '@/src/utils/dicomWindowRange'; function windowTags(center: string, width: string, voiFunction?: string) { diff --git a/src/utils/dicom/windowMetadata.ts b/src/utils/dicom/windowMetadata.ts index 028d23e9f..c128e0d04 100644 --- a/src/utils/dicom/windowMetadata.ts +++ b/src/utils/dicom/windowMetadata.ts @@ -1,6 +1,6 @@ -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; /** The VOI attributes used when choosing a shared display window. */ export const getWindowMetadata = (dataset: DicomDataset) => diff --git a/src/utils/dicomWindowRange.ts b/src/utils/dicomWindowRange.ts index d90af3073..22aec4143 100644 --- a/src/utils/dicomWindowRange.ts +++ b/src/utils/dicomWindowRange.ts @@ -1,4 +1,4 @@ -import { Tags } from '@/packages/dicom/core/metadata/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; type DicomMetadata = Iterable | null | undefined; diff --git a/tests/byteSourceFixtures.ts b/tests/byteSourceFixtures.ts index dc709afaf..b147cf2a1 100644 --- a/tests/byteSourceFixtures.ts +++ b/tests/byteSourceFixtures.ts @@ -1,4 +1,4 @@ -import type { ByteSource } from '@/packages/dicom/core/source/byteSource'; +import type { ByteSource } from '@/src/dicom/core/source/byteSource'; /** Hands out bytes a chunk at a time and counts what readers pulled and cancelled. */ export const trackedSource = (bytes: Uint8Array, chunkSize = bytes.length) => { diff --git a/tests/dicomDataset.ts b/tests/dicomDataset.ts index 981f520e2..83e99b778 100644 --- a/tests/dicomDataset.ts +++ b/tests/dicomDataset.ts @@ -1,9 +1,6 @@ -import { - fromBlob, - type ByteSource, -} from '@/packages/dicom/core/source/byteSource'; -import type { DicomDataset } from '@/packages/dicom/core/metadata/dicomDataset'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +import { fromBlob, type ByteSource } from '@/src/dicom/core/source/byteSource'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; /** Structured headers for fixtures whose values are written as tag strings. */ export const datasetFromTags = ( diff --git a/tests/dicomSourceFixtures.ts b/tests/dicomSourceFixtures.ts index 2ff9cf00d..304220a8d 100644 --- a/tests/dicomSourceFixtures.ts +++ b/tests/dicomSourceFixtures.ts @@ -1,7 +1,7 @@ import { readInstance, type ReadInstanceOptions, -} from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/instance/readInstance'; import { trackedSource } from '@/tests/byteSourceFixtures'; import { buildSyntheticDicom, diff --git a/tests/dicomVolumeFixtures.ts b/tests/dicomVolumeFixtures.ts index 986af5be9..b9bdae779 100644 --- a/tests/dicomVolumeFixtures.ts +++ b/tests/dicomVolumeFixtures.ts @@ -1,13 +1,13 @@ import { emptyRegistry, registerInstances, -} from '@/packages/dicom/core/collections/instanceRegistry'; -import { singleDecoderTable } from '@/packages/dicom/core/pixels/decoderTable'; +} from '@/src/dicom/core/collections/instanceRegistry'; +import { singleDecoderTable } from '@/src/dicom/core/pixels/decoderTable'; import { wholeInstanceDecoder, type WholeInstanceDecode, -} from '@/packages/dicom/core/pixels/pixelDecoder'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/pixels/pixelDecoder'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; /** The first collection planned from these members. */ export const plannedUpdate = (members: Instance[]) => diff --git a/tests/fixtures/dicom-pages/composition.ts b/tests/fixtures/dicom-pages/composition.ts index b2d5dde43..30593e33b 100644 --- a/tests/fixtures/dicom-pages/composition.ts +++ b/tests/fixtures/dicom-pages/composition.ts @@ -1,9 +1,9 @@ import { emptyRegistry, registerInstances, -} from '@/packages/dicom/core/collections/instanceRegistry'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/collections/instanceRegistry'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import corpus from '../../dicomCompositionCorpus.json'; import { failed, never, report, runtime, sourceOf } from './shared'; import { loadCollection } from './loadVolume'; diff --git a/tests/fixtures/dicom-pages/core.ts b/tests/fixtures/dicom-pages/core.ts index 7d7bd645f..20163d3ad 100644 --- a/tests/fixtures/dicom-pages/core.ts +++ b/tests/fixtures/dicom-pages/core.ts @@ -1,4 +1,4 @@ -import { fromBlob, readBytes } from '@/packages/dicom/core/source/byteSource'; +import { fromBlob, readBytes } from '@/src/dicom/core/source/byteSource'; import { assetUrls, createRuntime, diff --git a/tests/fixtures/dicom-pages/loadVolume.ts b/tests/fixtures/dicom-pages/loadVolume.ts index 5f38ec2c6..d1b6fa70e 100644 --- a/tests/fixtures/dicom-pages/loadVolume.ts +++ b/tests/fixtures/dicom-pages/loadVolume.ts @@ -1,19 +1,16 @@ import { allocateVolume, type Volume, -} from '@/packages/dicom/core/volume/allocateVolume'; +} from '@/src/dicom/core/volume/allocateVolume'; import { emptyRegistry, registerInstances, type InstanceCollectionUpdate, -} from '@/packages/dicom/core/collections/instanceRegistry'; -import { getDatasetModality } from '@/packages/dicom/core/metadata/datasetAccess'; -import { loadVolume } from '@/packages/dicom/core/volume/loadVolume'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; -import { - applyVolumeUpdate, - toVtkImageData, -} from '@/packages/dicom/vtk/volumeImage'; +} from '@/src/dicom/core/collections/instanceRegistry'; +import { getDatasetModality } from '@/src/dicom/core/metadata/datasetAccess'; +import { loadVolume } from '@/src/dicom/core/volume/loadVolume'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; +import { applyVolumeUpdate, toVtkImageData } from '@/src/dicom/vtk/volumeImage'; import { never, runtime } from './shared'; /** Allocates a planned collection and decodes it the way a viewer would. */ diff --git a/tests/fixtures/dicom-pages/parity.ts b/tests/fixtures/dicom-pages/parity.ts index 46e7bbca8..e476da9ba 100644 --- a/tests/fixtures/dicom-pages/parity.ts +++ b/tests/fixtures/dicom-pages/parity.ts @@ -2,12 +2,12 @@ import { getVolumeBufferType, instancePixelFormats, type VolumeBufferConstructor, -} from '@/packages/dicom/core/volume/pixelFormat'; -import { nativeFrameDecoder } from '@/packages/dicom/core/pixels/nativeFrame'; -import { planDecode } from '@/packages/dicom/core/pixels/decoderTable'; -import { readBytes } from '@/packages/dicom/core/source/byteSource'; -import type { DecodeUnit } from '@/packages/dicom/core/pixels/pixelDecoder'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/volume/pixelFormat'; +import { nativeFrameDecoder } from '@/src/dicom/core/pixels/nativeFrame'; +import { planDecode } from '@/src/dicom/core/pixels/decoderTable'; +import { readBytes } from '@/src/dicom/core/source/byteSource'; +import type { DecodeUnit } from '@/src/dicom/core/pixels/pixelDecoder'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { createRuntime, failed, diff --git a/tests/fixtures/dicom-pages/shared.ts b/tests/fixtures/dicom-pages/shared.ts index 6637e28b3..9821b15b2 100644 --- a/tests/fixtures/dicom-pages/shared.ts +++ b/tests/fixtures/dicom-pages/shared.ts @@ -1,13 +1,13 @@ import { createDicomRuntime, type DicomRuntimeOptions, -} from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { fromBlob, fromUrl } from '@/packages/dicom/core/source/byteSource'; +} from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; import { planDecode, singleDecoderTable, -} from '@/packages/dicom/core/pixels/decoderTable'; -import type { Instance } from '@/packages/dicom/core/instance/readInstance'; +} from '@/src/dicom/core/pixels/decoderTable'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; export const assetUrls = ( pipelineWorker = './assets/itk-wasm-pipeline.min.worker.js' diff --git a/tests/unit/octFixture.ts b/tests/unit/octFixture.ts index d9374cdcd..d0e2d0e2b 100644 --- a/tests/unit/octFixture.ts +++ b/tests/unit/octFixture.ts @@ -1,12 +1,12 @@ -import { allocateVolume } from '@/packages/dicom/core/volume/allocateVolume'; -import { createDicomRuntime } from '@/packages/dicom/core/runtime/createDicomRuntime'; -import { fromBlob } from '@/packages/dicom/core/source/byteSource'; -import { getDatasetTag } from '@/packages/dicom/core/metadata/datasetAccess'; +import { allocateVolume } from '@/src/dicom/core/volume/allocateVolume'; +import { createDicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; +import { getDatasetTag } from '@/src/dicom/core/metadata/datasetAccess'; import { readInstance, type Instance, -} from '@/packages/dicom/core/instance/readInstance'; -import type { WholeInstanceDecode } from '@/packages/dicom/core/pixels/pixelDecoder'; +} from '@/src/dicom/core/instance/readInstance'; +import type { WholeInstanceDecode } from '@/src/dicom/core/pixels/pixelDecoder'; import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { useImageCacheStore } from '@/src/store/image-cache'; diff --git a/tsconfig.json b/tsconfig.json index 5d191773a..1b262cfbe 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -43,8 +43,7 @@ "backend-contract/**/*.ts", "test/**/*.ts", "tests/**/*.ts", - "tests/**/*.tsx", - "packages/dicom/**/*.ts" + "tests/**/*.tsx" ], "exclude": [ "node_modules" From 516b5e979e48f83cf8283d4c57dbcc25d19354da Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:03:39 -0500 Subject: [PATCH 26/32] fix(dicom): space irregular stacks by their mean gap --- src/dicom/README.md | 12 ++++++---- .../__tests__/reconstructVolume.spec.ts | 10 ++++---- .../core/collections/reconstructVolume.ts | 23 ++++++++++--------- src/enface/__tests__/seriesGeometry.spec.ts | 2 +- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/src/dicom/README.md b/src/dicom/README.md index be042eb1a..dc30f5ea7 100644 --- a/src/dicom/README.md +++ b/src/dicom/README.md @@ -38,11 +38,13 @@ core `Volume` as a `vtkImageData`. `eslint.config.js` enforces both boundaries. assigning the returned state. The first registration of a SOP Instance UID is kept. - In a multi-file volume member i fills slice i. An irregular stack keeps its - planned order with approximate spacing and is not resampled. -- The buffer type comes from the headers' rescaled value ranges. Float32 is - used where it holds every value exactly, since vtk.js converts other types - to float32 on upload. Decoded values the buffer would round or not hold are - rejected. + planned order, spaced by its mean gap so its extent is kept, and is not + resampled. +- The buffer type comes from the headers' rescaled value ranges. Ranges that + fit 8 or 16 bit integers keep that integer type. Wider integer ranges and + fractional rescales use Float32 where it holds every value exactly, else + Int32, Uint32 or Float64. Decoded values the buffer would round or not hold + are rejected. - `loadVolume` writes each decoded unit at once and marks its slices loaded only when it yields the update. Units load focus first, then coarse to fine. A failed unit yields an error update naming the file and loading diff --git a/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts b/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts index 1e8d49fb4..92c030574 100644 --- a/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts +++ b/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts @@ -78,8 +78,7 @@ describe('reconstructVolume', () => { expect(result.sliceSpacing).toBeCloseTo(3.29, 2); }); - // The two slabs are 4mm stacks 42.439mm apart. Endpoint distance over slice - // count would call that a 4.59mm lattice, which describes neither slab. + // The two slabs are 4mm stacks 42.439mm apart, so no lattice holds them. it('calls the bilateral sagittal slabs an irregular stack', () => { const members = stack( bilateralSagittalSlabs @@ -92,9 +91,8 @@ describe('reconstructVolume', () => { expect(members).toHaveLength(66); expect(result.kind).toBe('irregular'); expect(result).toMatchObject({ reason: 'uneven-slice-spacing' }); - // The fallback places the slices at a gap the series actually holds. - expect(result.sliceSpacing).toBeCloseTo(4, 12); - expect(result.sliceSpacing).not.toBeCloseTo(4.59137, 4); + // The fallback keeps the distance between the outermost slices. + expect(result.sliceSpacing).toBeCloseTo(4.59137, 4); }); it('reports a hole in an otherwise even stack as irregular', () => { @@ -197,7 +195,7 @@ describe('reconstructVolume', () => { kind: 'irregular', reason: 'uneven-slice-spacing', }); - expect(result.sliceSpacing).toBeCloseTo(2, 12); + expect(result.sliceSpacing).toBeCloseTo(1, 12); }); it('has no step for members that never move', () => { diff --git a/src/dicom/core/collections/reconstructVolume.ts b/src/dicom/core/collections/reconstructVolume.ts index 7f0a24ca2..a619843f3 100644 --- a/src/dicom/core/collections/reconstructVolume.ts +++ b/src/dicom/core/collections/reconstructVolume.ts @@ -61,8 +61,7 @@ const spacingTolerance = (gap: number) => Math.abs(gap) * SLICE_SPACING_RELATIVE_TOLERANCE ); -// Lower median, so the fallback spacing of an irregular stack is one of its -// own gaps rather than an average of a gap and a hole. +// Lower median, so the step a stack is judged against is one of its own gaps. const median = (values: number[]) => [...values].sort((left, right) => left - right)[ Math.floor((values.length - 1) / 2) @@ -85,9 +84,10 @@ const distance = (left: number[], right: number[]) => /** * The step a stack that is no lattice still takes: the lower median of the * straight-line distance from each member to the next, in the order given. - * That is what ITK's series reader steps by, so a tilted gantry's slices, - * whose planes shift sideways as they advance, keep the extent they were - * scanned over. Null when a position is unreadable or the members never move. + * A tilted gantry's slices, whose planes shift sideways as they advance, keep + * the distance they were scanned at, and one slice shifted within its plane + * does not stretch the rest. Null when a position is unreadable or the + * members never move. */ const positionStep = (members: ReconstructionMember[]) => { const positions = members.map((member) => member.position); @@ -154,7 +154,10 @@ const lattice = (along: number[]): Reconstruction => { const gaps = along.slice(1).map((position, index) => position - along[index]); const step = median(gaps); const count = along.length; - const fallback = step > 0 ? step : null; + // The mean gap keeps an irregular stack's extent, so a missing slice moves + // its neighbours by less than half a slice and overlays stay registered. + const mean = (along[count - 1] - along[0]) / gaps.length; + const fallback = [mean, step].find((gap) => gap > 0) ?? null; // Frames are judged in stored order, so a step backwards is not a repeat. if (new Set(along).size < count) @@ -164,14 +167,12 @@ const lattice = (along: number[]): Reconstruction => { // Every gap matches, so the endpoints fit the members better than any single // printed gap does. - const sliceSpacing = (along[count - 1] - along[0]) / gaps.length; const drifts = along.some( - (position, index) => - Math.round((position - along[0]) / sliceSpacing) !== index + (position, index) => Math.round((position - along[0]) / mean) !== index ); return drifts - ? irregular('uneven-slice-spacing', step) - : { kind: 'regular', sliceSpacing }; + ? irregular('uneven-slice-spacing', fallback) + : { kind: 'regular', sliceSpacing: mean }; }; /** diff --git a/src/enface/__tests__/seriesGeometry.spec.ts b/src/enface/__tests__/seriesGeometry.spec.ts index 9398ffe65..194ffc09c 100644 --- a/src/enface/__tests__/seriesGeometry.spec.ts +++ b/src/enface/__tests__/seriesGeometry.spec.ts @@ -165,7 +165,7 @@ describe('assembled OCT series through real header and file collaborators', () = }); it.each([ - { positions: [0, 0.1, 0.4], displayedSpacing: 0.1 }, + { positions: [0, 0.1, 0.4], displayedSpacing: 0.2 }, { positions: [0, 0.2, 0.4003, 0.6, 0.8], displayedSpacing: 0.2 }, ])( 'keeps a nonuniform series projection-only: $positions', From e70d7ba9829d21a4731af58fe9061364670a01e1 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:03:48 -0500 Subject: [PATCH 27/32] fix(dicom): allocate chroma subsampled frames and name HTJ2K as undecodable --- .../pixels/__tests__/decoderTable.spec.ts | 26 +++--- src/dicom/core/pixels/decoderTable.ts | 3 + src/dicom/core/pixels/frameIndex.ts | 12 ++- .../volume/__tests__/allocateVolume.spec.ts | 87 ++++++++++++++----- .../core/volume/__tests__/loadVolume.spec.ts | 24 +++++ tests/nativePixelDicom.ts | 4 +- 6 files changed, 121 insertions(+), 35 deletions(-) diff --git a/src/dicom/core/pixels/__tests__/decoderTable.spec.ts b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts index 9870a2e1b..f108441d9 100644 --- a/src/dicom/core/pixels/__tests__/decoderTable.spec.ts +++ b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts @@ -57,17 +57,21 @@ describe('planDecode', () => { }); }); - it('names a known transfer syntax that has no decoder', async () => { - const { instance } = await pixelInstance({ - transferSyntaxUid: '1.2.840.10008.1.2.4.102', - }); - - const plan = planDecode(table, instance, Uint16Array); - - expect('error' in plan && plan.error.message).toBe( - 'Known transfer syntax MPEG-4 AVC/H.264 High Profile (1.2.840.10008.1.2.4.102) has no decoder' - ); - }); + 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'], + ])( + 'names known transfer syntax %s that has no decoder', + async (transferSyntaxUid, name) => { + const { instance } = await pixelInstance({ transferSyntaxUid }); + + const plan = planDecode(table, instance, Uint16Array); + + expect('error' in plan && plan.error.message).toBe( + `Known transfer syntax ${name} (${transferSyntaxUid}) has no decoder` + ); + } + ); it('takes the first candidate that accepts, in the order listed', async () => { const { instance } = await pixelInstance(); diff --git a/src/dicom/core/pixels/decoderTable.ts b/src/dicom/core/pixels/decoderTable.ts index 9ebf1a817..ca3460249 100644 --- a/src/dicom/core/pixels/decoderTable.ts +++ b/src/dicom/core/pixels/decoderTable.ts @@ -53,6 +53,9 @@ 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.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'], diff --git a/src/dicom/core/pixels/frameIndex.ts b/src/dicom/core/pixels/frameIndex.ts index e7313025e..c8c64fe08 100644 --- a/src/dicom/core/pixels/frameIndex.ts +++ b/src/dicom/core/pixels/frameIndex.ts @@ -8,7 +8,7 @@ import { IMPLICIT_VR_LITTLE_ENDIAN, } from '../metadata/dicomLayout'; import { Tags } from '../metadata/dicomTags'; -import { numberOr } from '../utils'; +import { numberOr, trimDicomPadding } from '../utils'; import { frameCount } from './pixelDecoder'; /** Transfer syntaxes whose Pixel Data is a plain run of fixed-size frames. */ @@ -49,6 +49,14 @@ export const shapeOf = ({ dataset }: Instance) => { const positiveInteger = (value: number) => Number.isSafeInteger(value) && value > 0; +// Chroma subsampling stores fewer bytes than Samples per Pixel implies. +const subsamplesChroma = ({ dataset }: Instance) => + /^YBR_(FULL|PARTIAL)_42[02]$/.test( + trimDicomPadding( + getDatasetTag(dataset, Tags.PhotometricInterpretation) ?? '' + ) + ); + type NativeLayout = Readonly<{ kind: 'native'; littleEndian: boolean; @@ -71,6 +79,8 @@ function nativeLayout(instance: Instance): NativeLayout | FrameIndex { ); if (pixelData.length === null) return unindexed('Pixel Data has undefined length'); + if (subsamplesChroma(instance)) + return unindexed('Chroma subsampled frames have no fixed sample layout'); const { rows, columns, samplesPerPixel, bitsAllocated, frames } = shapeOf(instance); if (![rows, columns, samplesPerPixel].every(positiveInteger)) diff --git a/src/dicom/core/volume/__tests__/allocateVolume.spec.ts b/src/dicom/core/volume/__tests__/allocateVolume.spec.ts index c336ce1af..5c4db6f6f 100644 --- a/src/dicom/core/volume/__tests__/allocateVolume.spec.ts +++ b/src/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -61,6 +61,26 @@ describe('allocateVolume', () => { ); }); + it('allocates a lone chroma subsampled instance, whose frames hold two bytes per pixel', async () => { + const instance = await readHeader( + nativePixelDicom({ + rows: 4, + columns: 4, + samplesPerPixel: 3, + photometric: 'YBR_FULL_422', + bitsAllocated: 8, + bitsStored: 8, + highBit: 7, + words: new Array(32).fill(128), + }) + ); + + const volume = allocateVolume(plannedUpdate([instance])); + + expect(volume.dimensions).toEqual([4, 4, 1]); + expect(volume.components).toBe(3); + }); + it('keeps an irregular stack in order', () => { const members = [3, 0, 1].map((z) => pixelSlice(z)); const volume = allocated(members); @@ -87,28 +107,51 @@ describe('allocateVolume', () => { }); }); - it('applies the first ultrasound region as display spacing', () => { - const ultrasound = pixelSlice(0, { modality: 'US' }); - ultrasound.dataset.elements.push({ - ...datasetFromTags([[Tags.SequenceOfUltrasoundRegions, '']]).elements[0], - vr: 'SQ', - values: { - kind: 'sequence', - items: [ - datasetFromTags([ - [Tags.PhysicalDeltaX, '0.01'], - [Tags.PhysicalDeltaY, '0.02'], - [Tags.PhysicalUnitsXDirection, '3'], - [Tags.PhysicalUnitsYDirection, '3'], - ]), - ], - }, - }); + it.each([ + { + name: 'applies a calibrated region as display spacing', + region: { deltaX: '0.01', deltaY: '0.02', unitsX: '3', unitsY: '3' }, + spacing: [0.1, 0.2], + warnings: [], + }, + { + name: 'keeps the pixel spacing and warns for a zero delta', + region: { deltaX: '0', deltaY: '0.02', unitsX: '3', unitsY: '3' }, + spacing: [0.5, 0.5], + warnings: ['Invalid ultrasound calibration'], + }, + { + name: 'keeps the pixel spacing when one axis is not a distance', + region: { deltaX: '0.01', deltaY: '0.02', unitsX: '3', unitsY: '4' }, + spacing: [0.5, 0.5], + warnings: [], + }, + ])( + '$name for the first ultrasound region', + ({ region, spacing, warnings }) => { + const ultrasound = pixelSlice(0, { modality: 'US' }); + ultrasound.dataset.elements.push({ + ...datasetFromTags([[Tags.SequenceOfUltrasoundRegions, '']]) + .elements[0], + vr: 'SQ', + values: { + kind: 'sequence', + items: [ + datasetFromTags([ + [Tags.PhysicalDeltaX, region.deltaX], + [Tags.PhysicalDeltaY, region.deltaY], + [Tags.PhysicalUnitsXDirection, region.unitsX], + [Tags.PhysicalUnitsYDirection, region.unitsY], + ]), + ], + }, + }); - const volume = allocated([ultrasound]); + const volume = allocated([ultrasound]); - expect(volume.spacing[0]).toBeCloseTo(0.1); - expect(volume.spacing[1]).toBeCloseTo(0.2); - expect(volume.warnings).toEqual([]); - }); + expect(volume.spacing[0]).toBeCloseTo(spacing[0]); + expect(volume.spacing[1]).toBeCloseTo(spacing[1]); + expect(volume.warnings.map(([title]) => title)).toEqual(warnings); + } + ); }); diff --git a/src/dicom/core/volume/__tests__/loadVolume.spec.ts b/src/dicom/core/volume/__tests__/loadVolume.spec.ts index f309545fa..c777106d7 100644 --- a/src/dicom/core/volume/__tests__/loadVolume.spec.ts +++ b/src/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -174,6 +174,30 @@ describe('loadVolume', () => { ]); }); + it('fails a slice of fractional values bound for an integer buffer and keeps whole-number floats', async () => { + const decode = valueDecoder(); + const decoder: WholeInstanceDecode = async (request, signal) => { + const image = await decode(request, signal); + const value = image.data[0]; + return value === 0 + ? image + : { ...image, data: new Float32Array(16).fill(value === 1 ? 1.5 : 2) }; + }; + const volume = stack(3); + + const updates = await loadAll(volume, runtimeWith(decoder)); + + expect(volume.data).toBeInstanceOf(Uint16Array); + expect(updates.find((update) => update.slot === 1)).toMatchObject({ + error: expect.objectContaining({ + message: expect.stringMatching( + /^File pixel-1 \(member 1\) has fractional pixel values/ + ), + }), + }); + expect(sliceValues(volume)).toEqual([0, null, 2]); + }); + it('fails a slice whose decoded values the volume buffer cannot hold', async () => { const decode = valueDecoder(); const decoder: WholeInstanceDecode = async (request, signal) => { diff --git a/tests/nativePixelDicom.ts b/tests/nativePixelDicom.ts index 10ed500d2..fc547b134 100644 --- a/tests/nativePixelDicom.ts +++ b/tests/nativePixelDicom.ts @@ -185,7 +185,9 @@ export function nativePixelDicom(options: NativePixelOptions = {}) { instance = 1, position = [0, 0, 0], } = options; - const count = rows * columns * samplesPerPixel * (frames ?? 1); + // 4:2:2 stores two bytes per pixel, whatever Samples per Pixel says. + const storedSamples = photometric.endsWith('_422') ? 2 : samplesPerPixel; + const count = rows * columns * storedSamples * (frames ?? 1); const words = options.words ?? patternWords(count, bitsAllocated, instance); if (words.length !== count) throw new Error(`Expected ${count} stored words, got ${words.length}`); From 87b635cf7e978e6d09cfc6520c65e397bf28f4ac Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:03:58 -0500 Subject: [PATCH 28/32] fix(dicom): bound the file meta read and keep empty numbers empty --- .../__tests__/dicomHeaderEncodings.spec.ts | 13 +++++++++++++ src/dicom/core/header/dicomParser.ts | 16 ++++++++++++---- .../core/metadata/__tests__/dicomDataset.spec.ts | 10 ++++++++++ src/dicom/core/metadata/dcmjsParser.ts | 10 ++++++---- 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts b/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts index 3aa3fd29d..fc68e31c5 100644 --- a/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts +++ b/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts @@ -51,6 +51,19 @@ const bigEndianItem = (element: number, length: number) => { }; describe('streamed header encodings', () => { + it('rejects a DICM file whose meta group names no transfer syntax before reading its data set', async () => { + const bytes = concatBytes([ + new Uint8Array(128), + encode('DICM'), + rawElement(0x0008, 0x0060, 'CS', encode('CT')), + rawElement(0x7fe0, 0x0010, 'OW', new Uint8Array(64)), + ]); + + await expect(readHeader(bytes, 7)).rejects.toThrow( + 'the file meta information names no transfer syntax' + ); + }); + it.each([sequenceItem, undefinedLengthItem])( 'passes encapsulated icon fragments inside %s to the metadata reader', async (item) => { diff --git a/src/dicom/core/header/dicomParser.ts b/src/dicom/core/header/dicomParser.ts index 6218f08e9..26c8f4b25 100644 --- a/src/dicom/core/header/dicomParser.ts +++ b/src/dicom/core/header/dicomParser.ts @@ -251,10 +251,18 @@ function* readFileMetaInfo( reader: StreamingByteReader, onDataElement: DataElementCallback | undefined ) { - yield* readDataElementsUntil(reader, equalsToTag(Tags.TransferSyntaxUID), { - ...FILE_META_ENCODING, - onDataElement, - }); + const isTransferSyntax = equalsToTag(Tags.TransferSyntaxUID); + yield* readDataElementsUntil( + reader, + (group, element) => group !== 0x0002 || isTransferSyntax(group, element), + { ...FILE_META_ENCODING, onDataElement } + ); + // Past group 0002 the data set's own encoding is unknown, pixels included. + const [nextGroup] = yield* peekElementTag(reader, FILE_META_ENCODING); + if (nextGroup !== 0x0002) + throw new Error( + 'Not a DICOM file: the file meta information names no transfer syntax' + ); const transferSyntaxUidElement = yield* readDataElement( reader, diff --git a/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts index 0321dfb91..db716191b 100644 --- a/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts +++ b/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts @@ -105,6 +105,16 @@ describe('readDicomDataset', () => { }); }); + it('reads a number element with no value as empty, not as zero', () => { + const dataset = readDicomDataset( + buildSlice({ + extraElements: [rawElement(0x0028, 0x0106, 'US', new Uint8Array())], + }) + ); + + expect(valuesOf(dataset, '00280106')).toMatchObject({ values: [] }); + }); + it('descends into a sequence and into the sequence inside it', () => { const dataset = readDicomDataset( buildSlice({ extraElements: [NESTED_SEQUENCE] }) diff --git a/src/dicom/core/metadata/dcmjsParser.ts b/src/dicom/core/metadata/dcmjsParser.ts index 2657035d0..d694ba0a0 100644 --- a/src/dicom/core/metadata/dcmjsParser.ts +++ b/src/dicom/core/metadata/dcmjsParser.ts @@ -37,6 +37,7 @@ const LENGTH_32_VRS = new Set([ 'UN', 'UR', 'UT', + 'UV', ]); /** Bound on one `String.fromCharCode` spread, which is an argument list. */ @@ -434,10 +435,11 @@ const readNextElement = ( stopAtPixelData ? READ_OPTIONS : { forceStoreRaw: true } ); const done = stopAtPixelData && element.tag.toCleanString() === PIXEL_DATA; - return { - element: done || element.vr === 0 ? null : parsedElement(element), - done, - }; + if (done || element.vr === 0) return { element: null, done }; + const parsed = parsedElement(element); + // dcmjs reads an empty fixed-size number as its default of 0. + const values = head.length === 0 ? [] : parsed.values; + return { element: { ...parsed, values }, done }; }; const readElements = ( From 679a86152961027c923f2f0f63fa62cdc24e2009 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:04:07 -0500 Subject: [PATCH 29/32] fix(import): skip image-less DICOM objects and report failures plainly --- .../__tests__/cachedStreamFetcher.spec.ts | 21 ++++++++------- src/core/streaming/cachedStreamFetcher.ts | 4 +-- .../processors/__tests__/handleDicom.spec.ts | 23 +++++++++++++++- src/io/import/processors/handleDicom.ts | 26 ++++++++++++++----- src/store/__tests__/dicom-web-store.spec.ts | 10 ++++--- src/store/dicom-web/dicom-web-store.ts | 13 ++++++---- 6 files changed, 69 insertions(+), 28 deletions(-) diff --git a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts index 65dc516ad..4010dab96 100644 --- a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts +++ b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts @@ -82,12 +82,15 @@ it('aborts its request and ends its streams when closed', async () => { expect(await bytesOf(fetcher.getStream())).toEqual(new Uint8Array()); }); -it('reports a missing resource', async () => { - const fetcher = new CachedStreamFetcher('https://example.test/missing', { - fetch: async () => new Response('gone', { status: 404 }), - }); - await expect(fetcher.connect()).rejects.toThrow( - 'https://example.test/missing' - ); - expect(fetcher.connected).toBe(false); -}); +it.each([404, 500])( + 'reports the HTTP status %i of a failed request', + async (status) => { + const fetcher = new CachedStreamFetcher('https://example.test/missing', { + fetch: async () => new Response('gone', { status }), + }); + await expect(fetcher.connect()).rejects.toThrow( + `HTTP ${status} for https://example.test/missing` + ); + expect(fetcher.connected).toBe(false); + } +); diff --git a/src/core/streaming/cachedStreamFetcher.ts b/src/core/streaming/cachedStreamFetcher.ts index f997e6071..1a702ba61 100644 --- a/src/core/streaming/cachedStreamFetcher.ts +++ b/src/core/streaming/cachedStreamFetcher.ts @@ -47,9 +47,7 @@ export class CachedStreamFetcher implements Fetcher { signal: request.signal, }); if (response.status !== 200) - throw new Error( - `The following resource could not be found: ${this.url}` - ); + throw new Error(`HTTP ${response.status} for ${this.url}`); if (!response.body) throw new Error('Did not receive a response body'); this.contentType = response.headers.get('content-type') ?? ''; this.contentDisposition = diff --git a/src/io/import/processors/__tests__/handleDicom.spec.ts b/src/io/import/processors/__tests__/handleDicom.spec.ts index 6c1e637f8..36aeb1093 100644 --- a/src/io/import/processors/__tests__/handleDicom.spec.ts +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -12,7 +12,12 @@ import handleDicom from '@/src/io/import/processors/handleDicom'; import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { Skip } from '@/src/utils/evaluateChain'; import { useMessageStore } from '@/src/store/messages'; -import { stripFileMeta, stripPreamble } from '@/tests/specs/syntheticDicom'; +import { + part10File, + rawElement, + stripFileMeta, + stripPreamble, +} from '@/tests/specs/syntheticDicom'; import { syntheticSlice, withoutPixelData } from '@/tests/dicomSourceFixtures'; import { StopSignal } from '@/src/core/streaming/cachedStreamFetcher'; import type { Fetcher } from '@/src/core/streaming/types'; @@ -195,6 +200,22 @@ describe('handleDicom', () => { } ); + it('skips an object that holds no image and says so', async () => { + const report = part10File( + '1.2.840.10008.5.1.4.1.1.88.11', + '1.2.826.0.1.3680043.10.997.88', + '1.2.840.10008.1.2.1', + rawElement(0x0008, 0x0060, 'CS', new TextEncoder().encode('SR')) + ); + + const result = await handleDicom(fileSource(report, 'report.dcm')); + + expect(result).toMatchObject({ type: 'ok' }); + expect(useMessageStore().messages[0].title).toBe( + 'DICOM file report.dcm holds no image (modality SR). It will be skipped.' + ); + }); + it('does not skip a non-RT modality whose name starts with R', async () => { const bytes = syntheticSlice({ modality: 'RG' }); diff --git a/src/io/import/processors/handleDicom.ts b/src/io/import/processors/handleDicom.ts index dcc403763..55513e218 100644 --- a/src/io/import/processors/handleDicom.ts +++ b/src/io/import/processors/handleDicom.ts @@ -1,5 +1,10 @@ import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; -import { getDatasetModality } from '@/src/dicom/core/metadata/datasetAccess'; +import { + getDatasetModality, + getDatasetTag, +} from '@/src/dicom/core/metadata/datasetAccess'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { IMPLICIT_VR_LITTLE_ENDIAN, type DicomLayout, @@ -79,6 +84,17 @@ async function readHeader(dataSource: DataSource, runtime: DicomRuntime) { /** * Reads a DICOM source's header and hands it on as an instance to import later. */ +/** Why a readable DICOM object is not imported, or null when it holds an image. */ +function whySkipped(dataset: DicomDataset, name: Maybe) { + const modality = getDatasetModality(dataset); + if (modality?.startsWith('RT')) + return `DICOM ${modality} modality is not supported. File ${name} will be skipped.`; + // Reports, key objects and directories carry no pixel matrix to allocate. + if (getDatasetTag(dataset, Tags.Rows) === undefined) + return `DICOM file ${name} holds no image${modality ? ` (modality ${modality})` : ''}. It will be skipped.`; + return null; +} + const handleDicom: ImportHandler = async (dataSource) => { if (!isDicom(dataSource)) return Skip; @@ -96,11 +112,9 @@ const handleDicom: ImportHandler = async (dataSource) => { }); reportLayout(name, instance.layout); - const modality = getDatasetModality(instance.dataset); - if (modality?.startsWith('RT')) { - useMessageStore().addWarning( - `DICOM ${modality} modality is not supported. File ${name} will be skipped.` - ); + const skipped = whySkipped(instance.dataset, name); + if (skipped) { + useMessageStore().addWarning(skipped); return asOkayResult(dataSource); } diff --git a/src/store/__tests__/dicom-web-store.spec.ts b/src/store/__tests__/dicom-web-store.spec.ts index dc203009c..609bd7679 100644 --- a/src/store/__tests__/dicom-web-store.spec.ts +++ b/src/store/__tests__/dicom-web-store.spec.ts @@ -128,17 +128,19 @@ describe('unsupported DICOMweb downloads', () => { describe('partly failed DICOMweb downloads', () => { beforeEach(() => setActivePinia(createPinia())); - it('shows the loaded volume and tells the user which files failed', async () => { + it('shows the loaded volume and names every failed file in one notice', async () => { const { select, store } = remoteSeries(); const retrieve = async () => [ new File([], 'good.dcm'), new File([], 'bad.dcm'), + new File([], 'worse.dcm'), ]; - const importSources = async ([good, bad]: Parameters< + const importSources = async ([good, bad, worse]: Parameters< typeof asOkayResult >[0][]) => [ asLoadableResult('volume-1', good, 'image'), asErrorResult(new Error('bad.dcm is not DICOM'), bad), + asErrorResult(new Error('worse.dcm is not DICOM'), worse), ]; await store.downloadVolume('series-uid', retrieve, importSources); @@ -147,9 +149,9 @@ describe('partly failed DICOMweb downloads', () => { expect(select).toHaveBeenCalledWith('volume-1'); expect(useMessageStore().messages).toEqual([ expect.objectContaining({ - title: expect.stringMatching(/may be incomplete/), + title: expect.stringMatching(/^2 of .* may be incomplete/), options: expect.objectContaining({ - details: expect.stringMatching(/bad\.dcm is not DICOM/), + details: 'bad.dcm is not DICOM\nworse.dcm is not DICOM', }), }), ]); diff --git a/src/store/dicom-web/dicom-web-store.ts b/src/store/dicom-web/dicom-web-store.ts index e5fb023aa..300ff77f1 100644 --- a/src/store/dicom-web/dicom-web-store.ts +++ b/src/store/dicom-web/dicom-web-store.ts @@ -89,12 +89,15 @@ function primaryVolumeResult(results: ImportDataSourcesResult[]) { failures[0]?.error ?? new Error('The series contains no supported image data') ); - failures.forEach(({ error }) => + // One notice for the series, however many of its files failed. + if (failures.length > 0) useMessageStore().addError( - 'Some files of the DICOM series failed to load; the volume may be incomplete', - { error } - ) - ); + `${failures.length} of the DICOM series' files failed to load; the volume may be incomplete`, + { + error: failures[0].error, + details: failures.map(({ error }) => error.message).join('\n'), + } + ); // A series holding overlapping acquisitions loads as several volumes; // show the one with the most slices rather than whichever import // happened to finish first. From 3d1b5e5d4e31e1cc0a4c9ca87b7be4b1bdd09dc2 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:04:15 -0500 Subject: [PATCH 30/32] fix(import): read a saved archive once when restoring its members --- .../import/__tests__/missingArchiveMember.spec.ts | 14 ++++++++++++++ src/io/import/processors/restoreStateFile.ts | 14 +++++++++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/io/import/__tests__/missingArchiveMember.spec.ts b/src/io/import/__tests__/missingArchiveMember.spec.ts index 3fd033806..38e41e4dd 100644 --- a/src/io/import/__tests__/missingArchiveMember.spec.ts +++ b/src/io/import/__tests__/missingArchiveMember.spec.ts @@ -8,6 +8,7 @@ import { import type { StateFileSetupResult } from '@/src/io/import/common'; import { ManifestSchema } from '@/src/io/state-file/schema'; import { useMessageStore } from '@/src/store/messages'; +import { Skip } from '@/src/utils/evaluateChain'; // --------------------------------------------------------------------------- // Regression: a state file whose archive is missing SOME of a dataset's files @@ -59,6 +60,19 @@ describe('restore with a partially missing dataset archive', () => { ]); }); + it('leaves a saved dataset archive to extraction, even when the archive holds a manifest', async () => { + const file = await stateZipMissingOneMember(); + + const result = await restoreStateFile({ + type: 'file', + file, + fileType: 'application/zip', + stateFileLeaf: { stateID: 'ds-ct', archivePaths: ['data/10/a.dcm'] }, + }); + + expect(result).toBe(Skip); + }); + it('the consolidated notice names a member missing from a dataset that still restored', async () => { await completeStateFileRestore( ManifestSchema.parse(manifest), diff --git a/src/io/import/processors/restoreStateFile.ts b/src/io/import/processors/restoreStateFile.ts index aba3fb298..cce7a00d5 100644 --- a/src/io/import/processors/restoreStateFile.ts +++ b/src/io/import/processors/restoreStateFile.ts @@ -9,6 +9,10 @@ import { ImportHandler, StateFileSetupResult, } from '@/src/io/import/common'; +import { + type DataSource, + findStateFileLeaves, +} from '@/src/io/import/dataSource'; import { MANIFEST, isStateFile } from '@/src/io/state-file/serialize'; import { partition, getURLBasename } from '@/src/utils'; import { basename } from '@/src/utils/path'; @@ -354,8 +358,16 @@ async function parseManifestFromJson(file: File) { return { manifestString, stateFiles: [] as FileEntry[] }; } +// Asking each member whether it is a session would read its archive whole. +const isSavedArchiveMember = (dataSource: DataSource) => + !!findStateFileLeaves(dataSource)[0]?.archivePaths?.length; + export const restoreStateFile: ImportHandler = async (dataSource) => { - if (dataSource.type === 'file' && (await isStateFile(dataSource.file))) { + if ( + dataSource.type === 'file' && + !isSavedArchiveMember(dataSource) && + (await isStateFile(dataSource.file)) + ) { const isJson = dataSource.fileType === 'application/json'; const { manifestString, stateFiles } = isJson ? await parseManifestFromJson(dataSource.file) From 577f456eec7c2efc7a2fe9f0dde957b36e1164f3 Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:04:23 -0500 Subject: [PATCH 31/32] fix(layers): accept NUL padded DICOM window values --- src/utils/__tests__/dicomWindowRange.spec.ts | 1 + src/utils/dicomWindowRange.ts | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/__tests__/dicomWindowRange.spec.ts b/src/utils/__tests__/dicomWindowRange.spec.ts index f278af565..bb383476d 100644 --- a/src/utils/__tests__/dicomWindowRange.spec.ts +++ b/src/utils/__tests__/dicomWindowRange.spec.ts @@ -16,6 +16,7 @@ describe('DICOM window display range', () => { it.each([ ['unsigned identity', '2048', '4096', undefined, [0, 4095]], ['signed window', '0', '100', 'LINEAR', [-50, 49]], + ['NUL padded values', '7758\0', '13964\0', undefined, [776, 14739]], ['fractional exact window', '0.5', '1', 'LINEAR_EXACT', [0, 1]], ['sub-unit exact width', '0', '0.25', 'LINEAR_EXACT', [-0.125, 0.125]], ] as const)( diff --git a/src/utils/dicomWindowRange.ts b/src/utils/dicomWindowRange.ts index 22aec4143..a61a6b052 100644 --- a/src/utils/dicomWindowRange.ts +++ b/src/utils/dicomWindowRange.ts @@ -1,4 +1,5 @@ import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; type DicomMetadata = Iterable | null | undefined; @@ -7,7 +8,8 @@ const decimal = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/; const parseValues = (value?: string) => value ?.split('\\') - .map((token) => (decimal.test(token.trim()) ? Number(token) : NaN)) ?? []; + .map(trimDicomPadding) + .map((token) => (decimal.test(token) ? Number(token) : NaN)) ?? []; function readWindow(metadata: DicomMetadata) { if (!metadata) return undefined; From 49e1b48192e199c2bbb645d4d83679859db81fbb Mon Sep 17 00:00:00 2001 From: Paul Elliott Date: Sun, 22 Nov 2026 06:04:31 -0500 Subject: [PATCH 32/32] fix(camera): hold a restored camera against auto-fit --- .../__tests__/view-camera-restore.spec.ts | 23 +++++++++++++++++++ src/store/view-configs/camera.ts | 3 ++- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 src/store/__tests__/view-camera-restore.spec.ts diff --git a/src/store/__tests__/view-camera-restore.spec.ts b/src/store/__tests__/view-camera-restore.spec.ts new file mode 100644 index 000000000..9b00f5527 --- /dev/null +++ b/src/store/__tests__/view-camera-restore.spec.ts @@ -0,0 +1,23 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import { useViewCameraStore } from '@/src/store/view-configs/camera'; + +describe('restoring a saved camera', () => { + beforeEach(() => setActivePinia(createPinia())); + + it.each([ + ['holds its zoom when the session saved no auto-fit choice', {}, false], + ['keeps auto-fit when the session saved it on', { autoFit: true }, true], + ])('%s', (_name, saved, autoFit) => { + const cameras = useViewCameraStore(); + + cameras.deserialize('view', { + image: { camera: { parallelScale: 7, ...saved } }, + }); + + expect(cameras.getConfig('view', 'image')).toMatchObject({ + parallelScale: 7, + autoFit, + }); + }); +}); diff --git a/src/store/view-configs/camera.ts b/src/store/view-configs/camera.ts index b4a2e95a0..f6bba1379 100644 --- a/src/store/view-configs/camera.ts +++ b/src/store/view-configs/camera.ts @@ -120,7 +120,8 @@ export const useViewCameraStore = defineStore('viewCamera', () => { const deserialize = (viewID: string, config: Record) => { Object.entries(config).forEach(([dataID, viewConfig]) => { if (viewConfig.camera) { - updateConfig(viewID, dataID, viewConfig.camera); + // A saved camera is a placed one: a resize must not refit it. + updateConfig(viewID, dataID, { autoFit: false, ...viewConfig.camera }); markCameraAsInitialized(viewID, dataID); } });