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/.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..ca3dbe9d5 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -171,7 +171,6 @@ const E2E_TIMEOUT_DEBT = [ export default tseslint.config( { ignores: [ - 'src/io/itk-dicom/emscripten-build/**', 'src/io/resample/emscripten-build/**', '**/*.d.ts', 'dist/**', @@ -292,7 +291,7 @@ export default tseslint.config( }, }, { - files: ['src/vtk/**/*.{js,ts}'], + files: ['src/vtk/**/*.{js,ts}', 'src/dicom/vtk/**/*.{js,ts}'], rules: { 'no-param-reassign': [ 'error', @@ -380,7 +379,7 @@ export default tseslint.config( { files: ['src/**/*.{js,ts,vue}'], ignores: [ - 'src/**/__tests__/**', + '**/__tests__/**', 'src/**/*.{spec,test}.{js,ts}', 'src/**/*.d.ts', '**/emscripten-build/**', @@ -395,5 +394,45 @@ 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: ['src/dicom/core/**/*.{js,ts}'], + ignores: ['**/__tests__/**'], + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: + '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/|@kitware/vtk\\.js(?:/|$)|(\\.\\./){2}|\\.\\./vtk(?:/|$))', + message: + 'DICOM core cannot depend on application code, UI frameworks, vtk.js or the DICOM vtk directory.', + }, + ], + }, + ], + }, + }, + { + files: ['src/dicom/vtk/**/*.{js,ts}'], + ignores: ['**/__tests__/**'], + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: + '^(@/|@src/|vue(?:/|$)|pinia(?:/|$)|@vueuse/|(\\.\\./){2})', + message: + 'DICOM vtk cannot depend on application code, application state or UI frameworks.', + }, + ], + }, + ], + }, + }, eslintConfigPrettier ); diff --git a/package-lock.json b/package-lock.json index ca3c577b5..a827a3940 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,13 +46,12 @@ "core-js": "3.47.0", "cors": "^2.8.5", "cross-env": "^10.1.0", - "dicom-parser": "^1.8.21", + "dcmjs": "^0.52.0", "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 +542,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 +7655,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 +9842,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 +10320,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", @@ -10609,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", @@ -13296,6 +13359,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 +13469,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 +15993,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..d6d5ad55b 100644 --- a/package.json +++ b/package.json @@ -22,10 +22,8 @@ "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,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", @@ -73,13 +71,12 @@ "core-js": "3.47.0", "cors": "^2.8.5", "cross-env": "^10.1.0", - "dicom-parser": "^1.8.21", + "dcmjs": "^0.52.0", "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/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/actions/loadUserFiles.ts b/src/actions/loadUserFiles.ts index 2b76ba54e..d875ffa52 100644 --- a/src/actions/loadUserFiles.ts +++ b/src/actions/loadUserFiles.ts @@ -7,6 +7,7 @@ import { } from '@/src/io/import/dataSource'; import useLoadDataStore from '@/src/store/load-data'; import { useDICOMStore } from '@/src/store/datasets-dicom'; +import { useImageCacheStore } from '@/src/store/image-cache'; import { useLayersStore } from '@/src/store/datasets-layers'; import { useSegmentationStore } from '@/src/segmentation/store'; import { wrapInArray, nonNullable, partition } from '@/src/utils'; @@ -276,8 +277,13 @@ export type DataSourceImporter = ( sources: DataSource[] ) => Promise; -export function showImportedData(results: ImportResult[]) { +export function showImportedData(importResults: ImportResult[]) { const loadDataStore = useLoadDataStore(); + const { imageById } = useImageCacheStore(); + // A later import can dissolve a volume before its import shows it. + const results = importResults.filter( + (result) => !isVolumeResult(result) || result.dataID in imageById + ); const primaryDataSource = findBaseDataSource( results, diff --git a/src/components/PatientStudyVolumeBrowser.vue b/src/components/PatientStudyVolumeBrowser.vue index 8f8453489..e446fa7a5 100644 --- a/src/components/PatientStudyVolumeBrowser.vue +++ b/src/components/PatientStudyVolumeBrowser.vue @@ -95,51 +95,67 @@ export default defineComponent({ const thumbnailCache = reactive>({}); watch( - volumeKeys, - (keys) => { - keys.forEach(async (key) => { - const cacheKey = dicomCacheKey(key); - if (cacheKey in thumbnailCache) { - return; - } - - const image = imageCacheStore.imageById[key]; - if (!image) return; + () => + volumeKeys.value.map((key) => ({ + key, + image: imageCacheStore.imageById[key], + info: dicomStore.volumeInfo[key], + })), + (entries, previousEntries, onCleanup) => { + let active = true; + onCleanup(() => { + active = false; + }); + const previousByKey = new Map( + previousEntries?.map((entry) => [entry.key, entry]) + ); - try { - const thumb = await image.getThumbnail(); - if (thumb) { - thumbnailCache[cacheKey] = { kind: 'image', value: thumb }; - } else { - thumbnailCache[cacheKey] = { - kind: 'text', - value: dicomStore.volumeInfo[key].Modality, - }; + entries + .filter(({ key, image, info }) => { + const cacheKey = dicomCacheKey(key); + const previous = previousByKey.get(key); + if (previous?.image !== image || previous?.info !== info) { + delete thumbnailCache[cacheKey]; } - } catch (err) { - if (err instanceof Error) { - const messageStore = useMessageStore(); - messageStore.addError('Failed to generate thumbnails', { - error: err, - details: `${err}. More details can be found in the developer's console.`, - }); + return image && info && !(cacheKey in thumbnailCache); + }) + .forEach(async ({ key, image, info }) => { + const cacheKey = dicomCacheKey(key); + + const isCurrent = () => + active && + 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; + thumbnailCache[cacheKey] = thumb + ? { kind: 'image', value: thumb } + : modality; + } catch (err) { + if (!isCurrent()) return; + if (err instanceof Error && err.name !== 'AbortError') { + useMessageStore().addError('Failed to generate thumbnails', { + error: err, + details: `${err}. More details can be found in the developer's console.`, + }); + } + thumbnailCache[cacheKey] = modality; } - thumbnailCache[cacheKey] = { - kind: 'text', - value: dicomStore.volumeInfo[key].Modality, - }; - } - }); + }); // deletion case - const lookup = new Set(keys.map((key) => dicomCacheKey(key))); + const lookup = new Set(entries.map(({ key }) => dicomCacheKey(key))); Object.keys(thumbnailCache).forEach((key) => { if (!lookup.has(key)) { delete thumbnailCache[key]; } }); }, - { immediate: true, deep: true } + { immediate: true } ); // --- selection --- // diff --git a/src/components/__tests__/ControlsStripTools.enFace.spec.ts b/src/components/__tests__/ControlsStripTools.enFace.spec.ts index 139f039aa..943a8ec0f 100644 --- a/src/components/__tests__/ControlsStripTools.enFace.spec.ts +++ b/src/components/__tests__/ControlsStripTools.enFace.spec.ts @@ -13,6 +13,7 @@ import { activateEnFace, createOCTFixture, loadOCT, + volumeOf, } from '@/tests/unit/octFixture'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; @@ -60,7 +61,7 @@ describe('En face contrast toolbar availability', () => { ); it('updates the disabled reason as metadata arrives and enables contrast once real OCT pixels finish loading', async () => { - const fixture = createOCTFixture({ deferDecode: true }); + const fixture = await createOCTFixture({ deferDecode: true }); decodeReleases.push(fixture.releaseDecode); useImageCacheStore().addProgressiveImage(fixture.image, { id: 'pending' }); const wrapper = mountToolbar('pending'); @@ -68,8 +69,7 @@ describe('En face contrast toolbar availability', () => { expect( windowAction(wrapper).get(':scope > [role="tooltip"]').text() ).toMatch(/complete volume/); - await fixture.chunk.loadMeta(); - await fixture.image.addChunks([fixture.chunk]); + fixture.image.setVolume(volumeOf([fixture.instance])); await nextTick(); expect(wrapper.get(windowTool).attributes('disabled')).toBeDefined(); expect( @@ -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 new file mode 100644 index 000000000..3a9bffa0c --- /dev/null +++ b/src/components/__tests__/PatientStudyVolumeBrowser.thumbnails.spec.ts @@ -0,0 +1,321 @@ +import { + afterEach, + beforeEach, + describe, + expect, + it, + onTestFinished, + vi, +} from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +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 { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; +import { + allocateVolume, + type Volume, +} 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'; +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'; + +const messageTitles = () => + useMessageStore().messages.map((message) => message.title); + +enableAutoUnmount(afterEach); + +const Slot = defineComponent({ template: '
' }); +const stubs = { + GroupableItem: { + template: '
', + }, + PersistentOverlay: Slot, + VImg: { + props: ['src'], + template: + '
', + }, + VProgressCircular: { template: '
' }, + VContainer: Slot, + VRow: Slot, + VCol: Slot, + VCard: Slot, + VCardText: Slot, + VCheckbox: true, + VBtn: Slot, + VMenu: Slot, + VList: Slot, + VListItem: { template: '' }, + VIcon: true, + VTooltip: true, + VSpacer: true, +}; + +function mountBrowser() { + const dicom = useDICOMStore(); + const Host = defineComponent(() => () => { + const volumeKeys = Object.keys(dicom.volumeInfo); + return volumeKeys.length + ? h(PatientStudyVolumeBrowser, { volumeKeys }) + : h('p', 'No volumes'); + }); + return mount(Host, { global: { stubs } }); +} + +const decoded = (): DecodedPixels => ({ + size: [1, 1, 1], + data: new Uint16Array([1]), + components: 1, +}); + +const sliceInstance = (z = 0) => + instanceFor( + datasetFromTags( + Object.entries({ + '00080060': 'CT', + '00080018': `1.2.3.${z}`, + '00200032': `0\\0\\${z}`, + '0008103E': 'Pending volume', + '00200011': '1', + '0020000D': '1.2.3.4', + '0020000E': '1.2.3.5', + '00100020': 'patient', + '00200037': '1\\0\\0\\0\\1\\0', + '00280010': '1', + '00280011': '1', + '00280030': '1\\1', + '00280101': '16', + '00280103': '0', + }) + ), + fromBlob(new Blob(['pixels'])) + ); + +// The thumbnail is read from the volume, so it waits on the volume's decode. +function importPendingThumbnail() { + const decode = defer(); + const started = defer(); + const runtime = createDicomRuntime( + decodingWith(() => { + started.resolve(); + return decode.promise; + }) + ); + const image = new DicomVolumeImage({ + runtime, + encodeThumbnail: () => 'data:image/png;base64,current', + }); + const result = useDICOMStore().importInstances([sliceInstance()], { + createImage: () => image, + }); + onTestFinished(() => { + decode.resolve(decoded()); + runtime.dispose(); + }); + return { id: Object.keys(result.volumes)[0], image, decode, started }; +} + +function expectCurrentThumbnail(wrapper: ReturnType) { + expect(wrapper.get('img').attributes('src')).toBe( + 'data:image/png;base64,current' + ); + expect(wrapper.find('[role="progressbar"]').exists()).toBe(false); + expect(messageTitles()).toEqual([]); +} + +function cacheImage(id: string) { + const image = new LoadedVtkImage(vtkImageData.newInstance(), id); + useImageCacheStore().addProgressiveImage(image, { id }); + return image; +} + +describe('volume browser thumbnail lifetime', () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + afterEach(async () => { + const cache = useImageCacheStore(); + [...cache.imageIds].forEach((id) => cache.removeImage(id)); + await flushPromises(); + vi.restoreAllMocks(); + }); + + it('shows a decoded thumbnail', async () => { + const { started, decode } = importPendingThumbnail(); + const wrapper = mountBrowser(); + await started.promise; + expect(wrapper.find('[role="progressbar"]').exists()).toBe(true); + + decode.resolve(decoded()); + await flushPromises(); + + expectCurrentThumbnail(wrapper); + }); + + it('shows the modality when no thumbnail is available', async () => { + seatVolume('empty', { Modality: 'MR' }); + cacheImage('empty'); + const wrapper = mountBrowser(); + await flushPromises(); + + expect(wrapper.get('.thumbnail-container').text()).toContain('MR'); + expect(wrapper.find('[role="progressbar"]').exists()).toBe(false); + expect(messageTitles()).toEqual([]); + }); + + it('reports a failed decode once, as a load error, and shows the modality', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + const { started, decode } = importPendingThumbnail(); + const wrapper = mountBrowser(); + await started.promise; + + decode.reject(new Error('Decoder failed')); + await flushPromises(); + + expect(wrapper.get('.thumbnail-container').text()).toContain('CT'); + expect(wrapper.find('[role="progressbar"]').exists()).toBe(false); + expect(messageTitles()).toEqual(['Error loading Pending volume']); + }); + + it.each([false, true])( + 'keeps Delete quiet during decoding when another volume remains: %s', + async (keepBrowser) => { + const { id, started, decode } = importPendingThumbnail(); + if (keepBrowser) { + seatVolume('remaining'); + cacheImage('remaining'); + } + const wrapper = mountBrowser(); + await started.promise; + + const card = wrapper + .findAll('.volume-card') + .find((item) => item.text().includes('Pending volume'))!; + const deleteButton = card + .findAll('button') + .find((button) => button.text() === 'Delete')!; + await deleteButton.trigger('click'); + await flushPromises(); + + expect(wrapper.text()).not.toContain('Pending volume'); + expect(wrapper.findComponent(PatientStudyVolumeBrowser).exists()).toBe( + keepBrowser + ); + expect(useDICOMStore().volumeInfo[id]).toBeUndefined(); + expect(useImageCacheStore().imageById[id]).toBeUndefined(); + expect(messageTitles()).toEqual([]); + + decode.resolve(decoded()); + await flushPromises(); + expect(wrapper.find('img').exists()).toBe(false); + expect(messageTitles()).toEqual([]); + } + ); + + it('settles a thumbnail after a growth is undone while it decodes', async () => { + 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); + 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); + }); + + it('reports no thumbnail failure after the browser unmounts', async () => { + const { started, decode } = importPendingThumbnail(); + const wrapper = mountBrowser(); + await started.promise; + + wrapper.unmount(); + decode.reject(new Error('Late decoder failure')); + await flushPromises(); + + expect(messageTitles()).not.toContain('Failed to generate thumbnails'); + }); + + it.each([ + ['image', 'success'], + ['record', 'empty'], + ['image', 'failure'], + ])( + 'keeps the replacement %s thumbnail after a late %s', + async (replacement, outcome) => { + seatVolume('volume'); + const image = cacheImage('volume'); + const pending = defer(); + vi.spyOn(image, 'getThumbnail') + .mockReturnValueOnce(pending.promise) + .mockResolvedValue('data:image/png;base64,replacement'); + const wrapper = mountBrowser(); + + if (replacement === 'image') { + useImageCacheStore().removeImage('volume'); + vi.spyOn(cacheImage('volume'), 'getThumbnail').mockResolvedValue( + 'data:image/png;base64,replacement' + ); + } else { + seatVolume('volume', { Modality: 'MR' }); + } + await flushPromises(); + expect(wrapper.get('img').attributes('src')).toBe( + 'data:image/png;base64,replacement' + ); + + if (outcome === 'failure') { + pending.reject(new Error('Obsolete thumbnail failed')); + } else { + pending.resolve( + outcome === 'empty' ? null : 'data:image/png;base64,obsolete' + ); + } + await flushPromises(); + expect(wrapper.get('img').attributes('src')).toBe( + 'data:image/png;base64,replacement' + ); + expect(messageTitles()).toEqual([]); + } + ); + + it('refreshes a completed thumbnail when its volume record changes', async () => { + seatVolume('volume', { Modality: 'CT' }); + const image = cacheImage('volume'); + const thumbnail = vi + .spyOn(image, 'getThumbnail') + .mockResolvedValue('data:image/png;base64,previous'); + const wrapper = mountBrowser(); + await flushPromises(); + expect(wrapper.get('img').attributes('src')).toBe( + 'data:image/png;base64,previous' + ); + + thumbnail.mockResolvedValue(null); + seatVolume('volume', { Modality: 'MR' }); + await flushPromises(); + + expect(wrapper.find('img').exists()).toBe(false); + expect(wrapper.get('.thumbnail-container').text()).toContain('MR'); + }); +}); diff --git a/src/components/__tests__/PlayControls.spec.ts b/src/components/__tests__/PlayControls.spec.ts index 51afe8c76..e32123b39 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 '@/src/dicom/core/metadata/dicomTags'; 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 b28346ff5..1f285020c 100644 --- a/src/components/vtk/VtkBaseVolumeRepresentation.vue +++ b/src/components/vtk/VtkBaseVolumeRepresentation.vue @@ -37,10 +37,8 @@ import { onVTKEvent } from '@/src/composables/onVTKEvent'; import { useCroppingEffect } from '@/src/composables/useCroppingEffect'; import { useCropStore } from '@/src/store/tools/crop'; import { useEventListener } from '@vueuse/core'; -import { - ChunkImage, - type ChunkLoadedInfo, -} from '@/src/core/streaming/chunkImage'; +import type DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; +import type { Extent } from '@/src/dicom/core/volume/loadVolume'; interface Props { viewId: string; @@ -85,13 +83,13 @@ rep.property.setSpecular(DEFAULT_SPECULAR); }); // watch for updated extents -const updatedExtents = shallowRef>([]); +const updatedExtents = shallowRef([]); useEventListener( - // safely assume ChunkImage. If not, the event will never be triggered - image as Ref, - 'chunkLoad', - (info: ChunkLoadedInfo) => { - updatedExtents.value = [...updatedExtents.value, info.updatedExtent]; + // Only a DICOM volume emits this; other images never trigger it. + image as Ref, + 'extentLoaded', + (extent: Extent) => { + updatedExtents.value = [...updatedExtents.value, extent]; } ); diff --git a/src/core/cine/DicomCineImage.ts b/src/core/cine/DicomCineImage.ts index c1a33b89b..6cd26946a 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'; @@ -11,12 +11,15 @@ import { BaseProgressiveImage, ProgressiveImageEvents, } from '@/src/core/progressiveImage'; +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 { - CineHeader, - CineParseResult, + type CineHeader, isNativeTransferSyntax, - isSupportedCineTransferSyntax, -} from './parseCineDicom'; + readCineFrames, + readCineHeader, +} from './cineInstance'; import { DecodedFrame, FrameCache, @@ -24,12 +27,11 @@ import { decodeJpegFrame, decodeNativeFrame, } from './frameCache'; -import { unitToMm } from '@/src/core/streaming/dicom/ultrasoundRegion'; -function pickPixelSpacing(header: CineHeader): [number, number] { +function pickPixelSpacing(header: CineHeader) { for (const r of header.regions) { - 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) continue; const { physicalDeltaX: dx, physicalDeltaY: dy } = r; if (!dx || !dy || !Number.isFinite(dx) || !Number.isFinite(dy)) continue; @@ -44,26 +46,52 @@ function pickPixelSpacing(header: CineHeader): [number, number] { return [1, 1]; } +/** 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(); @@ -77,7 +105,7 @@ export default class DicomCineImage extends BaseProgressiveImage { const imageData = vtkImageData.newInstance(); imageData.setExtent([0, cols - 1, 0, rows - 1, 0, 0]); // Spacing falls back to 1 when no region declares a spatial unit, so - // rulers report pixels (documented v1 behavior). + // rulers report pixels. const [spacingX, spacingY] = pickPixelSpacing(header); imageData.setSpacing([spacingX, spacingY, 1]); imageData.setOrigin([0, 0, 0]); @@ -126,14 +154,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) => { @@ -156,11 +176,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(); } @@ -171,34 +192,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. @@ -258,16 +265,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, { @@ -278,17 +301,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..5115adf83 100644 --- a/src/core/cine/__tests__/DicomCineImage.spec.ts +++ b/src/core/cine/__tests__/DicomCineImage.spec.ts @@ -1,135 +1,204 @@ import { describe, expect, it } from 'vitest'; - +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'; -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()); + +/** 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 }; +}; - 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 image = new DicomCineImage(offlineOnce()); + 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 image = new DicomCineImage( + offlineOnce(), + 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..fd1456e8d 100644 --- a/src/core/cine/__tests__/cineFixtures.ts +++ b/src/core/cine/__tests__/cineFixtures.ts @@ -1,12 +1,73 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; +import { + SOP_CLASS_ULTRASOUND_MULTIFRAME, + Tags, +} 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'; -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, + 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 +76,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 +83,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..ebb79852c --- /dev/null +++ b/src/core/cine/__tests__/cineInstance.spec.ts @@ -0,0 +1,228 @@ +import { describe, expect, it } from 'vitest'; +import { fromBlob } from '@/src/dicom/core/source/byteSource'; +import { readInstance } from '@/src/dicom/core/instance/readInstance'; +import { + SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, + Tags, +} from '@/src/dicom/core/metadata/dicomTags'; +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], + 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, + planarConfiguration: 0, + photometricInterpretation: 'MONOCHROME2', + pixelSpacing: [1.8, 0.45], + frameTimeMs: null, + 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', + [Tags.PlanarConfiguration]: '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..abe86f7fa --- /dev/null +++ b/src/core/cine/cineInstance.ts @@ -0,0 +1,150 @@ +import { + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, +} 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 '@/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'; + +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 type CineHeader = { + transferSyntaxUID: string; + rows: number; + cols: number; + numberOfFrames: number; + samplesPerPixel: number; + planarConfiguration: number; + photometricInterpretation: string; + pixelSpacing: [number, number] | null; + frameTimeMs: number | null; + 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; + 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), + planarConfiguration: countOr(dataset, Tags.PlanarConfiguration, 0), + photometricInterpretation: text(dataset, Tags.PhotometricInterpretation), + pixelSpacing: positivePair(dataset, Tags.PixelSpacing), + frameTimeMs: finiteOrNull(dataset, Tags.FrameTime), + 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 && + SUPPORTED_TRANSFER_SYNTAXES.has(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/dicomTags.ts b/src/core/dicomTags.ts deleted file mode 100644 index 585f43ac7..000000000 --- a/src/core/dicomTags.ts +++ /dev/null @@ -1,77 +0,0 @@ -type Tag = { - name: string; - tag: string; -}; - -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: 'SeriesDescription', tag: '0008|103e' }, - { 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: 'ImagePositionPatient', tag: '0020|0032' }, - { name: 'ImageOrientationPatient', tag: '0020|0037' }, - { name: 'PixelSpacing', tag: '0028|0030' }, - { name: 'SpacingBetweenSlices', tag: '0018|0088' }, - { 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: '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 -// US-MONO2-8-8x-execho) still emit the retired UID. -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 { - const trimmed = uid.trim(); - return ( - trimmed === SOP_CLASS_ULTRASOUND_MULTIFRAME || - trimmed === SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED - ); -} - -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/src/core/stateMachine.ts b/src/core/stateMachine.ts deleted file mode 100644 index 9915c22f8..000000000 --- a/src/core/stateMachine.ts +++ /dev/null @@ -1,113 +0,0 @@ -import mitt, { Emitter } from 'mitt'; - -/** - * The payload of an update event. - */ -export type UpdateEvent = { - state: S; - prevState: S; - event: TE; - data?: any; -}; - -/** - * The available events emitted internally by a state machine. - */ -export type StateMachineEvents = { - update: UpdateEvent; -}; - -/** - * The available state transitions. - */ -export type StateTransitions = Partial< - Record>> ->; - -/** - * Tests to see if a state event is entering a given state. - * @param event - * @param state - * @returns - */ -export function enters(event: UpdateEvent, state: S) { - return event.state === state; -} - -/** - * Tests to see if a state event is leaving a given state. - * @param event - * @param state - * @returns - */ -export function leaves(event: UpdateEvent, state: S) { - return event.prevState === state; -} - -/** - * Represents a state machine. - */ -export default class StateMachine< - S extends string, - TE extends string, - E extends StateMachineEvents = StateMachineEvents, -> { - private _events: Emitter; - private _state: S; - private _transitions: StateTransitions; - - constructor(initState: S, transitions: StateTransitions) { - this._state = initState; - this._transitions = transitions; - this._events = mitt(); - } - - get state() { - return this._state; - } - - /** - * Send an event to the state machine to trigger a transition. - * - * Event data will be broadcasted to update subscribers. - * @param event - * @param eventData - * @returns - */ - send(event: TE, eventData?: any) { - if (!(this._state in this._transitions)) return; - const stateTransitions = this._transitions[this._state]!; - - if (!(event in stateTransitions)) return; - const prevState = this._state; - this._state = stateTransitions[event]!; - this._events.emit('update', { - state: this._state, - prevState, - event, - data: eventData, - }); - } - - /** - * Subscribe to the update event. - * - * Returns a function to unsubscribe. - * @param callback - * @returns - */ - subscribe(callback: (event: UpdateEvent) => void) { - this._events.on('update', callback); - return () => { - this.unsubscribe(callback); - }; - } - - /** - * Unsubscribe from the update event. - * @param callback - */ - unsubscribe(callback: (event: UpdateEvent) => void) { - this._events.off('update', callback); - } -} diff --git a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts index d7eb46216..4010dab96 100644 --- a/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts +++ b/src/core/streaming/__tests__/cachedStreamFetcher.spec.ts @@ -1,120 +1,96 @@ -import { RequestPool } from '@/src/core/streaming/requestPool'; -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 bytes = new Uint8Array(size); - let offset = 0; - chunks.forEach((chunk) => { - bytes.set(chunk, offset); - offset += chunk.length; - }); - return bytes; -}; +const SOURCE = Uint8Array.from( + { length: 3 * 4096 + 123 }, + (_, index) => (index * 31) % 251 +); -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 pool = new RequestPool(1, fetchRange); - const fetcher = new CachedStreamFetcher('https://example.test/data', { - fetch: pool.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()); + +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(); - await fetcher.connect(); - expect(requestedRanges).toEqual([null, `bytes=${resumeAt}-`]); + 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(); +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.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/__tests__/chunkStateMachine.spec.ts b/src/core/streaming/__tests__/chunkStateMachine.spec.ts deleted file mode 100644 index 4933fd158..000000000 --- a/src/core/streaming/__tests__/chunkStateMachine.spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { - ChunkState, - ChunkStateMachine, - TransitionEvent, -} from '@/src/core/streaming/chunkStateMachine'; -import { describe, expect, it } from 'vitest'; - -describe('chunk', () => { - describe('state machine', () => { - it('should transition properly', () => { - const machine = new ChunkStateMachine(); - - expect(machine.state).to.equal(ChunkState.Init); - - [ - TransitionEvent.LoadData, - TransitionEvent.MetaLoaded, - TransitionEvent.DataLoaded, - TransitionEvent.Cancel, - ].forEach((event) => { - machine.send(event); - expect(machine.state).to.equal(ChunkState.Init); - }); - - machine.send(TransitionEvent.LoadMeta); - expect(machine.state).to.equal(ChunkState.MetaLoading); - - machine.send(TransitionEvent.MetaLoaded); - expect(machine.state).to.equal(ChunkState.MetaOnly); - - machine.send(TransitionEvent.LoadData); - expect(machine.state).to.equal(ChunkState.DataLoading); - - machine.send(TransitionEvent.DataLoaded); - expect(machine.state).to.equal(ChunkState.Loaded); - }); - }); -}); diff --git a/src/core/streaming/__tests__/dicomChunkImage.spec.ts b/src/core/streaming/__tests__/dicomChunkImage.spec.ts deleted file mode 100644 index ee6f66161..000000000 --- a/src/core/streaming/__tests__/dicomChunkImage.spec.ts +++ /dev/null @@ -1,507 +0,0 @@ -import { describe, it, expect, vi } from 'vitest'; -import { Chunk } from '@/src/core/streaming/chunk'; -import { ChunkState } from '@/src/core/streaming/chunkStateMachine'; -import { Tags } from '@/src/core/dicomTags'; -import DicomChunkImage, { - DicomChunkImageInit, -} from '@/src/core/streaming/dicomChunkImage'; -import { ChunkStatus } from '@/src/core/streaming/chunkImage'; -import { - US_UNIT_CENTIMETERS, - UltrasoundRegions, -} from '@/src/core/streaming/dicom/ultrasoundRegion'; - -const ROWS = 2; -const COLUMNS = 2; -const PIXELS_PER_SLICE = ROWS * COLUMNS; -const PUBLIC_DSC_SLOPE = 112067.85375182; - -function metadataFor(z: number, overrides: Record = {}) { - const metadata = [ - [Tags.SOPInstanceUID, `1.2.3.${z}`], - [Tags.ImagePositionPatient, `0\\0\\${z}`], - [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], - [Tags.Rows, String(ROWS)], - [Tags.Columns, String(COLUMNS)], - [Tags.PixelSpacing, '1\\1'], - [Tags.BitsStored, '16'], - [Tags.PixelRepresentation, '0'], - [Tags.SamplesPerPixel, '1'], - ] as Array<[string, string]>; - Object.entries(overrides).forEach(([tag, value]) => { - const existing = metadata.find((entry) => entry[0] === tag); - if (existing) existing[1] = value; - else metadata.push([tag, value]); - }); - return metadata; -} - -// The slice's z position is also its pixel value, so the decoded contents of a -// slice identify which chunk it came from. -async function makeLoadedChunk( - z: number, - overrides: Record = {}, - ultrasoundRegions?: UltrasoundRegions -) { - const meta = metadataFor(z, overrides); - const chunk = new Chunk({ - metaLoader: { - meta, - metaBlob: new Blob([`meta-${z}`]), - ultrasoundRegions, - load: () => {}, - stop: () => {}, - }, - dataLoader: { - data: new Blob([String(z)]), - load: () => {}, - stop: () => {}, - }, - }); - await chunk.loadMeta(); - await chunk.loadData(); - expect(chunk.state).toBe(ChunkState.Loaded); - return chunk; -} - -function zOf(chunk: Chunk) { - const meta = Object.fromEntries(chunk.metadata!); - return Number(meta[Tags.ImagePositionPatient].split('\\')[2]); -} - -function splitAndSortByPosition(chunks: Chunk[]) { - return Promise.resolve({ - volume: [...chunks].sort((a, b) => zOf(a) - zOf(b)), - }); -} - -// Decodes a chunk to a constant frame, letting the test choose the array type. -function decodeTo(dataFor: (value: number) => ArrayLike) { - const read: DicomChunkImageInit['readDicomImage'] = async (file) => { - const value = Number(await file.text()); - return { - image: { - size: [COLUMNS, ROWS, 1], - data: dataFor(value) as Uint16Array, - imageType: { components: 1 }, - }, - }; - }; - return read; -} - -const readDicomImage = decodeTo((value) => - new Uint16Array(PIXELS_PER_SLICE).fill(value) -); - -function sliceOf(image: DicomChunkImage, index: number) { - const scalars = image.getVtkImageData().getPointData().getScalars(); - const data = scalars.getData(); - return Array.from( - data.slice(index * PIXELS_PER_SLICE, (index + 1) * PIXELS_PER_SLICE) - ); -} - -// A decode held open per pixel value, so a test settles each attempt in the -// order it chooses. A chunk redecoded after a re-sort has one settler per -// attempt, oldest first; a settler given an error rejects instead of resolving. -function deferredDecoder() { - const pending = new Map void>>(); - const read: DicomChunkImageInit['readDicomImage'] = async (file) => { - const value = Number(await file.text()); - return new Promise((resolve, reject) => { - const settlers = pending.get(value) ?? []; - settlers.push((err) => { - if (err) reject(err); - else - resolve({ - image: { - size: [COLUMNS, ROWS, 1], - data: new Uint16Array(PIXELS_PER_SLICE).fill(value), - imageType: { components: 1 }, - }, - }); - }); - pending.set(value, settlers); - }); - }; - return { pending, read }; -} - -// Chunk 3 starts alone in slot 0, then chunks 1 and 2 arrive and re-sort it -// into slot 2 while its first decode is still outstanding. `pending.get(3)` -// then holds the stale attempt at index 0 and the current one at index 1. -async function imageWithResortedChunk() { - const { pending, read } = deferredDecoder(); - const image = new DicomChunkImage({ - splitAndSort: splitAndSortByPosition, - readDicomImage: read, - }); - - const errors: number[] = []; - image.addEventListener('chunkError', ({ chunk }) => { - errors.push(zOf(chunk)); - }); - - const [first, second, third] = await Promise.all([ - makeLoadedChunk(1), - makeLoadedChunk(2), - makeLoadedChunk(3), - ]); - - // Start chunk 3 in slot 0, then move it to slot 2 while decoding. - await image.addChunks([third]); - await vi.waitFor(() => expect(pending.get(3)).toHaveLength(1)); - - await image.addChunks([first, second]); - await vi.waitFor(() => expect(pending.get(3)).toHaveLength(2)); - - return { image, pending, errors }; -} - -// Asserts the volume's leading slices hold the pixels of the chunks that -// belong in them; a chunk's z position is also its pixel value, and 0 is a -// slice no chunk has written. -function expectSliceValues(image: DicomChunkImage, values: number[]) { - values.forEach((value, index) => - expect(sliceOf(image, index)).toEqual(Array(PIXELS_PER_SLICE).fill(value)) - ); -} - -async function loadRejectingSeries( - read: DicomChunkImageInit['readDicomImage'] -) { - const image = new DicomChunkImage({ - splitAndSort: splitAndSortByPosition, - readDicomImage: read, - }); - const errors: unknown[] = []; - image.addEventListener('chunkError', ({ error }) => { - errors.push(error); - }); - const [valid, invalid] = await Promise.all([ - makeLoadedChunk(1, { [Tags.BitsStored]: '8' }), - makeLoadedChunk(2, { [Tags.BitsStored]: '8' }), - ]); - - await image.addChunks([valid, invalid]); - await vi.waitFor(() => - expect(image.getChunkStatuses()).toEqual([ - ChunkStatus.Loaded, - ChunkStatus.Errored, - ]) - ); - - expect(image.status.value).toBe('complete'); - expect(errors).toHaveLength(1); - expectSliceValues(image, [1, 0]); - image.dispose(); - return String(errors[0]); -} - -describe('DicomChunkImage', () => { - it('preserves exact modality-rescaled pixels from the public DSC series', async () => { - // The public frames are 200x230; reduced geometry keeps the exact encoding, - // rescale, and an observed stored-pixel maximum in a focused volume test. - const decoded = Float64Array.from([ - 0, - PUBLIC_DSC_SLOPE, - 2 * PUBLIC_DSC_SLOPE, - 65131 * PUBLIC_DSC_SLOPE, - ]); - const image = new DicomChunkImage({ - splitAndSort: splitAndSortByPosition, - readDicomImage: decodeTo(() => decoded), - }); - const frame = await makeLoadedChunk(1, { - [Tags.SeriesInstanceUID]: - '1.3.6.1.4.1.9590.100.1.2.284777661700890778225181143863199482857', - [Tags.RescaleSlope]: String(PUBLIC_DSC_SLOPE), - [Tags.RescaleIntercept]: '0', - }); - - await image.addChunks([frame]); - await vi.waitFor(() => - expect(image.getChunkStatuses()).toEqual([ChunkStatus.Loaded]) - ); - - const data = image.getVtkImageData().getPointData().getScalars().getData(); - expect(data).toBeInstanceOf(Float64Array); - expect(Array.from(data)).toEqual(Array.from(decoded)); - - image.dispose(); - }); - - // 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 }, - ])( - 'applies ultrasound region spacing only when nonzero and finite (deltaX $physicalDeltaX)', - async ({ physicalDeltaX, expected, warnings }) => { - const warn = vi.fn(); - const image = new DicomChunkImage({ - splitAndSort: splitAndSortByPosition, - readDicomImage, - warn, - }); - const frame = await makeLoadedChunk( - 1, - { [Tags.Modality]: 'US', [Tags.PixelSpacing]: '0.6\\0.7' }, - { - region: { - physicalDeltaX, - physicalDeltaY: 0.03, - physicalUnitsXDirection: US_UNIT_CENTIMETERS, - physicalUnitsYDirection: US_UNIT_CENTIMETERS, - }, - regionCount: 1, - } - ); - - await image.addChunks([frame]); - - const [x, y] = image.getVtkImageData().getSpacing(); - expect(x).toBeCloseTo(expected[0]); - expect(y).toBeCloseTo(expected[1]); - expect(warn).toHaveBeenCalledTimes(warnings); - image.dispose(); - } - ); - - it('settles after rejecting decoded values its integer buffer cannot hold', async () => { - const message = await loadRejectingSeries( - decodeTo((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'); - }); - - it('settles after rejecting fractional samples bound for an integer buffer', async () => { - const message = await loadRejectingSeries( - decodeTo((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('serializes concurrent additions so an older sort cannot drop newer chunks', async () => { - const pendingSorts: Array<{ - chunks: Chunk[]; - resolve: (volumes: Record) => void; - }> = []; - const deferredSplitAndSort: DicomChunkImageInit['splitAndSort'] = ( - chunks - ) => - new Promise((resolve) => { - pendingSorts.push({ chunks: [...chunks], resolve }); - }); - const finishSort = (index: number) => { - pendingSorts[index].resolve({ - volume: [...pendingSorts[index].chunks].sort((a, b) => zOf(a) - zOf(b)), - }); - }; - const image = new DicomChunkImage({ - splitAndSort: deferredSplitAndSort, - readDicomImage, - }); - const [first, second] = await Promise.all([ - makeLoadedChunk(1), - makeLoadedChunk(2), - ]); - - const olderAddition = image.addChunks([second]); - await vi.waitFor(() => expect(pendingSorts).toHaveLength(1)); - - const newerAddition = image.addChunks([first]); - await Promise.resolve(); - expect(pendingSorts).toHaveLength(1); - - finishSort(0); - await olderAddition; - await vi.waitFor(() => expect(pendingSorts).toHaveLength(2)); - expect(pendingSorts[1].chunks.map(zOf)).toEqual([2, 1]); - - finishSort(1); - await newerAddition; - await vi.waitFor(() => - expect(image.getChunkStatuses()).toEqual([ - ChunkStatus.Loaded, - ChunkStatus.Loaded, - ]) - ); - - expect(image.getChunks().map(zOf)).toEqual([1, 2]); - expectSliceValues(image, [1, 2]); - - image.dispose(); - }); - - it('decodes every loaded chunk into its sorted slice position', async () => { - const image = new DicomChunkImage({ - splitAndSort: splitAndSortByPosition, - readDicomImage, - }); - - const loads: Array<{ z: number; zRange: number[] }> = []; - image.addEventListener('chunkLoad', ({ chunk, updatedExtent }) => { - loads.push({ z: zOf(chunk), zRange: updatedExtent.slice(4) }); - }); - - const [first, second, third] = await Promise.all([ - makeLoadedChunk(1), - makeLoadedChunk(2), - makeLoadedChunk(3), - ]); - - await image.addChunks([first]); - await vi.waitFor(() => expect(loads.length).toBe(1)); - - // Arrival order deliberately differs from slice order. - await image.addChunks([third, second]); - await vi.waitFor(() => expect(loads.length).toBe(4)); - - expect(image.getChunks().map(zOf)).toEqual([1, 2, 3]); - // The first slice is redecoded because reallocation cleared its pixels. - expect(loads).toEqual([ - { z: 1, zRange: [0, 0] }, - { z: 1, zRange: [0, 0] }, - { z: 2, zRange: [1, 1] }, - { z: 3, zRange: [2, 2] }, - ]); - expectSliceValues(image, [1, 2, 3]); - - image.dispose(); - }); - - it('keeps a stale in-flight decode from clobbering the re-sorted volume', async () => { - const { image, pending } = await imageWithResortedChunk(); - - let loads = 0; - image.addEventListener('chunkLoad', () => { - loads += 1; - }); - - await vi.waitFor(() => { - expect(pending.get(1)).toHaveLength(1); - expect(pending.get(2)).toHaveLength(1); - }); - - // Complete the current decodes before the stale attempt. - pending.get(1)![0](); - pending.get(2)![0](); - pending.get(3)![1](); - await vi.waitFor(() => expect(loads).toBe(3)); - - pending.get(3)![0](); - await Promise.resolve(); - await Promise.resolve(); - expect(loads).toBe(3); - - expectSliceValues(image, [1, 2, 3]); - - image.dispose(); - }); - - it('does not let a stale success overwrite a replacement failure', async () => { - const { image, pending, errors } = await imageWithResortedChunk(); - - pending.get(1)![0](); - pending.get(2)![0](); - await vi.waitFor(() => - expect(image.getChunkStatuses()[1]).toBe(ChunkStatus.Loaded) - ); - - // Fail the attempt for the current allocation. - pending.get(3)![1](new Error('replacement decode failed')); - await vi.waitFor(() => expect(errors).toEqual([3])); - - expect(image.getChunkStatuses()).toEqual([ - ChunkStatus.Loaded, - ChunkStatus.Loaded, - ChunkStatus.Errored, - ]); - expect(sliceOf(image, 0)).toEqual(Array(PIXELS_PER_SLICE).fill(1)); - - // A late success from the previous allocation must be ignored. - pending.get(3)![0](); - await Promise.resolve(); - await Promise.resolve(); - expect(image.getChunkStatuses()[2]).toBe(ChunkStatus.Errored); - expect(sliceOf(image, 2)).toEqual(Array(PIXELS_PER_SLICE).fill(0)); - - image.dispose(); - }); - - it('does not let a stale failure overwrite a replacement success', async () => { - const { image, pending, errors } = await imageWithResortedChunk(); - - pending.get(1)![0](); - pending.get(2)![0](); - pending.get(3)![1](); - await vi.waitFor(() => - expect(image.getChunkStatuses()).toEqual([ - ChunkStatus.Loaded, - ChunkStatus.Loaded, - ChunkStatus.Loaded, - ]) - ); - - // A late failure from the previous allocation must be ignored. - pending.get(3)![0](new Error('stale decode failed')); - await Promise.resolve(); - await Promise.resolve(); - expect(errors).toEqual([]); - expect(image.getChunkStatuses()[2]).toBe(ChunkStatus.Loaded); - expect(sliceOf(image, 2)).toEqual(Array(PIXELS_PER_SLICE).fill(3)); - - image.dispose(); - }); - - it('reports a reallocated chunk as loading until its slice is rewritten', async () => { - const { pending, read } = deferredDecoder(); - const image = new DicomChunkImage({ - splitAndSort: splitAndSortByPosition, - readDicomImage: read, - }); - - const [first, second] = await Promise.all([ - makeLoadedChunk(1), - makeLoadedChunk(2), - ]); - - await image.addChunks([first]); - await vi.waitFor(() => expect(pending.get(1)).toHaveLength(1)); - pending.get(1)![0](); - await vi.waitFor(() => expect(image.status.value).toBe('complete')); - - // Reallocation cleared chunk 1, and neither replacement decode has run. - await image.addChunks([second]); - - expect(image.getChunkStatuses()).toEqual([ - ChunkStatus.Loading, - ChunkStatus.Loading, - ]); - expect(image.status.value).toBe('incomplete'); - expect(sliceOf(image, 0)).toEqual(Array(PIXELS_PER_SLICE).fill(0)); - - await vi.waitFor(() => { - expect(pending.get(1)).toHaveLength(2); - expect(pending.get(2)).toHaveLength(1); - }); - pending.get(1)![1](); - pending.get(2)![0](); - await vi.waitFor(() => expect(image.status.value).toBe('complete')); - expectSliceValues(image, [1, 2]); - - image.dispose(); - }); -}); diff --git a/src/core/streaming/__tests__/dicomVolumeImage.spec.ts b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts new file mode 100644 index 000000000..ab81a5f72 --- /dev/null +++ b/src/core/streaming/__tests__/dicomVolumeImage.spec.ts @@ -0,0 +1,491 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +import { + allocateVolume, + type Volume, +} from '@/src/dicom/core/volume/allocateVolume'; +import { + createDicomRuntime, + type DicomRuntime, +} from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, type ByteSource } from '@/src/dicom/core/source/byteSource'; +import { + readInstance, + type Instance, +} from '@/src/dicom/core/instance/readInstance'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { + DecodedPixels, + WholeInstanceDecode, +} from '@/src/dicom/core/pixels/pixelDecoder'; +import type { Extent } from '@/src/dicom/core/volume/loadVolume'; +import { decodingWith, plannedUpdate } from '@/tests/dicomVolumeFixtures'; +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, { + type DicomVolumeImageInit, +} from '@/src/core/streaming/dicomVolumeImage'; + +const ROWS = 2; +const COLUMNS = 2; +const PIXELS_PER_SLICE = ROWS * COLUMNS; + +// The slice's z position is also its pixel value, so decoded contents say +// which instance a slice came from. +function sliceAt(z: number, overrides: Record = {}) { + const tags = new Map([ + [Tags.SOPInstanceUID, `1.2.3.${z}`], + [Tags.SeriesInstanceUID, '1.2.3'], + [Tags.ImagePositionPatient, `0\\0\\${z}`], + [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], + [Tags.Rows, String(ROWS)], + [Tags.Columns, String(COLUMNS)], + [Tags.PixelSpacing, '1\\1'], + [Tags.BitsStored, '16'], + [Tags.PixelRepresentation, '0'], + [Tags.SamplesPerPixel, '1'], + ...Object.entries(overrides), + ]); + return instanceFor(datasetFromTags(tags), fromBlob(new Blob([String(z)]))); +} + +const volumeOf = (members: Instance[], previous?: Volume) => + allocateVolume(plannedUpdate(members), previous); + +const stack = (count: number) => + volumeOf(Array.from({ length: count }, (_, z) => sliceAt(z))); + +/** Decodes a source written by `sliceAt`, recording the values it decodes. */ +function decodeTo( + dataFor: (value: number) => ArrayLike, + components = 1 +) { + const decoded: number[] = []; + const decoder: WholeInstanceDecode = async ({ bytes }) => { + const value = Number(new TextDecoder().decode(bytes)); + decoded.push(value); + return { + size: [COLUMNS, ROWS, 1], + data: dataFor(value) as DecodedPixels['data'], + components, + }; + }; + return { decoded, decoder }; +} + +const constantSlices = () => + decodeTo((value) => new Uint16Array(PIXELS_PER_SLICE).fill(value)); + +const runtimes: DicomRuntime[] = []; +const images: DicomVolumeImage[] = []; +afterEach(() => { + images.splice(0).forEach((image) => image.dispose()); + runtimes.splice(0).forEach((runtime) => runtime.dispose()); +}); + +function holder( + decoder: WholeInstanceDecode, + init: Omit = {}, + readConcurrency?: number +) { + const runtime = createDicomRuntime({ + ...decodingWith(decoder), + decodeConcurrency: 1, + }); + runtimes.push(runtime); + const encoded: ThumbnailSlice[] = []; + const image = new DicomVolumeImage({ + runtime: { + ...runtime, + readConcurrency: readConcurrency ?? runtime.readConcurrency, + }, + encodeThumbnail: (slice) => { + encoded.push(slice); + return `uri:${Array.from(slice.data).join(',')}`; + }, + ...init, + }); + images.push(image); + const extents: Extent[] = []; + const errors: Error[] = []; + image.addEventListener('extentLoaded', (extent) => extents.push(extent)); + image.addEventListener('error', (error) => errors.push(error)); + return { image, encoded, extents, errors }; +} + +/** Resolves once the image is no longer loading. */ +const idle = (image: DicomVolumeImage) => + new Promise((resolve) => { + if (!image.isLoading()) { + resolve(); + return; + } + const done = (loading: boolean) => { + if (loading) return; + image.removeEventListener('loading', done); + resolve(); + }; + image.addEventListener('loading', done); + }); + +async function show(image: DicomVolumeImage, volume: Volume) { + image.setVolume(volume); + image.startLoad(); + await idle(image); +} + +function sliceOf(image: DicomVolumeImage, index: number) { + const data = image.getVtkImageData().getPointData().getScalars().getData(); + return Array.from( + data.slice(index * PIXELS_PER_SLICE, (index + 1) * PIXELS_PER_SLICE) + ); +} + +const scalarRange = (image: DicomVolumeImage) => + image.getVtkImageData().getPointData().getScalars().getRange() as [ + number, + number, + ]; + +const filledWith = (value: number) => Array(PIXELS_PER_SLICE).fill(value); + +const thumbnailOf = (image: DicomVolumeImage, slice: number) => + sliceThumbnail(image.getVtkImageData(), slice); + +describe('DicomVolumeImage loading', () => { + it('fills every slice, reporting each decoded extent, then completes', async () => { + const { decoder } = constantSlices(); + const { image, extents } = holder(decoder); + const statuses: string[] = []; + image.addEventListener('status', (status) => statuses.push(status)); + + image.setVolume(stack(3)); + image.startLoad(); + expect(image.isLoading()).toBe(true); + expect(image.isLoaded()).toBe(false); + await idle(image); + + expect(image.isLoaded()).toBe(true); + expect(statuses).toEqual(['complete']); + expect([0, 1, 2].map((slice) => sliceOf(image, slice))).toEqual([ + filledWith(0), + filledWith(1), + filledWith(2), + ]); + expect([...extents].sort((left, right) => left[4] - right[4])).toEqual([ + [0, 1, 0, 1, 0, 0], + [0, 1, 0, 1, 1, 1], + [0, 1, 0, 1, 2, 2], + ]); + expect(scalarRange(image)).toEqual([0, 2]); + }); + + it('reports nothing loading when started with every slice already loaded', async () => { + const { decoder, decoded } = constantSlices(); + const { image } = holder(decoder); + await show(image, stack(2)); + + image.startLoad(); + + expect(image.isLoading()).toBe(false); + expect(image.isLoaded()).toBe(true); + expect(decoded).toHaveLength(2); + }); + + it('loads the slice the user looks at first', async () => { + const { decoder, decoded } = constantSlices(); + // One request at a time, so decode order is read order. + const { image } = holder(decoder, { focus: () => 7 }, 1); + + await show(image, stack(9)); + + expect(decoded).toEqual([7, 3, 5, 1, 6, 8, 4, 2, 0]); + }); +}); + +describe('DicomVolumeImage failures', () => { + 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(sliceOf(image, 0)).toEqual(filledWith(1)); + expect(sliceOf(image, 1)).toEqual(filledWith(0)); + 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 () => { + const file = fromBlob( + new Blob([nativePixelDicom({ rows: ROWS, columns: COLUMNS, frames: 3 })]) + ); + let frameReads = 0; + // The second frame read fails; the header and other frames read normally. + const source: ByteSource = { + read: (signal, range) => + range && ++frameReads === 2 + ? new ReadableStream({ + pull: (controller) => controller.error(new Error('reset')), + }) + : file.read(signal, range), + }; + const instance = await readInstance(source, new AbortController().signal); + const runtime = createDicomRuntime({}); + runtimes.push(runtime); + const image = new DicomVolumeImage({ runtime }); + images.push(image); + const errors: Error[] = []; + image.addEventListener('error', (error) => errors.push(error)); + + await show(image, volumeOf([instance])); + + 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); + }); + + it('retries a failed slice on the next load', async () => { + let failures = 1; + const { decoder, decoded } = constantSlices(); + const { image, errors } = holder(async (request, signal) => { + const slice = await decoder(request, signal); + if (slice.data[0] === 1 && failures-- > 0) + throw new Error('corrupt slice'); + return slice; + }); + await show(image, stack(3)); + expect(errors.map(({ message }) => message)).toEqual([ + expect.stringMatching(/could not be decoded: corrupt slice$/), + ]); + expect(sliceOf(image, 1)).toEqual(filledWith(0)); + + image.startLoad(); + await idle(image); + + expect(sliceOf(image, 1)).toEqual(filledWith(1)); + expect(decoded.filter((value) => value !== 1)).toHaveLength(2); + expect(image.isLoaded()).toBe(true); + }); +}); + +describe('DicomVolumeImage replacement', () => { + it('keeps decoded slices across growth without decoding them again', async () => { + const { decoder, decoded } = constantSlices(); + const { image } = holder(decoder); + const [first, middle, last] = [0, 1, 2].map((z) => sliceAt(z)); + const sparse = volumeOf([first, last]); + await show(image, sparse); + const before = image.getVtkImageData(); + decoded.length = 0; + + await show(image, volumeOf([first, middle, last], sparse)); + + expect(image.getVtkImageData()).not.toBe(before); + expect(decoded).toEqual([1]); + expect([0, 1, 2].map((slice) => sliceOf(image, slice))).toEqual([ + filledWith(0), + filledWith(1), + filledWith(2), + ]); + expect(scalarRange(image)).toEqual([0, 2]); + }); + + it('keeps a decode started for a replaced volume out of its successor', async () => { + const release = defer(); + const { decoder } = constantSlices(); + const { image, extents } = holder(async (request, signal) => { + await release.promise; + return decoder(request, signal); + }); + image.setVolume(volumeOf([sliceAt(5)])); + image.startLoad(); + + image.setVolume(volumeOf([sliceAt(7)])); + image.startLoad(); + release.resolve(); + await idle(image); + + expect(sliceOf(image, 0)).toEqual(filledWith(7)); + expect(extents).toHaveLength(1); + }); + + it('aborts loading when disposed', async () => { + const started = defer(); + const { image } = holder((_request, signal) => { + started.resolve(signal); + return new Promise(() => {}); + }); + image.setVolume(stack(1)); + image.startLoad(); + const signal = await started.promise; + + image.dispose(); + + expect(signal.aborted).toBe(true); + await expect(image.getThumbnail()).rejects.toThrow(/disposed/); + }); +}); + +describe('DicomVolumeImage thumbnails', () => { + it('thumbnails the middle slice out of the loaded volume', async () => { + const { decoder, decoded } = constantSlices(); + const { image, encoded } = holder(decoder); + await show(image, stack(3)); + + const uri = await image.getThumbnail(); + + expect(decoded).toHaveLength(3); + expect(encoded).toEqual([thumbnailOf(image, 1)]); + expect(uri).toBe(`uri:${Array.from(encoded[0].data).join(',')}`); + }); + + it('waits for the middle slice when asked before it loads, encoding once', async () => { + const { decoder, decoded } = constantSlices(); + const { image, encoded } = holder(decoder); + image.setVolume(stack(3)); + + const first = image.getThumbnail(); + const second = image.getThumbnail(); + image.startLoad(); + + expect(await first).toBe(await second); + await idle(image); + expect(decoded).toHaveLength(3); + expect(encoded).toHaveLength(1); + }); + + it('falls back to the loaded slice nearest the middle when the middle fails', async () => { + const { decoder } = constantSlices(); + const { image, encoded } = holder(async (request, signal) => { + const slice = await decoder(request, signal); + if (slice.data[0] === 1) throw new Error('corrupt middle slice'); + return slice; + }); + await show(image, stack(3)); + + await image.getThumbnail(); + + expect(encoded).toEqual([thumbnailOf(image, 0)]); + }); + + it('has no thumbnail when no slice loads', async () => { + const { image, encoded } = holder(async () => { + throw new Error('undecodable'); + }); + await show(image, stack(2)); + + expect(await image.getThumbnail()).toBeNull(); + 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); + const slices = [0, 1, 2].map((z) => sliceAt(z)); + const full = volumeOf(slices); + await show(image, full); + const before = await image.getThumbnail(); + + await show(image, volumeOf([slices[0], slices[2]], full)); + + expect(await image.getThumbnail()).not.toBe(before); + expect(encoded).toHaveLength(2); + expect(encoded[1]).toEqual(thumbnailOf(image, 1)); + }); +}); + +describe('DicomVolumeImage segmentation', () => { + const segInstance = (bytes = 'seg-bytes') => + instanceFor( + datasetFromTags([ + [Tags.Modality, 'SEG'], + [Tags.SOPInstanceUID, '1.2.3.9'], + ]), + fromBlob(new Blob([bytes])) + ); + + it('shows the labelmap the segmentation reader makes of its bytes', async () => { + const labelmap = vtkImageData.newInstance(); + const metadata = { segmentAttributes: [] }; + const read: string[] = []; + const { image } = holder(constantSlices().decoder, { + readSegmentation: async (file) => { + read.push(await file.text()); + return { + image: labelmap, + metadata: metadata as unknown as NonNullable< + DicomVolumeImage['segBuildInfo'] + >, + }; + }, + }); + + image.setSegmentation([segInstance()]); + image.startLoad(); + await idle(image); + + expect(read).toEqual(['seg-bytes']); + expect(image.getVtkImageData()).toBe(labelmap); + expect(image.segBuildInfo).toBe(metadata); + expect(image.getModality()).toBe('SEG'); + expect(image.isLoaded()).toBe(true); + }); + + it('reports a SEG object split over several files', async () => { + const { image, errors } = holder(constantSlices().decoder); + + image.setSegmentation([segInstance('a'), segInstance('b')]); + image.startLoad(); + await idle(image); + + expect(errors.map(({ message }) => message)).toEqual([ + expect.stringMatching(/multiple SEG files/), + ]); + 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/__tests__/requestPool.spec.ts b/src/core/streaming/__tests__/requestPool.spec.ts deleted file mode 100644 index 3cc846db9..000000000 --- a/src/core/streaming/__tests__/requestPool.spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { RequestPool } from '@/src/core/streaming/requestPool'; -import { describe, it, expect } from 'vitest'; - -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'); - } - }); -}); diff --git a/src/core/streaming/byteDeque.ts b/src/core/streaming/byteDeque.ts deleted file mode 100644 index 2515d3deb..000000000 --- a/src/core/streaming/byteDeque.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** - * A byte array deque. - */ -export default class ByteDeque { - 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; - } - - /** - * Pop bytes off the start. - * @param {number} count - */ - popStart(count: number): Uint8Array { - return this.consumeStart(count, false) as Uint8Array; - } - - /** - * 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. - * @param {number} count - */ - eraseStart(count: number): void { - this.consumeStart(count, true); - } - - private consumeStart(count: number, discard = false) { - 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; - } - - 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/src/core/streaming/cachedStreamFetcher.ts b/src/core/streaming/cachedStreamFetcher.ts index 7265ed2d0..1a702ba61 100644 --- a/src/core/streaming/cachedStreamFetcher.ts +++ b/src/core/streaming/cachedStreamFetcher.ts @@ -1,267 +1,115 @@ -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 type { Fetcher } from '@/src/core/streaming/types'; type FetchFunction = typeof fetch; -export interface CachedStreamFetcherRequestInit extends RequestInit { - prefixChunks?: Uint8Array[]; - contentLength?: number; +export type CachedStreamFetcherRequestInit = RequestInit & { 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; - this.fetch = init?.fetch ?? globalThis.fetch; + 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 cachedChunks() { - return this.chunks; + return this.open; } - get abortSignal() { - return this.abortController?.signal; - } - - async connect(init?: FetcherInit) { - if (this.connected) return; - - this.abortController = init?.abortController ?? new 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.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) { - 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); - } else if (!noMoreContent) { - this.chunks = []; + 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 !== 200) + 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 = + response.headers.get('content-disposition') ?? ''; + this.reader = response.body.getReader(); + } catch (error) { + this.close(); + throw error; } - - this.activeNetworkStream = response.body; - this.activeNetworkStreamReader = this.activeNetworkStream.getReader(); } 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) { - this.promise = this.activeNetworkStreamReader - .read() - .then((result) => { - 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(() => { - 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.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/chunk.ts b/src/core/streaming/chunk.ts deleted file mode 100644 index 0a31cdea5..000000000 --- a/src/core/streaming/chunk.ts +++ /dev/null @@ -1,186 +0,0 @@ -import { UpdateEvent, enters, leaves } from '@/src/core/stateMachine'; -import { - ChunkState, - ChunkStateMachine, - TransitionEvent, -} from '@/src/core/streaming/chunkStateMachine'; -import { DataLoader, MetaLoader } from '@/src/core/streaming/types'; -import mitt, { Emitter } from 'mitt'; - -type ChunkEvents = { - doneMeta: void; - doneData: void; - error: any; -}; - -interface ChunkEventData { - error?: Error; -} - -interface ChunkInit { - metaLoader: MetaLoader; - dataLoader: DataLoader; -} - -/** - * Represents a data chunk. - */ -export class Chunk { - private machine: ChunkStateMachine; - private metaLoader: MetaLoader; - private dataLoader: DataLoader; - private events: Emitter; - private userData: Map; - - constructor(init: ChunkInit) { - this.metaLoader = init.metaLoader; - this.dataLoader = init.dataLoader; - this.userData = new Map(); - - this.machine = new ChunkStateMachine(); - this.machine.subscribe(this.onStateUpdated); - - this.events = mitt(); - } - - getUserData(key: string) { - return this.userData.get(key); - } - - setUserData(key: string, value: unknown) { - return this.userData.set(key, value); - } - - addEventListener(event: keyof ChunkEvents, callback: (arg?: any) => void) { - this.events.on(event, callback); - return () => this.removeEventListener(event, callback); - } - - removeEventListener(event: keyof ChunkEvents, callback: (arg?: any) => void) { - this.events.off(event, callback); - } - - watchForState(state: ChunkState, callback: () => void) { - const handler = (event: UpdateEvent) => { - if (state === event.state) callback(); - }; - - return this.machine.subscribe(handler); - } - - dispose() { - this.machine.unsubscribe(this.onStateUpdated); - this.events.all.clear(); - this.userData.clear(); - } - - get state() { - return this.machine.state; - } - - get metadata() { - return this.metaLoader.meta; - } - - get metaBlob() { - return this.metaLoader.metaBlob; - } - - get ultrasoundRegions() { - return this.metaLoader.ultrasoundRegions; - } - - get dataBlob() { - return this.dataLoader.data; - } - - loadMeta() { - if (this.machine.state !== ChunkState.Init) { - return Promise.resolve(); - } - return new Promise((resolve, reject) => { - this.machine.send(TransitionEvent.LoadMeta); - const onDoneMeta = () => { - this.events.off('doneMeta', onDoneMeta); - resolve(); - }; - const onError = (error: any) => { - this.events.off('error', onError); - reject(error); - }; - this.events.on('doneMeta', onDoneMeta); - this.events.on('error', onError); - }); - } - - stopLoad() { - this.machine.send(TransitionEvent.Cancel); - } - - loadData() { - if (this.machine.state !== ChunkState.MetaOnly) { - return Promise.resolve(); - } - return new Promise((resolve, reject) => { - this.machine.send(TransitionEvent.LoadData); - const onDoneData = () => { - this.events.off('doneData', onDoneData); - resolve(); - }; - const onError = (error: any) => { - this.events.off('error', onError); - reject(error); - }; - this.events.on('doneData', onDoneData); - this.events.on('error', onError); - }); - } - - private onStateUpdated = async ( - event: UpdateEvent - ) => { - const data = event.data as ChunkEventData; - - if (data?.error) { - this.events.emit('error', data.error); - } - - if (leaves(event, ChunkState.MetaLoading)) { - this.metaLoader.stop(); - } else if (leaves(event, ChunkState.DataLoading)) { - this.dataLoader.stop(); - } - - if (event.event === TransitionEvent.MetaLoaded) { - this.events.emit('doneMeta'); - } else if (event.event === TransitionEvent.DataLoaded) { - this.events.emit('doneData'); - } - - try { - if (enters(event, ChunkState.MetaLoading)) { - await this.metaLoader.load(); - this.machine.send(TransitionEvent.MetaLoaded); - } else if (enters(event, ChunkState.DataLoading)) { - await this.dataLoader.load(); - this.machine.send(TransitionEvent.DataLoaded); - } - } catch (error) { - this.machine.send(TransitionEvent.Cancel, { error }); - } - }; -} - -export function waitForChunkState(chunk: Chunk, state: ChunkState) { - return new Promise((resolve) => { - if (chunk.state === state) { - resolve(chunk); - return; - } - - const stop = chunk.watchForState(state, () => { - resolve(chunk); - stop(); - }); - }); -} diff --git a/src/core/streaming/chunkImage.ts b/src/core/streaming/chunkImage.ts deleted file mode 100644 index 4d032aea8..000000000 --- a/src/core/streaming/chunkImage.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - ProgressiveImage, - ProgressiveImageEvents, -} from '@/src/core/progressiveImage'; -import { Chunk } from '@/src/core/streaming/chunk'; -import { Extent } from '@kitware/vtk.js/types'; - -export enum ChunkStatus { - NotLoaded, - Loading, - Loaded, - Errored, -} - -export type ChunkLoadedInfo = { - updatedExtent: Extent; - chunk: Chunk; -}; - -export type ChunkErrorInfo = { - error: unknown; - chunk: Chunk; -}; - -export type ChunkImageEvents = { - chunkLoad: ChunkLoadedInfo; - chunkError: ChunkErrorInfo; -} & ProgressiveImageEvents; - -export type ChunkImage = ProgressiveImage & { - addChunks(chunks: Chunk[]): void; - addEventListener( - type: T, - callback: (info: ChunkImageEvents[T]) => void - ): void; - removeEventListener( - type: T, - callback: (info: ChunkImageEvents[T]) => void - ): void; - getChunkStatuses(): Array; -}; diff --git a/src/core/streaming/chunkStateMachine.ts b/src/core/streaming/chunkStateMachine.ts deleted file mode 100644 index 638f0292f..000000000 --- a/src/core/streaming/chunkStateMachine.ts +++ /dev/null @@ -1,41 +0,0 @@ -import StateMachine from '@/src/core/stateMachine'; - -export enum ChunkState { - Init = 'Init', - MetaLoading = 'MetaLoading', - MetaOnly = 'MetaOnly', - DataLoading = 'DataLoading', - Loaded = 'Loaded', -} - -export enum TransitionEvent { - LoadMeta = 'LoadMeta', - MetaLoaded = 'MetaLoaded', - LoadData = 'LoadData', - DataLoaded = 'DataLoaded', - Cancel = 'Cancel', -} - -export class ChunkStateMachine extends StateMachine< - ChunkState, - TransitionEvent -> { - constructor() { - super(ChunkState.Init, { - [ChunkState.Init]: { - [TransitionEvent.LoadMeta]: ChunkState.MetaLoading, - }, - [ChunkState.MetaLoading]: { - [TransitionEvent.Cancel]: ChunkState.Init, - [TransitionEvent.MetaLoaded]: ChunkState.MetaOnly, - }, - [ChunkState.MetaOnly]: { - [TransitionEvent.LoadData]: ChunkState.DataLoading, - }, - [ChunkState.DataLoading]: { - [TransitionEvent.DataLoaded]: ChunkState.Loaded, - [TransitionEvent.Cancel]: ChunkState.MetaOnly, - }, - }); - } -} diff --git a/src/core/streaming/concatStreams.ts b/src/core/streaming/concatStreams.ts deleted file mode 100644 index 34a175bdd..000000000 --- a/src/core/streaming/concatStreams.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Concatenates multiple streams together in order. - * @param streams - * @returns - */ -export function concatStreams( - ...streams: ReadableStream[] -): ReadableStream { - let reader: ReadableStreamDefaultReader | null = null; - return new ReadableStream({ - async pull(controller) { - let enqueued = false; - while (!enqueued && streams.length) { - if (!reader) { - reader = streams[0].getReader(); - } - - const result = await reader.read(); - - if (result.value) { - controller.enqueue(result.value); - enqueued = true; - } - - if (result.done) { - streams.shift(); - reader = null; - } - } - - if (streams.length === 0) { - controller.close(); - } - }, - }); -} diff --git a/src/core/streaming/dicom/__tests__/dicomMetaLoader.spec.ts b/src/core/streaming/dicom/__tests__/dicomMetaLoader.spec.ts deleted file mode 100644 index 9c0145070..000000000 --- a/src/core/streaming/dicom/__tests__/dicomMetaLoader.spec.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { DicomMetaLoader } from '@/src/core/streaming/dicom/dicomMetaLoader'; -import { RequestPool } from '@/src/core/streaming/requestPool'; -import { CachedStreamFetcher } from '@/src/core/streaming/cachedStreamFetcher'; -import { describe, it, expect } from 'vitest'; - -describe('dicomMetaLoader', () => { - it('should load only metadata', async () => { - const pool = new RequestPool(); - const fetcher = new CachedStreamFetcher( - 'https://data.kitware.com/api/v1/file/57b5d4648d777f10f2693e7e/download', - { - fetch: pool.fetch, - } - ); - const loader = new DicomMetaLoader(fetcher, () => { - return []; - }); - await loader.load(); - - const downloaded = fetcher.cachedChunks.reduce( - (sum, chunk) => sum + chunk.length, - 0 - ); - // metadata header fits within 4096 - expect(downloaded).to.be.lessThanOrEqual(4096); - }); -}); diff --git a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts index 7301b0b5e..222cc95ff 100644 --- a/src/core/streaming/dicom/__tests__/octMetadata.spec.ts +++ b/src/core/streaming/dicom/__tests__/octMetadata.spec.ts @@ -1,12 +1,12 @@ -import dicomParser, { type DataSet } from 'dicom-parser'; import { deflateRawSync } from 'node:zlib'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { Tags } from '@/src/core/dicomTags'; -import { augmentOCTMetadata } from '@/src/core/streaming/dicom/octMetadata'; -import { allocateImageFromChunks } from '@/src/utils/allocateImageFromChunks'; -import type { Chunk } from '@/src/core/streaming/chunk'; +import { describe, expect, it, vi } from 'vitest'; +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'; -import { deflatedExplicitVR } from '@/tests/fixtures/oct/volumes'; import { isOCTMetadata, OCT_GEOMETRY_ERROR, @@ -22,54 +22,25 @@ import { element, enhancedFile, sequence, - overwriteDicomString, } from '@/tests/fixtures/oct/dicom'; -const baseMetadata = (): Array<[string, string]> => [ - [Tags.SOPClassUID, OPHTHALMIC_TOMOGRAPHY_SOP], - [Tags.Modality, 'OPT'], -]; +const fixtureBytes = (...options: Parameters) => + new Uint8Array(createSyntheticOCT(...options)); -afterEach(() => vi.restoreAllMocks()); - -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' }); -} - -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); -async function augmented(bytes = fixtureBytes()) { - return new Map( - await augmentOCTMetadata(new Blob([bytes as BlobPart]), baseMetadata()) - ); +const never = new AbortController().signal; + +async function projectFile(file: Blob) { + const { dataset } = await readInstance(fromBlob(file), never); + return enFaceTags(dataset); } -function recordBlobReads() { - const reads: number[] = []; - const arrayBuffer = Blob.prototype.arrayBuffer; - vi.spyOn(Blob.prototype, 'arrayBuffer').mockImplementation(function ( - this: Blob - ) { - reads.push(this.size); - return arrayBuffer.call(this); - }); - return reads; +async function augmented(bytes = fixtureBytes()) { + return new Map(await projectFile(new Blob([bytes as BlobPart]))); } describe('OCT DICOM activation', () => { @@ -81,6 +52,7 @@ describe('OCT DICOM activation', () => { isOCTMetadata([[Tags.SOPClassUID, OPHTHALMIC_BSCAN_ANALYSIS_SOP]]) ).toBe(true); expect(isOCTMetadata([[Tags.Modality, 'OPT ']])).toBe(true); + expect(isOCTMetadata([[Tags.Modality, 'OPT\0']])).toBe(true); }); it('does not activate a volume projection for an existing enface image', () => { @@ -99,45 +71,35 @@ describe('OCT DICOM activation', () => { } ); - it('preserves metadata and skips parsing non-OCT files', async () => { - const tags: Array<[string, string]> = [[Tags.Modality, 'CT']]; - expect(await augmentOCTMetadata(new Blob(['not a DICOM']), tags)).toBe( - tags - ); + 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 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); }); }); describe('OCT enhanced spatial metadata', () => { - it('reads the header without copying the volume pixels', async () => { - const source = fixtureBytes(); - const expected = await augmented(source); - const reads = recordBlobReads(); - - expect(await augmented(source)).toEqual(expected); - expect(reads.reduce((total, bytes) => total + bytes, 0)).toBeLessThan( - source.length / 10 - ); - }); - - it('reads large OCT headers without copying the pixel payload', async () => { + it('stops streaming after large OCT headers before the pixel payload', async () => { const frames = [{ position: '0\\0\\0' }, { position: '0\\0\\0.2' }]; - const expected = new Map( - await augmentOCTMetadata(enhancedFile(frames), baseMetadata()) - ); const file = new Blob([ enhancedFile(frames, [ element('00111010', 'OB', new Uint8Array(2 * 1024 * 1024)), ]), element('7fe00010', 'OW', new Uint8Array(16 * 1024 * 1024)), ]); - const reads = recordBlobReads(); - - expect(new Map(await augmentOCTMetadata(file, baseMetadata()))).toEqual( - expected - ); - expect(reads.reduce((total, bytes) => total + bytes, 0)).toBeLessThan( - file.size / 2 + const { source, stats } = trackedSource( + new Uint8Array(await file.arrayBuffer()), + 64 * 1024 ); + const { dataset } = await readInstance(source, never); + 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); }); it.each([64 * 1024, 2 * 1024 * 1024])( @@ -149,7 +111,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)), ]); @@ -157,30 +121,26 @@ describe('OCT enhanced spatial metadata', () => { header, element('7fe00010', 'OW', new Uint8Array(2)), ]); - expect(new Map(await augmentOCTMetadata(file, baseMetadata()))).toEqual( - new Map(await augmentOCTMetadata(enhancedFile(frames), baseMetadata())) + expect(new Map(await projectFile(file))).toEqual( + new Map(await projectFile(enhancedFile(frames))) ); } ); 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); @@ -190,18 +150,19 @@ 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); expect(await augmented(bytes)).toEqual(await augmented(source)); }); - it('records unreadable spatial metadata when the deflated dataset is truncated', async () => { - const bytes = deflatedExplicitVR(fixtureBytes()); - expect( - spatialMetadataError(await augmented(bytes.subarray(0, -10))) - ).toMatch(/could not be read/); + it('rejects a truncated deflated dataset before projecting its metadata', async () => { + const bytes = fixtureBytes({ deflate: true }); + await expect(augmented(bytes.subarray(0, -10))).rejects.toThrow(); }); it.each([ @@ -210,7 +171,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)]); @@ -235,9 +196,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'); @@ -253,13 +212,10 @@ describe('OCT enhanced spatial metadata', () => { sequence('00221640', [ sequence('00221618', [element('00080100', 'SH', pattern)]), ]), - ] - ); - const tags = new Map( - await augmentOCTMetadata(file, [ - [Tags.SOPClassUID, OPHTHALMIC_BSCAN_ANALYSIS_SOP], - ]) + ], + { set: { '00080016': OPHTHALMIC_BSCAN_ANALYSIS_SOP } } ); + const tags = new Map(await projectFile(file)); expect(tags.get(OCT_SCAN_PATTERN)).toBe(pattern); } ); @@ -273,6 +229,7 @@ describe('OCT enhanced spatial metadata', () => { Buffer.alloc(128), Buffer.from('DICM'), element('00020010', 'UI', '1.2.840.10008.1.2'), + attribute('00080016', OPHTHALMIC_BSCAN_ANALYSIS_SOP), attribute('00280008', '2'), attribute('00180088', '0.2'), implicit( @@ -281,11 +238,7 @@ describe('OCT enhanced spatial metadata', () => { ]) ), ]); - const tags = new Map( - await augmentOCTMetadata(file, [ - [Tags.SOPClassUID, OPHTHALMIC_BSCAN_ANALYSIS_SOP], - ]) - ); + const tags = new Map(await projectFile(file)); expect(tags.get(OCT_SCAN_PATTERN)).toBe('128282'); }); @@ -295,28 +248,22 @@ describe('OCT enhanced spatial metadata', () => { [{}, {}], [element('00180088', 'DS', '0.2'), sequence('00221640', [raster, raster])] ); - expect( - new Map(await augmentOCTMetadata(file, baseMetadata())).get( - OCT_SCAN_PATTERN - ) - ).toBe('multiple'); + expect(new Map(await projectFile(file)).get(OCT_SCAN_PATTERN)).toBe( + 'multiple' + ); }); 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(); @@ -324,8 +271,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 ); @@ -339,14 +285,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 ); @@ -356,103 +297,77 @@ 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' - ); - } - const metadata: Array<[string, string]> = [ - ...baseMetadata(), - [Tags.Rows, '2'], - [Tags.Columns, '2'], - [Tags.NumberOfFrames, '2'], - [Tags.BitsStored, '16'], - [Tags.PixelRepresentation, '0'], - [Tags.ImagePositionPatient, '9\\8\\7'], - [Tags.ImageOrientationPatient, '1\\0\\0\\0\\1\\0'], - ]; - const tags = new Map( - await augmentOCTMetadata(new Blob([bytes]), metadata) - ); + 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(); - const image = allocateImageFromChunks([{ metadata: [...tags] } as Chunk]); - expect(image.getOrigin()).toEqual([9, 8, 7]); - expect(image.getDirection()).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]); - image.delete(); + expect(tags.get(Tags.ImagePositionPatient)?.trim()).toBe('9\\8\\7'); + expect(tags.get(Tags.ImageOrientationPatient)?.trim()).toBe( + '1\\0\\0\\0\\1\\0' + ); } ); 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/ ); }); it('derives inter-frame spacing from uniform positions', async () => { - const tags = await augmentOCTMetadata( + const tags = await projectFile( enhancedFile([ { position: '0\\0\\0' }, { position: '0\\0\\0.2' }, { position: '0\\0\\0.4' }, - ]), - baseMetadata() + ]) ); expect(spatialMetadataError(tags)).toBeUndefined(); expect(new Map(tags).get(Tags.SpacingBetweenSlices)).toBe('0.2'); }); it('accepts positions rounded to four decimal places', async () => { - const tags = await augmentOCTMetadata( + const tags = await projectFile( enhancedFile( Array.from({ length: 49 }, (_, i) => ({ position: `0\\0\\${(i * 0.12306585).toFixed(4)}`, })) - ), - baseMetadata() + ) ); expect(spatialMetadataError(tags)).toBeUndefined(); }); 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(); }); @@ -461,13 +376,10 @@ describe('OCT enhanced spatial metadata', () => { const normal = [-0.97088946, 0.17417332, 0.16458873]; const position = normal.map((n) => (n * 0.2).toFixed(4)).join('\\'); const tags = new Map( - await augmentOCTMetadata( - enhancedFile( - [{ position: '0\\0\\0' }, { position }], - [], - [sequence('00209116', [element('00200037', 'DS', orientation)])] - ), - baseMetadata() + await projectFile( + enhancedFile([{ position: '0\\0\\0' }, { position }], [], { + orientation, + }) ) ); expect(spatialMetadataError(tags)).toBeUndefined(); @@ -480,26 +392,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'); @@ -509,13 +415,12 @@ describe('OCT enhanced spatial metadata', () => { it('does not promote geometry for frames stored against the positive normal', async () => { const tags = new Map( - await augmentOCTMetadata( + await projectFile( enhancedFile([ { position: '0\\0\\0.4' }, { position: '0\\0\\0.2' }, { position: '0\\0\\0' }, - ]), - baseMetadata() + ]) ) ); expect(spatialMetadataError(tags)).toMatch(/image grid/); @@ -531,36 +436,28 @@ describe('OCT enhanced spatial metadata', () => { [{}, {}, {}], spacing === undefined ? [] : [element('00180088', 'DS', spacing)] ); - const tags = new Map(await augmentOCTMetadata(file, baseMetadata())); + const tags = new Map(await projectFile(file)); expect(spatialMetadataError(tags)).toMatch(/slice spacing.*unavailable/); expect(tags.get(Tags.PixelSpacing)).toBe('0.01\\0.02'); } ); 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'); }); @@ -603,17 +500,100 @@ describe('OCT enhanced spatial metadata', () => { /Repeated/, ], ])('rejects %s', async (_label, frames, error) => { - const tags = await augmentOCTMetadata(enhancedFile(frames), baseMetadata()); + const tags = await projectFile(enhancedFile(frames)); expect(spatialMetadataError(tags)).toMatch(error); }); - it('records unreadable spatial metadata when the OCT header cannot be parsed', async () => { - const tags = await augmentOCTMetadata( - new Blob(['corrupt OCT']), - baseMetadata() - ); - expect(spatialMetadataError(tags)).toBe( - 'OCT spatial metadata could not be read.' - ); + it('rejects a corrupt OCT header before projecting metadata', async () => { + 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__/ultrasoundRegion.spec.ts b/src/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts deleted file mode 100644 index 8b4968529..000000000 --- a/src/core/streaming/dicom/__tests__/ultrasoundRegion.spec.ts +++ /dev/null @@ -1,219 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import type { DataElement } from '@/src/core/streaming/dicom/dicomParser'; -import { - decodeUltrasoundRegion, - parseUltrasoundRegionFromBlob, - unitToMm, - US_UNIT_CENTIMETERS, -} from '@/src/core/streaming/dicom/ultrasoundRegion'; - -const u16LE = (v: number) => { - const b = new Uint8Array(2); - new DataView(b.buffer).setUint16(0, v, true); - return b; -}; - -const f64LE = (v: number) => { - const b = new Uint8Array(8); - new DataView(b.buffer).setFloat64(0, v, true); - return b; -}; - -const concat = (parts: Uint8Array[]) => { - const total = parts.reduce((sum, p) => sum + p.length, 0); - const out = new Uint8Array(total); - let offset = 0; - parts.forEach((p) => { - out.set(p, offset); - offset += p.length; - }); - return out; -}; - -// Builds an explicit-VR-LE data element for a VR with 2-byte length (US/FD/UI/etc). -const shortVRElement = ( - group: number, - element: number, - vr: string, - value: Uint8Array -) => { - 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, value.length, true); - return concat([header, value]); -}; - -type Item = { group: number; element: number; vr: string; value: Uint8Array }; - -// Fake parsed sequence data mirroring what readSequenceValue emits. -const fakeSequenceData = (items: Item[][]): DataElement['data'] => - items.map( - (elements) => - elements.map((e) => ({ - group: e.group, - element: e.element, - vr: e.vr, - length: e.value.length, - data: e.value, - })) as DataElement[] - ); - -const wellFormedItem: Item[] = [ - { - group: 0x0018, - element: 0x6024, - vr: 'US', - value: u16LE(US_UNIT_CENTIMETERS), - }, - { - group: 0x0018, - element: 0x6026, - vr: 'US', - value: u16LE(US_UNIT_CENTIMETERS), - }, - { group: 0x0018, element: 0x602c, vr: 'FD', value: f64LE(0.05) }, - { group: 0x0018, element: 0x602e, vr: 'FD', value: f64LE(0.1) }, -]; - -describe('decodeUltrasoundRegion', () => { - it('decodes the first item of the sequence', () => { - const result = decodeUltrasoundRegion(fakeSequenceData([wellFormedItem])); - expect(result).toEqual({ - region: { - physicalDeltaX: 0.05, - physicalDeltaY: 0.1, - physicalUnitsXDirection: US_UNIT_CENTIMETERS, - physicalUnitsYDirection: US_UNIT_CENTIMETERS, - }, - regionCount: 1, - }); - }); - - it('returns no region with zero count when the sequence is empty', () => { - expect(decodeUltrasoundRegion([])).toEqual({ regionCount: 0 }); - }); - - it('returns no region with zero count when the data is not a sequence', () => { - expect(decodeUltrasoundRegion(undefined)).toEqual({ regionCount: 0 }); - expect(decodeUltrasoundRegion(new Uint8Array(4))).toEqual({ - regionCount: 0, - }); - }); - - it('returns no region but reports the count when a required field is missing', () => { - const missingDeltaY = wellFormedItem.filter( - (e) => !(e.group === 0x0018 && e.element === 0x602e) - ); - expect(decodeUltrasoundRegion(fakeSequenceData([missingDeltaY]))).toEqual({ - regionCount: 1, - }); - }); - - it('decodes only the first item but reports the total count', () => { - const second: Item[] = [ - { group: 0x0018, element: 0x6024, vr: 'US', value: u16LE(0) }, - { group: 0x0018, element: 0x6026, vr: 'US', value: u16LE(0) }, - { group: 0x0018, element: 0x602c, vr: 'FD', value: f64LE(999) }, - { group: 0x0018, element: 0x602e, vr: 'FD', value: f64LE(999) }, - ]; - const result = decodeUltrasoundRegion( - fakeSequenceData([wellFormedItem, second]) - ); - expect(result.region?.physicalDeltaX).toBe(0.05); - expect(result.regionCount).toBe(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', () => { - // Per DICOM PS3.3 C.8.5.5.1.15: 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. - [0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12].forEach((code) => { - expect(unitToMm(code)).toBeNull(); - }); - }); -}); - -// Builds a minimal DICOM P10 byte stream containing only what the ultrasound -// parser needs: preamble, DICM magic, a TransferSyntaxUID (Explicit VR LE), -// and a SequenceOfUltrasoundRegions with one populated item. -const buildDicomBlob = (item: Item[]) => { - const preamble = new Uint8Array(128); - const magic = new TextEncoder().encode('DICM'); - - // File Meta Info: just TransferSyntaxUID. The parser exits the meta block - // as soon as it peeks a non-0x0002 group, so FileMetaInformationGroupLength - // is not required here. - const tsxValue = new TextEncoder().encode('1.2.840.10008.1.2.1\0'); - const tsx = shortVRElement(0x0002, 0x0010, 'UI', tsxValue); - - const itemBody = concat( - item.map((e) => shortVRElement(e.group, e.element, e.vr, e.value)) - ); - - // Item header: (fffe,e000) tag + 4-byte length. - const itemHeader = new Uint8Array(8); - const ivh = new DataView(itemHeader.buffer); - ivh.setUint16(0, 0xfffe, true); - ivh.setUint16(2, 0xe000, true); - ivh.setUint32(4, itemBody.length, true); - - const sequenceBody = concat([itemHeader, itemBody]); - - // SQ header: tag + "SQ" + 2 reserved + 4-byte length. - const sqHeader = new Uint8Array(12); - const sqh = new DataView(sqHeader.buffer); - sqh.setUint16(0, 0x0018, true); - sqh.setUint16(2, 0x6011, true); - sqHeader[4] = 'S'.charCodeAt(0); - sqHeader[5] = 'Q'.charCodeAt(0); - sqh.setUint32(8, sequenceBody.length, true); - - // Pixel data tag so the parser reaches its stop condition cleanly. - const pixelDataTag = new Uint8Array(4); - new DataView(pixelDataTag.buffer).setUint16(0, 0x7fe0, true); - new DataView(pixelDataTag.buffer).setUint16(2, 0x0010, true); - - return new Blob([ - concat([preamble, magic, tsx, sqHeader, sequenceBody, pixelDataTag]), - ]); -}; - -describe('parseUltrasoundRegionFromBlob', () => { - it('extracts the region and count from a synthetic DICOM blob', async () => { - const blob = buildDicomBlob(wellFormedItem); - const result = await parseUltrasoundRegionFromBlob(blob); - expect(result).toEqual({ - region: { - physicalDeltaX: 0.05, - physicalDeltaY: 0.1, - physicalUnitsXDirection: US_UNIT_CENTIMETERS, - physicalUnitsYDirection: US_UNIT_CENTIMETERS, - }, - regionCount: 1, - }); - }); - - it('returns undefined when the blob has no SequenceOfUltrasoundRegions', async () => { - // Build a blob with only the TransferSyntaxUID + pixel data tag. - const preamble = new Uint8Array(128); - const magic = new TextEncoder().encode('DICM'); - const tsxValue = new TextEncoder().encode('1.2.840.10008.1.2.1\0'); - const tsx = shortVRElement(0x0002, 0x0010, 'UI', tsxValue); - const pixelDataTag = new Uint8Array(4); - new DataView(pixelDataTag.buffer).setUint16(0, 0x7fe0, true); - new DataView(pixelDataTag.buffer).setUint16(2, 0x0010, true); - const blob = new Blob([concat([preamble, magic, tsx, pixelDataTag])]); - - expect(await parseUltrasoundRegionFromBlob(blob)).toBeUndefined(); - }); -}); diff --git a/src/core/streaming/dicom/dicomDataLoader.ts b/src/core/streaming/dicom/dicomDataLoader.ts deleted file mode 100644 index 0a0d03060..000000000 --- a/src/core/streaming/dicom/dicomDataLoader.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { DataLoader, Fetcher } from '@/src/core/streaming/types'; -import { Maybe } from '@/src/types'; - -export class DicomDataLoader implements DataLoader { - public data: Maybe; - private fetcher: Fetcher; - - constructor(fetcher: Fetcher) { - this.fetcher = fetcher; - } - - async load() { - this.data = await this.fetcher.blob(); - } - - stop() { - this.fetcher.close(); - } -} diff --git a/src/core/streaming/dicom/dicomFileDataLoader.ts b/src/core/streaming/dicom/dicomFileDataLoader.ts deleted file mode 100644 index 1868fd788..000000000 --- a/src/core/streaming/dicom/dicomFileDataLoader.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { DataLoader } from '@/src/core/streaming/types'; - -export class DicomFileDataLoader implements DataLoader { - public data: Blob; - - constructor(data: Blob) { - this.data = data; - } - - // Data is provided, so load/stop does nothing. - - load() {} - - stop() {} -} diff --git a/src/core/streaming/dicom/dicomFileMetaLoader.ts b/src/core/streaming/dicom/dicomFileMetaLoader.ts deleted file mode 100644 index 0ae32a119..000000000 --- a/src/core/streaming/dicom/dicomFileMetaLoader.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { ReadDicomTagsFunction } from '@/src/core/streaming/dicom/dicomMetaLoader'; -import { MetaLoader } from '@/src/core/streaming/types'; -import { Maybe } from '@/src/types'; -import { Tags } from '@/src/core/dicomTags'; -import { augmentOCTMetadata } from '@/src/core/streaming/dicom/octMetadata'; -import { - parseUltrasoundRegionFromBlob, - UltrasoundRegions, -} from '@/src/core/streaming/dicom/ultrasoundRegion'; - -export class DicomFileMetaLoader implements MetaLoader { - public tags: Maybe>; - public ultrasoundRegions: UltrasoundRegions | undefined; - private file: File; - - constructor( - file: File, - private readDicomTags: ReadDicomTagsFunction - ) { - this.file = file; - } - - get meta() { - return this.tags; - } - - get metaBlob() { - return this.file; - } - - async load() { - if (this.tags) return; - this.tags = await augmentOCTMetadata( - this.file, - await this.readDicomTags(this.file) - ); - - const modality = new Map(this.tags).get(Tags.Modality)?.trim(); - if (modality === 'US') { - this.ultrasoundRegions = await parseUltrasoundRegionFromBlob(this.file); - } - } - - stop() { - // do nothing - } -} diff --git a/src/core/streaming/dicom/dicomMetaLoader.ts b/src/core/streaming/dicom/dicomMetaLoader.ts deleted file mode 100644 index bc90078cc..000000000 --- a/src/core/streaming/dicom/dicomMetaLoader.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { - createDicomParser, - ImplicitTransferSyntaxUID, -} from '@/src/core/streaming/dicom/dicomParser'; -import { StopSignal } from '@/src/core/streaming/cachedStreamFetcher'; -import { Fetcher, MetaLoader } from '@/src/core/streaming/types'; -import { Maybe } from '@/src/types'; -import { Awaitable } from '@vueuse/core'; -import { toAscii } from '@/src/utils'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; -import { Tags } from '@/src/core/dicomTags'; -import { augmentOCTMetadata } from '@/src/core/streaming/dicom/octMetadata'; -import { - decodeUltrasoundRegion, - SEQUENCE_OF_ULTRASOUND_REGIONS, - UltrasoundRegions, -} from '@/src/core/streaming/dicom/ultrasoundRegion'; - -export type ReadDicomTagsFunction = ( - file: File -) => Awaitable>; - -function generateEmptyPixelData(explicitVr: boolean) { - // prettier-ignore - return new Uint8Array([ - 0xe0, 0x7f, 0x10, 0x00, // PixelData (group, element) - ...(explicitVr ? [0x4f, 0x42, 0x00, 0x00] : []), // OB - 0, 0, 0, 0 // zero length - ]); -} - -export class DicomMetaLoader implements MetaLoader { - private tags: Maybe>; - private fetcher: Fetcher; - private readDicomTags: ReadDicomTagsFunction; - private blob: Blob | null; - public ultrasoundRegions: UltrasoundRegions | undefined; - - constructor(fetcher: Fetcher, readDicomTags: ReadDicomTagsFunction) { - this.fetcher = fetcher; - this.readDicomTags = readDicomTags; - this.blob = null; - } - - get meta() { - return this.tags; - } - - get metaBlob() { - return this.blob; - } - - async load() { - if (this.tags) return; - - await this.fetcher.connect(); - const stream = this.fetcher.getStream(); - let explicitVr = true; - let dicomUpToPixelDataIdx = -1; - let modality: string | undefined; - let ultrasoundRegions: UltrasoundRegions | undefined; - - const parse = createDicomParser({ - stopAtElement(group, element) { - // PixelData - return group === 0x7fe0 && element === 0x0010; - }, - onDataElement: (el) => { - if (el.group === 0x0002 && el.element === 0x0010) { - const transferSyntaxUid = toAscii(el.data as Uint8Array); - explicitVr = transferSyntaxUid !== ImplicitTransferSyntaxUID; - } - // Capture Modality tag (0008,0060) - if (el.group === 0x0008 && el.element === 0x0060 && el.data) { - modality = toAscii(el.data as Uint8Array).trim(); - } - if ( - el.group === SEQUENCE_OF_ULTRASOUND_REGIONS[0] && - el.element === SEQUENCE_OF_ULTRASOUND_REGIONS[1] && - !ultrasoundRegions - ) { - // Decoding can throw if a malformed FD/US value has an unexpected - // length; swallow rather than abort the whole metadata load. - try { - ultrasoundRegions = decodeUltrasoundRegion(el.data); - } catch (err) { - console.warn('Failed to decode SequenceOfUltrasoundRegions:', err); - } - } - }, - }); - - const sinkStream = new WritableStream({ - write: (chunk) => { - const result = parse(chunk); - if (result.done) { - dicomUpToPixelDataIdx = result.value.position; - this.fetcher.close(); - } - }, - }); - - try { - await stream.pipeTo(sinkStream, { - // ensure we use the fetcher's abort signal, - // otherwise a DOMException will be propagated - signal: this.fetcher.abortSignal, - }); - } catch (err) { - if (err !== StopSignal) { - throw err; - } - } - - // itk.wasm/GDCM requires valid pixel data to be present, so we need to - // generate fake pixel data. Valid means valid length and VR. - // It turns out that encapsulated pixel data structures are parsed, even if - // the pixel data itself is not touched. This does not work well with - // metadata streaming. - const metaBlob = new Blob(this.fetcher.cachedChunks).slice( - 0, - dicomUpToPixelDataIdx - ); - const validPixelDataBlob = new Blob( - [metaBlob, generateEmptyPixelData(explicitVr)], - { type: FILE_EXT_TO_MIME.dcm } - ); - - this.blob = validPixelDataBlob; - - // Skip ITK-WASM for RT modalities as they're not supported - if (modality?.startsWith('RT')) { - this.tags = [[Tags.Modality, modality]]; - return; - } - - const metadataFile = new File([validPixelDataBlob], 'file.dcm'); - this.tags = await augmentOCTMetadata( - metadataFile, - await this.readDicomTags(metadataFile) - ); - - if (modality === 'US' && ultrasoundRegions) { - this.ultrasoundRegions = ultrasoundRegions; - } - } - - stop() { - this.fetcher.close(); - } -} diff --git a/src/core/streaming/dicom/dicomParser.ts b/src/core/streaming/dicom/dicomParser.ts deleted file mode 100644 index 51502a4d3..000000000 --- a/src/core/streaming/dicom/dicomParser.ts +++ /dev/null @@ -1,389 +0,0 @@ -import StreamingByteReader from '@/src/core/streaming/streamingByteReader.js'; -import { toAscii, asCoroutine } from '@/src/utils'; - -// [Group, Element] -type Tag = [number, number]; - -export type DataElement = { - group: number; - element: number; - vr: string; - length: number; - data: Array | Uint8Array | undefined; -}; - -export type DataElementCallback = (el: DataElement) => void; -export type ElementTagCallback = ( - group: number, - element: number -) => string | null; - -interface ParseOptions { - peek?: boolean; - littleEndian?: boolean; - explicitVr?: boolean; - onDataElement?: DataElementCallback; -} - -// 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; -export const ImplicitTransferSyntaxUID = '1.2.840.10008.1.2'; -export const ExplicitVRBigEndianUID = '1.2.840.10008.1.2.2'; - -const Tags = { - TransferSyntaxUID: [0x0002, 0x0010] as Tag, - ItemDelimiter: [0xfffe, 0xe00d] as Tag, - Item: [0xfffe, 0xe000] as Tag, -}; - -// VR reference: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html -// See: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.2 -// prettier-ignore -const ExplicitVrLegacyDataElementFormat = new Set(["AE", "AS", "AT", "CS", "DA", "DS", "DT", "FL", "FD", "IS", "LO", "LT", "PN", "SH", "SL", "SS", "ST", "TM", "UI", "UL", "US"]); -// 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]; -} - -function* readElementTag( - reader: StreamingByteReader, - { littleEndian = false } = {} -) { - const group = yield* reader.readUint16({ littleEndian }); - const element = yield* reader.readUint16({ littleEndian }); - return [group, element] as Tag; -} - -/** - * 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, - { 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; -} - -/** - * Reads an element value. - * - * 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 - */ -function* readElementValue( - reader: StreamingByteReader, - vr: string, - length: number, - { explicitVr = false, littleEndian = false } = {} -): Generator { - // See examples: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_7.5.2.html - if (vr === 'SQ') { - return yield* readSequenceValue(reader, length, { - explicitVr, - littleEndian, - }); - } - - if (length === UndefinedLength) - throw new Error('cannot read a value of undefined length'); - return yield* reader.read(length); -} - -/** - * Reads the data element at point. - * - * 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 } = opts ?? {}; - // read tag - const [group, element] = yield* readElementTag(reader, { littleEndian }); - let length = 0; - let vr: string = ''; - let data: DataElement['data']; - - if (explicitVr) { - // read VR - vr = yield* reader.readAscii(2); - if (ExplicitVrLegacyDataElementFormat.has(vr)) { - length = yield* reader.readUint16({ littleEndian }); - } else { - // skip reserved bytes - yield* reader.seek(2); - length = yield* reader.readUint32({ littleEndian }); - } - - if ( - length === UndefinedLength && - 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, - }); - } 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) { - vr = 'SQ'; - } - - data = yield* readElementValue(reader, vr, length, { - littleEndian, - explicitVr, - }); - } - - return { group, element, vr, length, data }; -} - -/** - * Stops the reader at the beginning of the data element that satisfies untilFn. - * - * Assumes the reader is pointing to the start of a Data Element. - * - * untilFn is passed (group, element) - */ -function* readDataElementsUntil( - reader: StreamingByteReader, - untilFn: (group: number, element: number) => boolean, - opts: ParseOptions -) { - while (true) { - const [group, element] = yield* peekElementTag(reader, opts); - if (untilFn(group, element)) { - return; - } - const el = yield* readDataElement(reader, opts); - opts.onDataElement?.(el); - } -} - -/** - * 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; - while (reader.position < endPosition) { - const el = yield* readDataElement(reader, opts); - opts.onDataElement?.(el); - } -} - -/** - * 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( - reader: StreamingByteReader, - byteLength: number, - { explicitVr = false, littleEndian = false } = {} -) { - 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 }); - - // 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); - 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); - return items; - } - - throw new Error( - `readSequenceValue: encountered unknown element: (${group.toString( - 16 - )},${element.toString(16)})` - ); - } -} - -// 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( - reader: StreamingByteReader, - opts?: { onDataElement?: DataElementCallback } -) { - // read up until the Transfer Syntax UID - yield* readDataElementsUntil(reader, equalsToTag(Tags.TransferSyntaxUID), { - explicitVr: true, - littleEndian: true, - onDataElement: opts?.onDataElement, - }); - - const transferSyntaxUidElement = yield* readDataElement(reader, { - explicitVr: true, - littleEndian: true, - }); - opts?.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, - } - ); - - // 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 - yield* readDataElementsUntil(reader, (group) => group !== 0x0002, { - explicitVr: true, - littleEndian: true, - onDataElement: opts?.onDataElement, - }); - - return { - transferSyntaxUid, - }; -} - -export type ReadDicomOptions = { - stopAtElement?(group: number, element: number): boolean; - onDataElement?: DataElementCallback; -}; - -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; - - yield* readDataElementsUntil( - reader, - // (7fe0,0010): Pixel Data - (group, element) => opts?.stopAtElement?.(group, element) ?? false, - { explicitVr, littleEndian, onDataElement: opts?.onDataElement } - ); - - return { - position: reader.position, - }; -} - -export const createDicomParser = (callbacks?: ReadDicomOptions) => { - return asCoroutine(readDicomUntilPixelData(callbacks)); -}; diff --git a/src/core/streaming/dicom/octMetadata.ts b/src/core/streaming/dicom/octMetadata.ts index 2111e3a37..e93f70c67 100644 --- a/src/core/streaming/dicom/octMetadata.ts +++ b/src/core/streaming/dicom/octMetadata.ts @@ -1,7 +1,9 @@ -import dicomParser, { type DataSet } from 'dicom-parser'; -import { inflateSync } from 'fflate'; +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 { Tags, toDicomParserKey } from '@/src/core/dicomTags'; import { frameGridGeometry, imageDirection, @@ -20,48 +22,38 @@ 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 sequenceTags = new Set([ - SHARED, - PER_FRAME, - MEASURES, - ORIENTATION, - POSITION, - SCAN_PATTERN, - ACQUISITION_PARAMETERS, - 'x00283000', - 'x00289145', -]); - -const firstItem = (data: DataSet | undefined, tag: string) => - data?.elements[tag]?.items?.[0]?.dataSet; -const sequenceItems = (data: DataSet, tag: string) => - data.elements[tag]?.items?.flatMap((item) => - item.dataSet ? [item.dataSet] : [] - ) ?? []; -const stringValue = (data: DataSet | undefined, tag: string) => - data?.string(tag)?.trim() || undefined; +const SHARED = '52009229'; +const PER_FRAME = '52009230'; +const MEASURES = '00289110'; +const ORIENTATION = '00209116'; +const POSITION = '00209113'; +const SCAN_PATTERN = '00221618'; +const ACQUISITION_PARAMETERS = '00221640'; +// 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: DataSet | undefined, + data: DicomDataset | undefined, sequence: string, attribute: string ) { return stringValue(firstItem(data, sequence), attribute); } -function frameGeometry(data: DataSet) { +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. @@ -70,16 +62,20 @@ function frameGeometry(data: DataSet) { 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, - declaredFrames: data.intString(toDicomParserKey(Tags.NumberOfFrames)), - orientation: attribute(ORIENTATION, IMAGE_ORIENTATION), - spacing: attribute(MEASURES, PIXEL_SPACING), + declaredFrames: Number.parseInt( + stringValue(data, Tags.NumberOfFrames) ?? '', + 10 + ), + 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), }; } @@ -108,7 +104,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.'; @@ -128,14 +124,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 ) ) @@ -144,7 +145,7 @@ function geometryError(geometry: ReturnType) { frameAttributeMismatch( geometry, ORIENTATION, - IMAGE_ORIENTATION, + Tags.ImageOrientationPatient, geometry.orientation ) ) @@ -152,11 +153,11 @@ function geometryError(geometry: ReturnType) { return positionError(geometry); } -function scanPattern(data: DataSet) { +function scanPattern(data: DicomDataset) { 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 +165,7 @@ function scanPattern(data: DataSet) { : patterns[0]; } -function promoteOCTGeometry(data: DataSet, tags: Map) { +function promoteOCTGeometry(data: DicomDataset, tags: Map) { const geometry = frameGeometry(data); const set = (tag: string, value: Maybe) => { if (value) tags.set(tag, value); @@ -172,7 +173,7 @@ function promoteOCTGeometry(data: DataSet, 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); @@ -191,58 +192,14 @@ function promoteOCTGeometry(data: DataSet, tags: Map) { set(Tags.SpacingBetweenSlices, sliceSpacing); } -async function readOCTHeader(file: Blob) { - let length = Math.min(file.size, 64 * 1024); - for (;;) { - const isCompleteFile = length === file.size; - const headerBytes = new Uint8Array( - await file.slice(0, length).arrayBuffer() - ); - let needsCompleteFile = false; - try { - const data = dicomParser.parseDicom(headerBytes, { - untilTag: 'x7fe00010', - vrCallback: (tag) => (sequenceTags.has(tag) ? 'SQ' : undefined), - inflater: (bytes, position) => { - // Inflate only the complete stream, including trailing NULL padding. - if (!isCompleteFile) { - needsCompleteFile = true; - throw new Error('Deflated OCT requires the complete dataset'); - } - const inflated = inflateSync(bytes.subarray(position)); - const complete = new Uint8Array(position + inflated.length); - complete.set(bytes.subarray(0, position)); - complete.set(inflated, position); - // The inflater resumes at zero. Skip the Part 10 header as one OB - // element while retaining the file-meta offsets in the same buffer. - complete.fill(0, 0, 12); - complete.set([0x4f, 0x42], 4); - new DataView(complete.buffer).setUint32(8, position - 12, true); - return complete; - }, - }); - // A successful parse of a prefix can still end between metadata elements. - // Only accept it once the complete Pixel Data header has been reached. - if (isCompleteFile || data.elements.x7fe00010) return data; - } catch (error) { - if (isCompleteFile) throw error; - } - length = needsCompleteFile ? file.size : Math.min(file.size, length * 4); - } -} - -/** Promotes enhanced OCT geometry for the loader. */ -export async function augmentOCTMetadata( - file: Blob, - metadata: Array<[string, string]> -) { +/** 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); - try { - const data = await readOCTHeader(file); - promoteOCTGeometry(data, tags); - } catch { - tags.set(OCT_GEOMETRY_ERROR, 'OCT spatial metadata could not be read.'); - } + promoteOCTGeometry(dataset, tags); return [...tags]; } diff --git a/src/core/streaming/dicom/octMetadataTags.ts b/src/core/streaming/dicom/octMetadataTags.ts index d78a916dd..f287d4ed1 100644 --- a/src/core/streaming/dicom/octMetadataTags.ts +++ b/src/core/streaming/dicom/octMetadataTags.ts @@ -1,4 +1,5 @@ -import { Tags } from '@/src/core/dicomTags'; +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'; @@ -10,11 +11,11 @@ export const OCT_GEOMETRY_ERROR = 'oct:geometry-error'; export function isOCTMetadata(metadata: Iterable<[string, string]>) { const tags = new Map(metadata); - const sop = tags.get(Tags.SOPClassUID)?.trim(); + const sop = trimDicomPadding(tags.get(Tags.SOPClassUID) ?? ''); if (sop === OPHTHALMIC_EN_FACE_SOP) return false; return ( sop === OPHTHALMIC_TOMOGRAPHY_SOP || sop === OPHTHALMIC_BSCAN_ANALYSIS_SOP || - tags.get(Tags.Modality)?.trim() === 'OPT' + trimDicomPadding(tags.get(Tags.Modality) ?? '') === 'OPT' ); } diff --git a/src/core/streaming/dicom/seriesGeometry.ts b/src/core/streaming/dicom/seriesGeometry.ts index 430d41a5e..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 '@/src/core/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { frameGridGeometry, imageDirection, @@ -50,6 +50,20 @@ function seriesPositions(tags: Map[]) { return positions.every((position) => position !== null) ? positions : null; } +function matchesLoadedDirection(actual: ArrayLike, declared: number[]) { + const axes = [declared.slice(0, 3), declared.slice(3, 6)].flatMap((axis) => { + const length = Math.hypot(...axis); + return axis.map((value) => value / length); + }); + // The structured allocator normalizes valid, rounded direction cosines. + const normalized = imageDirection(axes); + return ( + areEquals(Array.from(actual), declared, TOLERANCE) || + (normalized !== null && + areEquals(Array.from(actual), normalized, TOLERANCE)) + ); +} + function loadedGridReason( grid: Grid | undefined, direction: number[], @@ -58,7 +72,7 @@ function loadedGridReason( ) { if ( grid && - (!areEquals(Array.from(grid.direction), direction, TOLERANCE) || + (!matchesLoadedDirection(grid.direction, direction) || !areEquals(Array.from(grid.origin), origin, TOLERANCE) || !near(grid.spacing[2], distance, TOLERANCE)) ) diff --git a/src/core/streaming/dicom/ultrasoundRegion.ts b/src/core/streaming/dicom/ultrasoundRegion.ts deleted file mode 100644 index 3fab3a12b..000000000 --- a/src/core/streaming/dicom/ultrasoundRegion.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { - createDicomParser, - DataElement, -} from '@/src/core/streaming/dicom/dicomParser'; -import { Tags, tagToGroupElement } from '@/src/core/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; -}; - -export const SEQUENCE_OF_ULTRASOUND_REGIONS = tagToGroupElement( - Tags.SequenceOfUltrasoundRegions -); -const PHYSICAL_DELTA_X = tagToGroupElement(Tags.PhysicalDeltaX); -const PHYSICAL_DELTA_Y = tagToGroupElement(Tags.PhysicalDeltaY); -const PHYSICAL_UNITS_X_DIRECTION = tagToGroupElement( - Tags.PhysicalUnitsXDirection -); -const PHYSICAL_UNITS_Y_DIRECTION = tagToGroupElement( - Tags.PhysicalUnitsYDirection -); - -const isTag = (el: DataElement, [group, element]: [number, number]) => - el.group === group && el.element === element; - -const readFloat64LE = (bytes: Uint8Array) => - new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getFloat64( - 0, - true - ); - -const readUint16LE = (bytes: Uint8Array) => - new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint16( - 0, - true - ); - -/** - * Decodes the first item of a SequenceOfUltrasoundRegions element and - * reports the total number of regions found. The first region's spacing - * is what gets applied to the VTK image; the count lets callers warn when - * additional regions exist (multi-region images are only partially - * supported because VTK image data has a single global spacing). - */ -export function decodeUltrasoundRegion( - sequenceData: DataElement['data'] -): UltrasoundRegions { - if (!Array.isArray(sequenceData) || sequenceData.length === 0) { - return { regionCount: 0 }; - } - const [firstItem] = sequenceData; - - const findBytes = (target: [number, number]) => { - const el = firstItem.find((inner) => isTag(inner, target)); - if (!el || !(el.data instanceof Uint8Array)) return undefined; - return el.data; - }; - - const deltaXBytes = findBytes(PHYSICAL_DELTA_X); - const deltaYBytes = findBytes(PHYSICAL_DELTA_Y); - const unitsXBytes = findBytes(PHYSICAL_UNITS_X_DIRECTION); - const unitsYBytes = findBytes(PHYSICAL_UNITS_Y_DIRECTION); - - const regionCount = sequenceData.length; - if (!deltaXBytes || !deltaYBytes || !unitsXBytes || !unitsYBytes) { - return { regionCount }; - } - - return { - region: { - physicalDeltaX: readFloat64LE(deltaXBytes), - physicalDeltaY: readFloat64LE(deltaYBytes), - physicalUnitsXDirection: readUint16LE(unitsXBytes), - physicalUnitsYDirection: readUint16LE(unitsYBytes), - }, - regionCount, - }; -} - -/** - * Parses a DICOM blob and returns the first ultrasound region plus the - * total region count, if a SequenceOfUltrasoundRegions is present. - */ -export async function parseUltrasoundRegionFromBlob( - blob: Blob -): Promise { - let regions: UltrasoundRegions | undefined; - - const parse = createDicomParser({ - stopAtElement(group, element) { - return group === 0x7fe0 && element === 0x0010; - }, - onDataElement(el) { - if (regions) return; - if (isTag(el, SEQUENCE_OF_ULTRASOUND_REGIONS)) { - regions = decodeUltrasoundRegion(el.data); - } - }, - }); - - const stream = blob.stream(); - const reader = stream.getReader(); - try { - while (!regions) { - const { value, done } = await reader.read(); - if (done) break; - const result = parse(value); - if (result.done) break; - } - } catch (err) { - console.warn('Failed to parse SequenceOfUltrasoundRegions:', err); - return undefined; - } finally { - reader.releaseLock(); - } - - return regions; -} diff --git a/src/core/streaming/dicomChunkImage.ts b/src/core/streaming/dicomChunkImage.ts deleted file mode 100644 index 566f5c1be..000000000 --- a/src/core/streaming/dicomChunkImage.ts +++ /dev/null @@ -1,646 +0,0 @@ -import { - readDicomSegmentation, - ReadOverlappingSegmentationMeta, - readVolumeSlice, - splitAndSort as splitAndSortChunks, -} from '@/src/io/dicom'; -import { Chunk, waitForChunkState } from '@/src/core/streaming/chunk'; -import { - Image, - JsonCompatible, - readImage as readItkImage, -} from '@itk-wasm/image-io'; -import { getWorker } from '@/src/io/itk/worker'; -import { - allocateImageFromChunks, - getBufferValueRange, - samplesAreIntegral, - valuesFitBuffer, -} from '@/src/utils/allocateImageFromChunks'; -import { TypedArray } from '@kitware/vtk.js/types'; -import { Tags } from '@/src/core/dicomTags'; -import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; -import { ChunkState } from '@/src/core/streaming/chunkStateMachine'; -import { - type ChunkImage, - ChunkStatus, - ChunkImageEvents, -} from '@/src/core/streaming/chunkImage'; -import mitt, { Emitter } from 'mitt'; -import { - BaseProgressiveImage, - ProgressiveImageStatus, -} from '@/src/core/progressiveImage'; -import { ensureError } from '@/src/utils'; -import { computed } from 'vue'; -import { convertItkToVtkImage } from '@/src/io/convertItkToVtkImage'; -import { unitToMm } from '@/src/core/streaming/dicom/ultrasoundRegion'; -import { isUsableSpacing } from '@/src/utils/imageSpace'; -import { surfaceWarning } from '@/src/store/messages'; - -const { fastComputeRange } = vtkDataArray; - -const DATA_RANGE_KEY = 'pixel-data-range'; - -function getChunkId(chunk: Chunk) { - const metadata = Object.fromEntries(chunk.metadata!); - const SOPInstanceUID = metadata[Tags.SOPInstanceUID]; - return SOPInstanceUID; -} - -// Assume itkImage type is Uint8Array -function itkImageToURI(itkImage: Image) { - const [width, height] = itkImage.size; - const im = new ImageData(width, height); - const arr32 = new Uint32Array(im.data.buffer); - const itkBuf = itkImage.data; - if (!itkBuf) { - return ''; - } - - for (let i = 0; i < itkBuf.length; i += 1) { - const byte = itkBuf[i] as number; - // ABGR order - - arr32[i] = (255 << 24) | (byte << 16) | (byte << 8) | byte; - } - - const canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - const ctx = canvas.getContext('2d'); - if (ctx) { - ctx.putImageData(im, 0, 0); - return canvas.toDataURL('image/png'); - } - return ''; -} - -async function dicomSliceToImageUri(blob: Blob) { - const file = new File([blob], 'file.dcm'); - const itkImage = await readVolumeSlice(file, true); - return itkImageToURI(itkImage); -} - -function readDicomImage(file: File) { - return readItkImage(file, { webWorker: getWorker() }); -} - -export interface DicomChunkImageInit { - splitAndSort: ( - chunks: Chunk[], - mapToBlob: (chunk: Chunk, index: number) => Blob - ) => Promise>; - readDicomImage: (file: File) => Promise<{ - image: Pick & { - imageType: Pick; - }; - }>; - warn: (title: string, details: string) => void; -} - -type DecodedChunkImage = Awaited< - ReturnType ->['image']; - -// The buffer is allocated for the range every chunk's tags declare, so a chunk -// only fails here when its decoded values disagree with its tags. -// TypedArray.set raises nothing for such values: integers wrap and fractions -// truncate. -function assertSamplesRepresentable( - decoded: ArrayLike, - range: { min: number; max: number }, - buffer: TypedArray, - where: string -) { - 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 default class DicomChunkImage - extends BaseProgressiveImage - implements ChunkImage -{ - private splitAndSort: DicomChunkImageInit['splitAndSort']; - private readDicomImage: DicomChunkImageInit['readDicomImage']; - private warn: DicomChunkImageInit['warn']; - protected chunks: Chunk[]; - private chunkListeners: Array<() => void>; - private thumbnailCache: WeakMap>; - private events: Emitter; - private chunkStatus: ChunkStatus[]; - private allocationGeneration: number; - private chunkAdditionQueue: Promise; - - public segBuildInfo: - | (JsonCompatible & ReadOverlappingSegmentationMeta) - | null; - - constructor(init: Partial = {}) { - super(); - - this.splitAndSort = init.splitAndSort ?? splitAndSortChunks; - this.readDicomImage = init.readDicomImage ?? readDicomImage; - this.warn = init.warn ?? surfaceWarning; - - this.status.value = 'incomplete'; - this.loaded = computed(() => { - return !this.loading.value && this.status.value === 'complete'; - }); - - this.chunks = []; - this.chunkListeners = []; - this.chunkStatus = []; - this.thumbnailCache = new WeakMap(); - this.events = mitt(); - this.allocationGeneration = 0; - this.chunkAdditionQueue = Promise.resolve(); - this.segBuildInfo = null; - - this.addEventListener('loading', (loading) => { - this.loading.value = loading; - }); - - this.addEventListener('status', (status) => { - this.status.value = status; - }); - } - - getModality() { - const meta = Object.fromEntries(this.getDicomMetadata() ?? []); - return meta[Tags.Modality]?.trim() ?? null; - } - - getChunkStatuses(): Array { - return this.chunkStatus.slice(); - } - - getDicomMetadata(chunkNum = 0) { - if (chunkNum < 0 || chunkNum >= this.chunks.length) { - throw RangeError('chunkNum is out of bounds'); - } - return this.chunks[chunkNum].metadata; - } - - getChunks() { - return this.chunks.slice(); - } - - addEventListener( - type: T, - callback: (info: ChunkImageEvents[T]) => void - ): void { - this.events.on(type, callback); - } - - removeEventListener( - type: T, - callback: (info: ChunkImageEvents[T]) => void - ): void { - this.events.off(type, callback); - } - - dispose() { - this.allocationGeneration += 1; - super.dispose(); - this.unregisterChunkListeners(); - this.events.all.clear(); - this.chunks.length = 0; - this.vtkImageData.value.delete(); - this.chunkStatus = []; - this.thumbnailCache = new WeakMap(); - } - - startLoad() { - if (this.chunkStatus.every((status) => status === ChunkStatus.Loaded)) - return; - this.chunks.forEach((chunk) => { - chunk.loadData(); - }); - this.events.emit('loading', true); - } - - stopLoad() { - this.chunks.forEach((chunk) => { - chunk.stopLoad(); - }); - this.events.emit('loading', false); - } - - addChunks(chunks: Chunk[]) { - const chunksToAdd = chunks.slice(); - const addition = this.chunkAdditionQueue.then(() => - this.addChunksInOrder(chunksToAdd) - ); - this.chunkAdditionQueue = addition.catch(() => {}); - return addition; - } - - private async addChunksInOrder(chunks: Chunk[]) { - const existingIds = new Set(this.chunks.map((chunk) => getChunkId(chunk))); - const newChunks = chunks.filter( - (chunk) => !existingIds.has(getChunkId(chunk)) - ); - if ( - !newChunks.length && - this.chunkStatus.every((status) => status === ChunkStatus.Loaded) - ) - return; - - this.unregisterChunkListeners(); - newChunks.forEach((chunk) => { - this.chunks.push(chunk); - }); - - await Promise.all(chunks.map((chunk) => chunk.loadMeta())); - const chunksByVolume = await this.splitAndSort( - this.chunks, - (chunk) => chunk.metaBlob! - ); - const volumes = Object.values(chunksByVolume); - if (volumes.length !== 1) - throw new Error('Did not get just a single volume!'); - - // Invalidate decodes targeting the previous buffer and chunk order. - this.allocationGeneration += 1; - this.chunks = volumes[0]; - - this.chunkStatus = this.chunks.map((chunk) => { - switch (chunk.state) { - case ChunkState.Init: - case ChunkState.MetaLoading: - case ChunkState.MetaOnly: - return ChunkStatus.NotLoaded; - case ChunkState.DataLoading: - return ChunkStatus.Loading; - // Loaded pixels belong to the previous allocation. - case ChunkState.Loaded: - return ChunkStatus.Loading; - default: - throw new Error('Chunk is in an invalid state'); - } - }); - this.onChunksUpdated(); - - if (this.getModality() !== 'SEG') { - this.reallocateImage(); - } - - this.registerChunkListeners(); - this.processLoadedChunks(); - - // Update data range with already loaded chunks after reallocating image - if (this.getModality() !== 'SEG') { - this.updateDataRangeFromChunks(); - } - } - - getThumbnail(): Promise { - const middle = Math.floor(this.chunks.length / 2); - const chunk = this.chunks[middle]; - - if (!this.thumbnailCache.has(chunk)) { - // FIXME(fli): if chunk changes, the old promise is not cancelled - this.thumbnailCache.set( - chunk, - waitForChunkState(chunk, ChunkState.Loaded).then((ch) => { - if (!ch.dataBlob) throw new Error('No chunk data'); - return dicomSliceToImageUri(ch.dataBlob); - }) - ); - } - return this.thumbnailCache.get(chunk)!; - } - - // Reallocation clears the buffer, so restore every available slice. - private processLoadedChunks() { - this.chunks.forEach((chunk) => { - if (chunk.state !== ChunkState.Loaded) return; - this.decodeChunk(chunk); - }); - } - - private decodeChunk(chunk: Chunk) { - const generation = this.allocationGeneration; - this.onChunkHasData(chunk, generation).catch((err) => { - if (generation !== this.allocationGeneration) return; - this.onChunkErrored(chunk, err); - }); - } - - private registerChunkListeners() { - this.chunkListeners = [ - ...this.chunks.map((chunk) => { - const stopDoneData = chunk.addEventListener('doneData', () => { - this.decodeChunk(chunk); - }); - - const stopError = chunk.addEventListener('error', (err) => { - this.onChunkErrored(chunk, err); - }); - - return () => { - stopDoneData(); - stopError(); - }; - }), - ]; - } - - private unregisterChunkListeners() { - while (this.chunkListeners.length) { - this.chunkListeners.pop()!(); - } - } - - private reallocateImage() { - // Allocation can throw, and the cache keeps this image either way, so the - // old buffer is only safe to release once its replacement exists. - const previous = this.vtkImageData.value; - this.vtkImageData.value = allocateImageFromChunks(this.chunks); - previous.delete(); - this.applyUltrasoundSpacing(); - } - - private applyUltrasoundSpacing() { - if (this.getModality() !== 'US') return; - - // Ultrasound DICOMs are typically a single multi-frame chunk, so the - // region table on chunk[0] applies to the whole image. If a US series - // ever spanned multiple chunks with differing regions, this would - // silently use the first chunk's spacing for all of them. - const regions = this.chunks[0]?.ultrasoundRegions; - if (!regions?.region) return; - - // VTK image data has a single global spacing, so multi-region images - // (e.g. dual-pane B-mode + Doppler) cannot be fully represented. The - // first region's spacing is applied to the whole image; warn so the - // mismatch on additional panes is at least visible in the console. - if (regions.regionCount > 1) { - console.warn( - `Ultrasound image has ${regions.regionCount} regions; only the first region's physical spacing is applied. Multi-region (e.g. dual-pane B-mode + Doppler) ultrasound is not fully supported.` - ); - } - - const { region } = regions; - 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.` - ); - return; - } - - const spacingX = region.physicalDeltaX * xFactor; - const spacingY = region.physicalDeltaY * yFactor; - if (!isUsableSpacing(spacingX) || !isUsableSpacing(spacingY)) { - this.warn( - 'Invalid ultrasound calibration', - `The ultrasound region declares PhysicalDeltaX=${region.physicalDeltaX} and PhysicalDeltaY=${region.physicalDeltaY}. Measurements use the image pixel spacing instead.` - ); - return; - } - - const [, , zSpacing] = this.vtkImageData.value.getSpacing(); - this.vtkImageData.value.setSpacing([spacingX, spacingY, zSpacing]); - } - - private updateDataRangeFromChunks() { - const scalars = this.vtkImageData.value.getPointData().getScalars(); - const ranges = this.dataRangeFromChunks(); - if (ranges.length > 0) { - ranges.forEach(([min, max], compIdx) => { - scalars.setRange({ min, max }, compIdx); - }); - scalars.modified(); // so image-stats will trigger update of range - } - } - - private dataRangeFromChunks() { - const outputRanges: Array<[number, number]> = []; - this.chunks.forEach((chunk) => { - const ranges = chunk.getUserData(DATA_RANGE_KEY) as - | Array<[number, number]> - | undefined; - if (!ranges) return; - ranges.forEach((range, idx) => { - const curMin = outputRanges[idx]?.[0] ?? range[0]; - const curMax = outputRanges[idx]?.[1] ?? range[1]; - outputRanges[idx] = [ - Math.min(curMin, range[0]), - Math.max(curMax, range[1]), - ]; - }); - }); - - return outputRanges; - } - - private async onChunkHasData(chunk: Chunk, generation: number) { - if (this.getModality() === 'SEG') { - await this.onSegChunkHasData(chunk, generation); - } else { - await this.onRegularChunkHasData(chunk, generation); - } - } - - private async onSegChunkHasData(chunk: Chunk, generation: number) { - if (this.chunks.length !== 1 || this.chunks[0] !== chunk) - throw new Error( - `Cannot handle multiple SEG files. Expected 1 chunk at index 0, got ${this.chunks.length} chunks with current index ${this.chunks.indexOf(chunk)}` - ); - - const results = await readDicomSegmentation( - new File([chunk.dataBlob!], 'seg.dcm') - ); - if (generation !== this.allocationGeneration) return; - - const image = convertItkToVtkImage(results.outputImage); - this.vtkImageData.value.delete(); - this.vtkImageData.value = image; - - this.segBuildInfo = results.metaInfo; - - this.chunkStatus[0] = ChunkStatus.Loaded; - this.onChunksUpdated(); - } - - // The slot layout gives one frame per file, so several files that each carry - // several frames have nowhere to go. - private assertSingleFramePerFile(frames: number, where: string) { - if (frames > 1 && this.chunks.length > 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. - private assertChunkFitsSlot( - image: DecodedChunkImage, - volume: { dims: number[]; componentCount: number }, - where: string - ) { - const { dims, componentCount } = volume; - const multiFile = this.chunks.length > 1; - const framesPerChunk = multiFile ? 1 : dims[2]; - const [chunkWidth, chunkHeight] = image.size; - const chunkFrames = image.size[2] ?? 1; - const chunkComponents = image.imageType.components; - 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 - ); - } - } - - private async onRegularChunkHasData(chunk: Chunk, generation: number) { - const chunkIndex = this.chunks.indexOf(chunk); - if (!chunk.dataBlob) - throw new Error(`Chunk ${chunkIndex} does not have data`); - - const chunkId = chunk.metadata ? getChunkId(chunk) : `index-${chunkIndex}`; - const result = await this.readDicomImage( - new File([chunk.dataBlob], `file-${chunkIndex}.dcm`) - ); - - if (!result.image.data) - throw new Error(`No data read from chunk ${chunkId}`); - - // Only the decode started for the current allocation may update it. - if (generation !== this.allocationGeneration) return; - - // Sorting may have changed across the await; resolve the slot now. - const sliceIndex = this.chunks.indexOf(chunk); - if (sliceIndex === -1) return; - - const where = `File ${chunkId} (chunk ${sliceIndex})`; - this.assertSingleFramePerFile(result.image.size[2], where); - - const scalars = this.vtkImageData.value.getPointData().getScalars(); - const pixelData = scalars.getData(); - const componentCount = scalars.getNumberOfComponents(); - - const dims = this.vtkImageData.value.getDimensions(); - - this.assertChunkFitsSlot(result.image, { dims, componentCount }, where); - - const chunkData = result.image.data as TypedArray; - const chunkDataRange: Array<[number, number]> = []; - for (let comp = 0; comp < componentCount; comp++) { - const { min, max } = fastComputeRange(chunkData, comp, componentCount); - chunkDataRange.push([min, max]); - } - - const chunkMin = Math.min(...chunkDataRange.map(([min]) => min)); - const chunkMax = Math.max(...chunkDataRange.map(([, max]) => max)); - assertSamplesRepresentable( - chunkData, - { min: chunkMin, max: chunkMax }, - pixelData, - where - ); - - const offset = dims[0] * dims[1] * componentCount * sliceIndex; - pixelData.set(chunkData, offset); - - const rangeAlreadyInitialized = this.chunkStatus.some( - (status) => status === ChunkStatus.Loaded - ); - - // update the data range - chunkDataRange.forEach(([min, max], comp) => { - const curRange = scalars.getRange(comp); - const newMin = rangeAlreadyInitialized ? Math.min(min, curRange[0]) : min; - const newMax = rangeAlreadyInitialized ? Math.max(max, curRange[1]) : max; - scalars.setRange({ min: newMin, max: newMax }, comp); - }); - scalars.modified(); // so image-stats will trigger update of range - - chunk.setUserData(DATA_RANGE_KEY, chunkDataRange); - - this.chunkStatus[sliceIndex] = ChunkStatus.Loaded; - this.events.emit('chunkLoad', { - chunk, - updatedExtent: [0, dims[0] - 1, 0, dims[1] - 1, sliceIndex, sliceIndex], - }); - this.onChunksUpdated(); - - this.vtkImageData.value.modified(); - } - - private onChunkErrored(chunk: Chunk, err: unknown) { - // Sorting may have changed since the operation started. - const sliceIndex = this.chunks.indexOf(chunk); - if (sliceIndex === -1) return; - - this.chunkStatus[sliceIndex] = ChunkStatus.Errored; - this.events.emit('chunkError', { - chunk, - error: err, - }); - this.events.emit('error', ensureError(err)); - this.onChunksUpdated(); - } - - // Errored is terminal: a rejected chunk never loads, so waiting on it would - // keep the image loading forever. - private isSettled() { - return this.chunkStatus.every( - (status) => - status === ChunkStatus.Loaded || status === ChunkStatus.Errored - ); - } - - private computeStatus(): ProgressiveImageStatus { - const anyLoaded = this.chunkStatus.some( - (status) => status === ChunkStatus.Loaded - ); - // An image where every chunk errored holds no pixel data, so it is settled - // but never complete. - return this.isSettled() && anyLoaded ? 'complete' : 'incomplete'; - } - - private onChunksUpdated() { - this.events.emit('status', this.computeStatus()); - if (this.isSettled()) { - this.events.emit('loading', false); - } - } -} diff --git a/src/core/streaming/dicomVolumeImage.ts b/src/core/streaming/dicomVolumeImage.ts new file mode 100644 index 000000000..f5880974f --- /dev/null +++ b/src/core/streaming/dicomVolumeImage.ts @@ -0,0 +1,381 @@ +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 '@/src/dicom/core/metadata/datasetAccess'; +import { + loadVolume, + middleSlot, + type Extent, + type VolumeUpdate, +} 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 '@/src/dicom/vtk/volumeImage'; +import { + encodeThumbnailToUri, + type ThumbnailSlice, +} from '@/src/dicom/vtk/thumbnail'; +import { + BaseProgressiveImage, + type ProgressiveImageEvents, +} from '@/src/core/progressiveImage'; +import { + readDicomSegmentation, + type ReadOverlappingSegmentationMeta, +} from '@/src/io/dicom'; +import { convertItkToVtkImage } from '@/src/io/convertItkToVtkImage'; +import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; +import { ensureError } from '@/src/utils'; +import { abortError } from '@/src/dicom/core/utils'; + +type DicomVolumeImageEvents = ProgressiveImageEvents & { + /** A decoded region of the current image, as an inclusive extent. */ + extentLoaded: Extent; +}; + +type SegmentationResult = { + image: vtkImageData; + metadata: JsonCompatible & ReadOverlappingSegmentationMeta; +}; + +export type DicomVolumeImageInit = { + runtime?: Pick< + DicomRuntime, + 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' + >; + readSegmentation?: (file: File) => Promise; + encodeThumbnail?: (slice: ThumbnailSlice) => string; + /** The slice the user is looking at, loaded first; undefined for the middle. */ + focus?: () => number | undefined; +}; + +type Content = + | { kind: 'volume'; volume: Volume; failed: Set } + | { + kind: 'segmentation'; + instances: readonly Instance[]; + loaded: boolean; + /** The last load failed, so no thumbnail is coming. */ + failed: boolean; + }; + +const readSegmentationFile = async (file: File) => { + const result = await readDicomSegmentation(file); + return { + image: convertItkToVtkImage(result.segImage), + metadata: result.metaInfo, + }; +}; + +/** `failed` holds slices, so a frame that failed settles on its own. */ +function volumeSettled({ volume, failed }: Content & { kind: 'volume' }) { + return volume.loaded.every( + (isLoaded, slice) => isLoaded === 1 || failed.has(slice) + ); +} + +const contentComplete = (content: Content | null) => { + if (!content) return false; + if (content.kind === 'segmentation') return content.loaded; + return volumeSettled(content) && content.volume.loaded.includes(1); +}; + +// Nothing is left to read, so starting a load would only flicker `loading`. +const fullyLoaded = (content: Content) => + content.kind === 'segmentation' + ? content.loaded + : content.volume.loaded.every((isLoaded) => isLoaded === 1); + +// The loaded slice nearest the middle, once loading can add no more. +function fallbackSlice(volume: Volume) { + const middle = middleSlot(volume); + const loaded = [...volume.loaded.keys()].filter( + (slice) => volume.loaded[slice] === 1 + ); + if (!loaded.length) return null; + return loaded.reduce((best, slice) => + Math.abs(slice - middle) < Math.abs(best - middle) ? slice : best + ); +} + +/** + * The app's handle on one DICOM dataset: the current volume, its vtkImageData + * and the one load that fills it. A new volume replaces the image and + * restarts loading; disposing aborts it. + */ +export default class DicomVolumeImage extends BaseProgressiveImage { + private content: Content | null = null; + + private load: AbortController | null = null; + + private disposed = false; + + private thumbnail: Promise | null = null; + + /** Settles the pending thumbnail once its slice is known; null when none is pending. */ + private settleThumbnail: (() => void) | null = null; + + private readonly events = mitt(); + + private readonly init: Required> & + Pick; + + public segBuildInfo: SegmentationResult['metadata'] | null = null; + + constructor(init: DicomVolumeImageInit = {}) { + super(); + this.init = { + ...init, + runtime: init.runtime ?? useDicomRuntimeStore().runtime, + readSegmentation: init.readSegmentation ?? readSegmentationFile, + encodeThumbnail: init.encodeThumbnail ?? encodeThumbnailToUri, + }; + this.loaded = computed( + () => !this.loading.value && this.status.value === 'complete' + ); + } + + /** The instances the current image is built from, in planned order. */ + getInstances(): readonly Instance[] { + if (!this.content) return []; + return this.content.kind === 'volume' + ? this.content.volume.members + : this.content.instances; + } + + /** The volume being shown, or null before one is set and for SEG. */ + getVolume() { + return this.content?.kind === 'volume' ? this.content.volume : null; + } + + getModality() { + return getDatasetModality(this.getInstances()[0]?.dataset); + } + + /** Shows a newly allocated volume; slices it already holds stay loaded. */ + setVolume(volume: Volume) { + this.replaceContent({ kind: 'volume', volume, failed: new Set() }); + this.replaceImage(toVtkImageData(volume)); + this.settleThumbnail?.(); + } + + /** A SEG object, which the segmentation reader turns into a labelmap. */ + setSegmentation(instances: readonly Instance[]) { + this.replaceContent({ + kind: 'segmentation', + instances, + loaded: false, + failed: false, + }); + this.settleThumbnail?.(); + } + + startLoad() { + const { content } = this; + if (this.disposed || this.load || !content || fullyLoaded(content)) return; + const controller = new AbortController(); + this.load = controller; + this.setLoading(true); + const run = + content.kind === 'volume' + ? this.loadPixels(content, controller.signal) + : this.loadSegmentation(content, controller.signal); + run + .catch((error) => { + if (!controller.signal.aborted) + this.events.emit('error', ensureError(error)); + }) + .finally(() => { + if (this.load === controller) this.finishLoad(); + }); + } + + stopLoad() { + this.load?.abort(abortError('DICOM loading stopped')); + this.finishLoad(); + } + + getThumbnail(): Promise { + if (this.disposed) return Promise.reject(abortError('Image disposed')); + this.thumbnail ??= new Promise((resolve, reject) => { + this.settleThumbnail = () => { + const slice = this.disposed ? null : this.thumbnailSlice(); + if (slice === undefined) return; + this.settleThumbnail = null; + if (this.disposed) reject(abortError('Image disposed')); + else if (slice === null) resolve(null); + else + resolve( + this.init.encodeThumbnail( + sliceThumbnail(this.vtkImageData.value, slice) + ) + ); + }; + this.settleThumbnail(); + }); + return this.thumbnail; + } + + addEventListener( + type: T, + callback: (info: DicomVolumeImageEvents[T]) => void + ) { + this.events.on(type, callback); + } + + removeEventListener( + type: T, + callback: (info: DicomVolumeImageEvents[T]) => void + ) { + this.events.off(type, callback); + } + + dispose() { + if (this.disposed) return; + this.disposed = true; + this.load?.abort(abortError('Image disposed')); + this.load = null; + this.settleThumbnail?.(); + this.events.all.clear(); + super.dispose(); + this.vtkImageData.value.delete(); + } + + private replaceContent(content: Content) { + this.stopLoad(); + this.content = content; + 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; + if (previous !== image) previous.delete(); + } + + private finishLoad() { + this.load = null; + this.setLoading(false); + } + + private setLoading(loading: boolean) { + if (this.loading.value === loading) return; + this.loading.value = loading; + this.events.emit('loading', loading); + this.settleThumbnail?.(); + } + + private updateStatus() { + const status = contentComplete(this.content) ? 'complete' : 'incomplete'; + if (this.status.value === status) return; + this.status.value = status; + this.events.emit('status', status); + } + + /** Undefined while the slice to show may still load; null for none. */ + private thumbnailSlice() { + const { content } = this; + if (!content) return 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; + return fallbackSlice(content.volume); + } + + private onUpdate( + content: Content & { kind: 'volume' }, + image: vtkImageData, + update: VolumeUpdate + ) { + if ('error' in update) { + const [, , , , first, last] = update.extent; + for (let slice = first; slice <= last; slice += 1) + content.failed.add(slice); + this.events.emit('error', update.error); + } else { + applyVolumeUpdate(image, update); + this.events.emit('extentLoaded', update.extent); + } + // 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?.(); + } + + private async loadPixels( + content: Content & { kind: 'volume' }, + signal: AbortSignal + ) { + const { volume } = content; + const image = this.vtkImageData.value; + content.failed.clear(); + this.forgetSettledThumbnail(); + const updates = loadVolume(volume, { + runtime: this.init.runtime, + signal, + focus: () => this.init.focus?.() ?? middleSlot(volume), + }); + for await (const update of updates) { + // An update yielded just before the abort still reaches this body. + if (signal.aborted) return; + this.onUpdate(content, image, update); + } + } + + private async loadSegmentation( + content: Content & { kind: 'segmentation' }, + signal: AbortSignal + ) { + content.failed = false; + this.forgetSettledThumbnail(); + 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( + `Cannot handle multiple SEG files. Expected 1, got ${content.instances.length}` + ); + const bytes = await readBytes(content.instances[0].source, signal); + const result = await this.init.readSegmentation( + new File([bytes as BlobPart], 'seg.dcm') + ); + if (signal.aborted) { + result.image.delete(); + return; + } + this.segBuildInfo = result.metadata; + this.replaceImage(result.image); + content.loaded = true; + 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 4a70c9eae..000000000 --- a/src/core/streaming/httpCodes.ts +++ /dev/null @@ -1,9 +0,0 @@ -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/src/core/streaming/requestPool.ts b/src/core/streaming/requestPool.ts deleted file mode 100644 index 2804f67d4..000000000 --- a/src/core/streaming/requestPool.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { Deferred, defer } from '@/src/utils'; -import { $fetch } from '@/src/utils/fetch'; - -const DEFAULT_POOL_SIZE = 24; - -let nextId = 0; -function getNextId() { - return ++nextId; -} - -interface FetchRequest { - id: number; - request: RequestInfo | URL; - init: RequestInit | undefined; - deferred: Deferred; -} - -/** - * Fixed-size pool for managing requests. - * - * Requests are processed in the order that they are received. - */ -export class RequestPool { - public readonly poolSize: number; - - private queue: FetchRequest[]; - private inflight: Set; - private fetchFn: typeof fetch; - - constructor(poolSize = DEFAULT_POOL_SIZE, fetchFn: typeof fetch = $fetch) { - this.poolSize = poolSize; - this.queue = []; - this.inflight = new Set(); - this.fetchFn = (input: RequestInfo | URL, init?: RequestInit) => - fetchFn(input, init); - } - - get activeConnections() { - return this.inflight.size; - } - - /** - * Queues up a fetch request. - * - * If an AbortSignal is provided and is triggered prior to - * the request actually starting, it will be removed from the queue. - * @param requestUrl - * @param options - * @returns - */ - fetch = (request: RequestInfo | URL, init?: RequestInit) => { - this.pushToQueue({ - request, - init, - }); - const { deferred } = this.queue.at(-1)!; - - this.processQueue(); - return deferred.promise; - }; - - /** - * Adds a fetch request to the internal queue. - * @param req - * @returns - */ - private pushToQueue(req: Omit) { - const id = getNextId(); - const deferred = defer(); - this.queue.push({ ...req, id, deferred }); - return id; - } - - /** - * Begins processing the queue. - * @returns - */ - private processQueue() { - if (this.inflight.size === this.poolSize) return; - if (this.queue.length === 0) return; - this.startRequest(this.queue.shift()!); - } - - /** - * Acts on a fetch request. - * @param req - */ - private async startRequest(req: FetchRequest) { - const { id, deferred, request, init } = req; - - if (init?.signal?.aborted) { - deferred.reject(init.signal.reason); - this.processQueue(); - return; - } - - this.inflight.add(id); - - try { - const resp = await this.fetchFn(request, init); - deferred.resolve(resp); - } catch (err) { - deferred.reject(err); - } finally { - this.inflight.delete(id); - // continue processing the queue - this.processQueue(); - } - } -} - -let currentRequestPool: RequestPool = new RequestPool(); - -/** - * Gets the current request pool. - * @returns - */ -export const getRequestPool = () => currentRequestPool; - -/** - * Sets the current request pool. - * @param pool - */ -export function setCurrentRequestPool(pool: RequestPool) { - currentRequestPool = pool; -} diff --git a/src/core/streaming/streamingByteReader.ts b/src/core/streaming/streamingByteReader.ts deleted file mode 100644 index 902fd9f1c..000000000 --- a/src/core/streaming/streamingByteReader.ts +++ /dev/null @@ -1,122 +0,0 @@ -import ByteDeque from '@/src/core/streaming/byteDeque.js'; -import { toAscii } from '@/src/utils'; - -/** - * StreamingByteReader - * - * Expects Uint8Array inputs - */ -export default class StreamingByteReader { - protected leftover: ByteDeque; - protected pos = 0; - - constructor() { - this.leftover = new ByteDeque(); - } - - get position() { - return this.pos; - } - - /** - * Seeks along the byte stream. - * - * No negative values. - * @param offset - */ - *seek(offset: number) { - if (offset < 0) { - throw new Error('Offset must not be negative'); - } - - while (this.leftover.size < offset) { - this.leftover.pushEnd(yield); - } - - this.leftover.eraseStart(offset); - this.pos += offset; - } - - /** - * Reads a number of bytes. - * @param length - * @param param1 - * @returns - */ - *read( - length: number, - { peek = false } = {} - ): Generator { - if (length < 0) { - throw new Error('Length must be a positive number'); - } - if (length === 0) return new Uint8Array(); - - while (this.leftover.size < length) { - this.leftover.pushEnd(yield); - } - - const data = this.leftover.popStart(length); - - if (peek) { - this.leftover.pushStart(data); - } else { - this.pos += length; - } - - return data; - } - - /** - * Reads an ASCII string. - * @param length - * @param param1 - * @returns - */ - *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: 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); - } - - *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/src/core/streaming/types.ts b/src/core/streaming/types.ts index 33cdce8b1..c2641e707 100644 --- a/src/core/streaming/types.ts +++ b/src/core/streaming/types.ts @@ -1,51 +1,11 @@ -import { Maybe } from '@/src/types'; -import { Awaitable } from '@vueuse/core'; -import type { UltrasoundRegions } from '@/src/core/streaming/dicom/ultrasoundRegion'; - -export type LoaderEvents = { - error: any; - done: any; -}; - -interface Loader { - load(): Awaitable; - stop(): Awaitable; -} - -/** - * A metadata loader. - */ -export interface MetaLoader extends Loader { - meta: Maybe>; - metaBlob: Maybe; - ultrasoundRegions?: UltrasoundRegions; -} - -/** - * A data loader. - */ -export interface DataLoader extends Loader { - data: Maybe; -} - -/** - * Init options for a Fetcher. - */ -export interface FetcherInit { - abortController?: AbortController; -} - /** - * A fetcher that caches an incoming stream. + * A source of bytes that can be streamed from the start or taken whole. */ -export interface Fetcher { +export type Fetcher = { connect(): Promise; getStream(): ReadableStream; blob(): Promise; close(): void; - cachedChunks: Uint8Array[]; connected: boolean; - size: number; contentType?: string; - abortSignal?: AbortSignal; -} +}; diff --git a/src/dicom/README.md b/src/dicom/README.md new file mode 100644 index 000000000..dc30f5ea7 --- /dev/null +++ b/src/dicom/README.md @@ -0,0 +1,75 @@ +# Browser DICOM module + +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; callers import each name from the file that +defines it. + +## Layout + +| 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 slice thumbnails | + +`core` uses no Vue, Pinia, vtk.js or VolView application code. `vtk` shows a +core `Volume` as a `vtkImageData`. `eslint.config.js` enforces both boundaries. + +## Invariants + +- Instances, collection updates and volumes are plain values. Only the + runtime from `createDicomRuntime` holds resources (request pool, metadata + workers, GDCM workers), and only it has `dispose()`. Importing a file starts + no worker and touches no DOM. +- Every asynchronous operation takes an `AbortSignal`; aborting it is the + whole of cancellation. +- A `ByteSource` opens a fresh stream per read and holds nothing between + reads. Instances keep no bytes; read the source again for them. +- `readInstance` stops reading at Pixel Data, or after Modality for + radiotherapy objects. The dataset omits private elements. +- `registerInstances` is a pure reducer: abandoning an import is not + 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, 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 + goes on. Stopping ends the iteration without throwing and writes nothing + more. +- At most `readConcurrency` units are being read or waiting to decode, and at + most `decodeConcurrency` decode at once, per volume. +- A URL source whose server ignores Range has its remaining ranged units read + in one request. +- `nativeFrameDecoder` accepts only instances whose result is identical to + GDCM's. The default table sends other instances whole to GDCM in a worker, + and fails JPIP, video and JPEG XL syntaxes as having no decoder. + +## Spacing + +Missing physical spacing is permitted for some DICOM objects, such as +secondary captures. A fallback spacing of 1 does not establish a millimeter +scale, and a singleton axis does not establish a distance between slices. +Calibrated placement between OCT B-scans, vendor ultrasound volume +calibration, RT dose semantics and gated NM are not supported. + +## Tests + +Module unit tests sit in `__tests__` beside the code. Browser pages in +`tests/fixtures/dicom-pages` exercise the module without VolView startup; +the `dicom-*.e2e.ts` specs drive them against generated instances and pinned +public corpora described in `tests/dicomVolumeCorpus.json` and +`tests/dicomCompositionCorpus.json`. diff --git a/src/dicom/core/collections/__tests__/assignCollectionIds.spec.ts b/src/dicom/core/collections/__tests__/assignCollectionIds.spec.ts new file mode 100644 index 000000000..74e0c187d --- /dev/null +++ b/src/dicom/core/collections/__tests__/assignCollectionIds.spec.ts @@ -0,0 +1,212 @@ +import { describe, it, expect } from 'vitest'; +import { assignIds, encodeCollectionKey } from '../assignCollectionIds'; +import { ORIENTATION_TOLERANCE } from '../orientation'; +import { planDicomCollections } from '../planDicomCollections'; +import type { CollectionKey, DicomCollection } from '../planDicomCollections'; +import { + IDENTITY_ORIENTATION, + 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)), + reconstruction: { kind: 'regular', sliceSpacing: null }, + orientation: [1, 0, 0, 0, 1, 0], + label: null, + warnings: [], +}); + +const idsOf = (collections: Array<{ id: string }>) => + collections.map((c) => c.id); + +describe('encodeCollectionKey', () => { + it('keeps a series apart from another whose key ends in the separator', () => { + const plain: CollectionKey = { + seriesKey: SERIES_KEY, + parts: [ + ['rows', '4'], + ['columns', '8'], + ], + }; + const smuggled: CollectionKey = { + seriesKey: `${SERIES_KEY}|rows=4`, + parts: [['columns', '8']], + }; + + expect(encodeCollectionKey(smuggled)).not.toBe(encodeCollectionKey(plain)); + }); +}); + +describe('assignIds', () => { + it('mints the encoded key when nothing is committed', () => { + const collection = collectionOf(['a', 'b']); + + const collections = assignIds([collection], []); + + expect(collections[0].id).toBe(encodeCollectionKey(collection.key)); + }); + + it('keeps the committed id when key and members are unchanged', () => { + const collection = collectionOf(['a', 'b']); + const committed = [{ id: 'visible-1', sopInstanceUids: ['a', 'b'] }]; + + const collections = assignIds([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.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).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', () => { + 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 = [ + { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, + ]; + + const collections = assignIds([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 = [ + { id: 'visible-1', sopInstanceUids: ['a', 'b', 'c', 'd'] }, + ]; + + const collections = assignIds([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 = [{ id: 'visible-1', sopInstanceUids: ['x', 'y'] }]; + + const collections = assignIds([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 = [ + { + id: encodeCollectionKey(collection.key), + sopInstanceUids: ['x'], + }, + ]; + + const collections = assignIds([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 = [ + { id: 'small', sopInstanceUids: ['a', 'b'] }, + { id: 'large', sopInstanceUids: ['c', 'd', 'e'] }, + ]; + + const collections = assignIds([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 = [ + { id: 'zeta', sopInstanceUids: ['a', 'b'] }, + { id: 'alpha', sopInstanceUids: ['c', 'd'] }, + ]; + + const collections = assignIds([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 = [{ id: 'visible-1', sopInstanceUids: ['a'] }]; + + const collections = assignIds([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 = [{ id: 'visible-1', sopInstanceUids: ['a'] }]; + + const collections = assignIds([collection], committed); + + expect(collections[0].id).not.toBe('visible-1'); + }); +}); diff --git a/src/dicom/core/collections/__tests__/idcSeriesFixtures.ts b/src/dicom/core/collections/__tests__/idcSeriesFixtures.ts new file mode 100644 index 000000000..0c37f42d5 --- /dev/null +++ b/src/dicom/core/collections/__tests__/idcSeriesFixtures.ts @@ -0,0 +1,138 @@ +import { Tags } from '../../metadata/dicomTags'; + +/** + * Real Imaging Data Commons (IDC) series behind the acquisition-split rules. + * + * 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: + * + * from idc_index import IDCClient + * IDCClient().download_from_selection( + * seriesInstanceUID='', downloadDir='.') + * + * The groups mirror 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[]; +}; + +const steps = (start: number, count: number, step: number) => + Array.from({ length: count }, (_, i) => start + i * step); + +// 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), +})); + +// 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), +})); + +// 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), + }, +]; + +// 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', + [Tags.EchoNumbers]: '1', + [Tags.DiffusionBValue]: String(bValue), + }, + zs: steps(-67.0785, 30, 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), + }, +]; + +// 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', + }, + 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/src/dicom/core/collections/__tests__/instanceFacts.spec.ts b/src/dicom/core/collections/__tests__/instanceFacts.spec.ts new file mode 100644 index 000000000..c37a7bb1b --- /dev/null +++ b/src/dicom/core/collections/__tests__/instanceFacts.spec.ts @@ -0,0 +1,350 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, expect, it } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import { + readInstanceDetails, + seriesKeyOf as structuredSeriesKeyOf, +} from '../instanceFacts'; + +const INSTANCE_NUMBER_TAG = '0020|0013'; + +// 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'], + [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('instance facts', () => { + it('reads every fact the planner compares', () => { + expect(factsOf(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(factsOf([])).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([ + ['SequenceName', Tags.SequenceName, 'sequenceName'], + ['Rows', Tags.Rows, 'rows'], + ] as const)( + 'reads a zero length %s as absent, not as an empty string', + (_name, tag, fact) => { + expect(factsOf(metadata({ [tag]: '' }))[fact]).toBeNull(); + expect(factsOf(metadata({ [tag]: ' ' }))[fact]).toBeNull(); + } + ); + + 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( + factsOf(metadata({ [Tags.SeriesDate]: '00240101 ' })).seriesDate + ).toBe('00240101'); + }); + + it('keeps a sequence name as text', () => { + expect( + factsOf(metadata({ [Tags.SequenceName]: '007 ' })).sequenceName + ).toBe('007'); + }); + + it('trims the padding DICOM adds to odd length identifiers', () => { + const facts = factsOf( + 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 = factsOf(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 = factsOf(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 = factsOf(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 = 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 = factsOf( + 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 = factsOf(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 = factsOf( + 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('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( + 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 = factsOf( + metadata({ [Tags.ImageOrientationPatient]: '0\\0\\1\\0\\1\\0' }) + ); + expect(facts.projectedPosition).toBeCloseTo(-10, 10); + }); + + it.each([ + ['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(); + }); + + it.each([ + ['5 ', 5], + ['+5', 5], + ['-3', -3], + ])('reads the instance number %s as a number', (value, expected) => { + expect( + factsOf(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(factsOf(entries).instanceNumber).toBeNull(); + }); +}); + +describe('seriesKeyOf', () => { + 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' + ); + }); + + 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')); + }); +}); + +function factsOf(tags: Iterable) { + return readInstanceDetails(datasetFromTags(tags)).facts; +} +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( + factsOf(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( + factsOf(metadata({ [Tags.PixelSpacing]: value })).pixelSpacing + ).toEqual([0.5, 0.75]); + } + ); +}); diff --git a/src/dicom/core/collections/__tests__/instanceFactsFixture.ts b/src/dicom/core/collections/__tests__/instanceFactsFixture.ts new file mode 100644 index 000000000..bd8af1cf8 --- /dev/null +++ b/src/dicom/core/collections/__tests__/instanceFactsFixture.ts @@ -0,0 +1,57 @@ +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), +]; + +// 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/src/dicom/core/collections/__tests__/instanceRegistry.spec.ts b/src/dicom/core/collections/__tests__/instanceRegistry.spec.ts new file mode 100644 index 000000000..783a7536e --- /dev/null +++ b/src/dicom/core/collections/__tests__/instanceRegistry.spec.ts @@ -0,0 +1,436 @@ +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, + registerInstances, +} from '../instanceRegistry'; +import { mergingInstances, tilt } 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; + +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 })); + + 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); + }); + + // 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]]], + ['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).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', () => { + 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[0]).toBe(original); + expect(second.updates[0].provenance[0]).toBe(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.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, unchanged }) => [ + id, + members[0], + unchanged, + ]) + ).toContainEqual([idOf(clips[1]), clips[1], true]); + expect( + again.updates.find((update) => update.members[0] === clips[0])!.unchanged + ).toBe(false); + }); + + 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', () => { + const { between, straight, tilted } = mergingInstances(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('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.unchanged) + ); + + expect(changes).toEqual([[false], [true], [false]]); + }); + + 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, unchanged, collection }) => [ + id === first.updates[0].id, + unchanged, + collection.label, + ]) + ).toEqual([ + [true, true, 'acquisition 1'], + [false, false, '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 [first, second, third] = registerAll([ + acquisition('1', [0, 2]), + [scout], + acquisition('2', [1, 3]), + ]); + + expect( + second.updates + .map(({ members, unchanged, collection }) => [ + sopsOf(members), + unchanged, + collection.label, + ]) + .sort() + ).toEqual([ + [['1-0', '1-2'], true, 'rows 4'], + [['scout'], false, '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 + )!; + expect(sopsOf(relabelled.members)).toEqual(['1-0', '1-2']); + expect(relabelled.collection.label).toBe('rows 4, acquisition 1'); + expect(third.removed).toEqual([]); + }); + + // 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( + 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', () => { + // Within the orientation tolerance, so one bucket, but leaning the normal. + const tilted = '1\\0\\0\\0\\0.99995\\0.0099998'; + + 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.unchanged).toBe(false); + }); + + 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]); + + registerInstances(state, [slice({ sop: 'b', z: 1 })]); + const retried = slice({ sop: 'b', z: 1 }); + const { updates } = registerInstances(state, [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', () => { + 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, + 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); + }); + + it('drops an emptied series from the state', () => { + const only = slice(); + const { state, updates } = registerInstances(emptyRegistry, [only]); + const forgotten = forgetCollection(state, updates[0].id); + expect(forgotten.size).toBe(0); + }); +}); diff --git a/src/dicom/core/collections/__tests__/multiframeGeometry.spec.ts b/src/dicom/core/collections/__tests__/multiframeGeometry.spec.ts new file mode 100644 index 000000000..2218ae828 --- /dev/null +++ b/src/dicom/core/collections/__tests__/multiframeGeometry.spec.ts @@ -0,0 +1,111 @@ +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) => + planDicomCollections({ + seriesKey: 'frames', + 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('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(), + [0, 1, 0, 1].map((z) => positioned(`0\\0\\${z}`)), + { '00080060': 'SEG' } + ); + expect(collectionOf(metadata).warnings).toEqual([]); + }); +}); diff --git a/src/dicom/core/collections/__tests__/planDicomCollections.spec.ts b/src/dicom/core/collections/__tests__/planDicomCollections.spec.ts new file mode 100644 index 000000000..0b650d6bc --- /dev/null +++ b/src/dicom/core/collections/__tests__/planDicomCollections.spec.ts @@ -0,0 +1,711 @@ +import { describe, it, expect } from 'vitest'; +import { ORIENTATION_TOLERANCE } from '../orientation'; +import { + IN_PLANE_SHIFT_WARNING, + NONPARALLEL_SLICES_WARNING, + IRREGULAR_VOLUME_WARNING, + REPEATED_POSITIONS_WARNING, + planDicomCollections, +} from '../planDicomCollections'; +import type { DicomCollection, InstanceFacts } from '../planDicomCollections'; +import { + IDENTITY_ORIENTATION, + clone, + makeFacts, + 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; +} + +// 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([]); + }); + + 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].members[0]).toBe(a); + expect(collections[0].members[1]).toBe(b); + expect(collections[0].label).toBeNull(); + expect(collections[0].warnings).toEqual([]); + }); + + 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 %s differing as %j', + (_rule, facts) => { + const a = makeFacts('uid-a'); + const b = makeFacts('uid-b', facts); + + 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']); + } + ); + + 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('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(collectionWith(collections, 'uid-b').orientation).toEqual( + tiltedOrientation(BEYOND) + ); + }); + + 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).toHaveLength(2); + expect(uidsOf(collectionWith(forward, 'uid-a'))).toEqual([ + 'uid-a', + 'uid-b', + ]); + expect(uidsOf(collectionWith(forward, '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 [x, y, z] = [0, CHAIN, 2 * CHAIN].map((theta, position) => + makeFacts(null, { + orientation: tiltedOrientation(theta), + projectedPosition: position, + }) + ); + const forward = plan([x, y, z]); + + 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('buckets an unreadable orientation on its own', () => { + const a = makeFacts('uid-a'); + const b = makeFacts('uid-b', { orientation: null }); + + const collections = plan([a, b]); + + expect(collections).toHaveLength(2); + 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]); + + expect(collections).toHaveLength(1); + expect(collections[0].members).toHaveLength(2); + }); + + 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']); + }); + + // 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].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']); + }); + + 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']); + }); + + it('breaks a shared position between anonymous members on instance number', () => { + 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]); + 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']); + expect(collectionWith(collections, 'uid-b').label).toBeNull(); + + const unknown = collectionWith(collections, 'uid-a'); + expect(uidsOf(unknown)).toEqual(['uid-c', 'uid-a']); + expect(unknown.label).toBe('position unknown'); + expect(unknown.warnings).toEqual([]); + }); + + 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].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('names 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').label).toBe('position unknown'); + }); + + it('orders a positionless stack on instance number, then SOP Instance UID', () => { + const second = makeFacts('uid-b', { + projectedPosition: null, + instanceNumber: 4, + }); + const first = makeFacts('uid-a', { + projectedPosition: null, + instanceNumber: 4, + }); + const earlier = makeFacts('uid-c', { + projectedPosition: null, + instanceNumber: 1, + }); + + const collections = plan([second, first, earlier]); + + expect(uidsOf(collections[0])).toEqual(['uid-c', 'uid-a', 'uid-b']); + expect(collections[0].label).toBeNull(); + }); + + it('keeps 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']); + }); + + 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).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, 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 members = collections.flatMap((c) => c.members); + + expect(collections).toHaveLength(5); + expect(members).toHaveLength(instances.length); + expect(new Set(members)).toEqual(new Set(instances)); + expect(new Set(collections.map((c) => JSON.stringify(c.key))).size).toBe( + collections.length + ); + }); +}); + +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, + }) + ); + + // 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'); + 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])); + + expect(collections).toHaveLength(1); + expect(collections[0].warnings).toEqual([IRREGULAR_VOLUME_WARNING]); + }); + + 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([]); + }); + + 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(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)[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)); + const after = plan(clips.slice(1)); + 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 and unlabelled 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); + 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 + ); + 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)( + '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('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([ + makeFacts('unknown', { sequenceName: null }), + makeFacts('known', { sequenceName: '*ep_b0' }), + ]); + + expect(collections.map((collection) => collection.label).sort()).toEqual([ + 'sequence *ep_b0', + 'sequence unknown', + ]); + }); + + 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, + }); + }); + + 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(1); + expect(collections[0].reconstruction.kind).toBe('regular'); + }); + + 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('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.map((collection) => collection.label).sort()).toEqual([ + 'sequence first', + 'sequence second', + ]); + expect(collections.flatMap((collection) => collection.warnings)).toEqual( + [] + ); + }); +}); diff --git a/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts b/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts new file mode 100644 index 000000000..92c030574 --- /dev/null +++ b/src/dicom/core/collections/__tests__/reconstructVolume.spec.ts @@ -0,0 +1,233 @@ +import { describe, expect, it } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import { reconstructVolume } from '../reconstructVolume'; +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)); + +// 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, { + 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', () => { + const result = reconstructVolume(stack([-10, -6, -2, 2, 6])); + + expect(result.kind).toBe('regular'); + expect(result.sliceSpacing).toBeCloseTo(4, 12); + }); + + 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(); + }); + + it('accepts a single plane without patient position or orientation', () => { + expect( + reconstructVolume([ + { + orientation: null, + position: null, + pixelSpacing: null, + }, + ]) + ).toEqual({ kind: 'regular', sliceSpacing: null }); + }); + + 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, so no lattice holds them. + it('calls the bilateral sagittal slabs an irregular stack', () => { + const members = stack( + bilateralSagittalSlabs + .flatMap((group) => group.zs) + .sort((left, right) => left - right) + ); + + const result = reconstructVolume(members); + + expect(members).toHaveLength(66); + expect(result.kind).toBe('irregular'); + expect(result).toMatchObject({ reason: 'uneven-slice-spacing' }); + // 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', () => { + 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 result = reconstructVolume([...stack([0, 4]), slice(null)]); + + 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 = slice(null, { + tags: { [Tags.ImagePositionPatient]: '0\\30\\8' }, + }); + + 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); + }); + + it('reports two in-plane sample spacings as irregular', () => { + const coarse = slice(8, { tags: { [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 result = reconstructVolume( + [0, 4, 8].map((z) => slice(z, { orientation: null })) + ); + + expect(result).toMatchObject({ + kind: 'irregular', + reason: 'unreadable-geometry', + }); + 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(1, 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', + }); + }); + + 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/src/dicom/core/collections/__tests__/sliceFixture.ts b/src/dicom/core/collections/__tests__/sliceFixture.ts new file mode 100644 index 000000000..9e3124563 --- /dev/null +++ b/src/dicom/core/collections/__tests__/sliceFixture.ts @@ -0,0 +1,63 @@ +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'; + +export type SliceOptions = { + sop?: string | null; + series?: string | null; + z?: number | null; + rows?: string; + orientation?: string | null; + instanceNumber?: number | null; + modality?: string; + // Extra tags, keyed 'gggg|eeee'; a fixed tag given here is replaced. + tags?: Record; +}; + +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 { + sop = `sop-${(sopCounter += 1)}`, + series = SERIES_UID, + z = 0, + rows = '4', + orientation = '1\\0\\0\\0\\1\\0', + instanceNumber = 1, + modality = 'MR', + tags = {}, + } = options; + + 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(Tags.InstanceNumber, instanceNumber), + ...Object.entries(tags), + ]) + ); +} + +/** 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/src/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts b/src/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts new file mode 100644 index 000000000..ae2f84d08 --- /dev/null +++ b/src/dicom/core/collections/__tests__/splitOverlappingAcquisitions.spec.ts @@ -0,0 +1,427 @@ +import { describe, it, expect } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +import type { InstanceFacts } from '../planDicomCollections'; +import { splitOverlappingAcquisitions } from '../splitOverlappingAcquisitions'; +import { makeFacts } from './instanceFactsFixture'; +import { + bilateralSagittalSlabs, + dceEightPhase, + dixonDualEcho, + dixonUnevenEchoes, + doubledAcquisition, + dwiMultiBValue, + partialTemporalTags, + type SliceGroup, +} from './idcSeriesFixtures'; +import { sliceFacts } from './sliceFixture'; + +type SemanticPart = ReturnType[number]; + +const zOf = (facts: InstanceFacts) => facts.projectedPosition as number; +const byPosition = (a: InstanceFacts, b: InstanceFacts) => zOf(a) - zOf(b); + +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) => + Array.from({ length: count }, (_, i) => + slice(start + i * step, { [Tags.AcquisitionNumber]: acquisition }) + ); + +// Slices mirroring a real IDC series recorded in idcSeriesFixtures.ts. +const fixtureSlices = (groups: SliceGroup[]) => + 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; +}; + +describe('splitOverlappingAcquisitions', () => { + it('passes a single acquisition through as one unlabelled part', () => { + const members = stack('1', 0, 5); + + const parts = split(members); + + expect(parts).toHaveLength(1); + expect(parts[0]).toMatchObject({ + members, + label: null, + repeatedPositions: false, + unreadablePositions: false, + }); + }); + + 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 = split([...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(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 = split(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 = split(groups.flat().sort(byPosition)); + + expect(parts).toHaveLength(1); + }); + + 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 = split(members); + + 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', () => { + // 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 = split(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 = split(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 = split([...scans, ...remainder].sort(byPosition)); + + expect(labels(parts)).toEqual([ + `${rule} 1`, + `${rule} 2`, + `${rule} mixed`, + ]); + expect(partLabelled(parts, `${rule} mixed`).members).toEqual(remainder); + } + ); + + 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 = split([...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 = split([...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(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(split(merged)).toHaveLength(1); + }); + + 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 = split([blind, ...first, ...second]); + + // The two overlapping acquisitions stay separated, and the member nothing + // 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(parts.filter((part) => part.unreadablePositions)).toEqual([unknown]); + }); + + 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 = split(blind); + + expect(parts).toHaveLength(1); + expect(parts[0].members).toEqual(blind); + expect(parts[0].unreadablePositions).toBe(true); + }); + + it('is invariant to member permutation in membership', () => { + const acq1 = stack('1', -20, 5); + const acq2 = stack('2', -19.25, 6); + const forward = split([...acq1, ...acq2]); + const backward = split([...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)); + }); +}); + +describe('splitOverlappingAcquisitions temporal and echo axes', () => { + it('separates DCE timepoints that re-scan one range', () => { + 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(parts.every((part) => !part.repeatedPositions)).toBe(true); + }); + + it('separates Dixon echoes that nothing else distinguishes', () => { + const parts = split(fixtureSlices(dixonDualEcho)); + + expect(labels(parts)).toEqual(['echo 1', 'echo 2']); + }); + + it('separates echoes with unequal slice counts', () => { + 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 = split(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 = split([...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]); + }); + + 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 = split(members); + + expect(labels(parts)).toEqual(['echo 1', 'echo 2']); + expect(parts.every((part) => !part.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 = 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 = split(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('splits a doubled acquisition and still flags the repetition', () => { + const parts = split(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. + 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 = split(merged); + + expect(labels(parts)).toEqual([ + 'phase 1, echo 1', + 'phase 1, echo 2', + 'phase 2, echo 1', + 'phase 2, echo 2', + ]); + parts.forEach((part) => { + expect(part.members).toHaveLength(10); + }); + }); +}); diff --git a/src/dicom/core/collections/assignCollectionIds.ts b/src/dicom/core/collections/assignCollectionIds.ts new file mode 100644 index 000000000..6859061b0 --- /dev/null +++ b/src/dicom/core/collections/assignCollectionIds.ts @@ -0,0 +1,84 @@ +import type { CollectionKey, DicomCollection } from './planDicomCollections'; + +export type CommittedCollection = { + id: string; + sopInstanceUids: string[]; +}; + +// The series key is escaped because mint only de-duplicates within a series. +export function encodeCollectionKey(key: CollectionKey) { + return [ + encodeURIComponent(key.seriesKey), + ...key.parts.map( + ([rule, value]) => `${rule}=${encodeURIComponent(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( + planned: DicomCollection[], + committedIds: CommittedCollection[] +) { + const plannedUids = planned.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((uids) => + overlapSize(uids, 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)); + + 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 }; + }); +} diff --git a/src/dicom/core/collections/datasetDetails.ts b/src/dicom/core/collections/datasetDetails.ts new file mode 100644 index 000000000..186726715 --- /dev/null +++ b/src/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/src/dicom/core/collections/groupBy.ts b/src/dicom/core/collections/groupBy.ts new file mode 100644 index 000000000..ba0f8fdfe --- /dev/null +++ b/src/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: readonly T[], keyOf: (item: T) => K) => { + 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/src/dicom/core/collections/instanceFacts.ts b/src/dicom/core/collections/instanceFacts.ts new file mode 100644 index 000000000..820e237b2 --- /dev/null +++ b/src/dicom/core/collections/instanceFacts.ts @@ -0,0 +1,200 @@ +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'; + +// 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) ?? ''); + 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: number +) => { + const parts = getFrameTag(metadata, tag, frameIndex) + ?.split('\\') + .map(trimDicomPadding); + if (parts?.length !== length || !parts.every(Boolean)) return null; + const values = parts.map(Number); + return 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. + */ +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 }; +} + +// 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, led by its Series Instance UID. + * Instances of different series are planned independently. + */ +export function seriesKeyOf(metadata: DicomDataset) { + const seriesUid = textOf(metadata, Tags.SeriesInstanceUID); + 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, + studyUid, + encodeURIComponent(textOf(metadata, Tags.PatientID) ?? ''), + ].join('|'); +} diff --git a/src/dicom/core/collections/instanceKey.ts b/src/dicom/core/collections/instanceKey.ts new file mode 100644 index 000000000..26cc2ba8d --- /dev/null +++ b/src/dicom/core/collections/instanceKey.ts @@ -0,0 +1,16 @@ +import type { InstanceFacts } from './planDicomCollections'; + +const anonymousKeys = new WeakMap(); +let nextAnonymousKey = 0; + +// 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) => { + 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/src/dicom/core/collections/instanceRegistry.ts b/src/dicom/core/collections/instanceRegistry.ts new file mode 100644 index 000000000..b4cc3d51a --- /dev/null +++ b/src/dicom/core/collections/instanceRegistry.ts @@ -0,0 +1,252 @@ +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, type CommittedCollection } from './assignCollectionIds'; +import { seriesKeyOf } from './instanceFacts'; +import { readDatasetDetails } from './datasetDetails'; +import { groupBy } from './groupBy'; +import type { Reconstruction } from './reconstructVolume'; + +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[]; + /** 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 +// 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[]; + 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 = { + 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() }; + +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) => ({ + key: keyOf(instance), + instance, + facts: { ...readDatasetDetails(instance.dataset).facts }, +}); + +// 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 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; + +const sameVolume = (before: Committed, after: Committed) => + sameList(before.members, after.members) && + sameList(before.orientation, after.orientation) && + sameReconstruction(before.reconstruction, after.reconstruction); + +const sameDescription = (before: Committed | undefined, after: Committed) => + !before || + (before.label === after.label && sameList(before.warnings, after.warnings)); + +// 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.map(({ id, ...collection }) => { + const entries = collection.members.map((facts) => entryOf.get(facts)!); + const committed: Committed = { + members: entries.map((entry) => entry.key), + orientation: collection.orientation, + reconstruction: collection.reconstruction, + label: collection.label, + warnings: collection.warnings, + }; + const members = entries.map((entry) => entry.instance); + const previous = series.committed.get(id); + const unchanged = !!previous && sameVolume(previous, committed); + const update: InstanceCollectionUpdate = { + id, + collection, + members, + provenance: entries.map(provenanceOf), + unchanged, + }; + // A replan can move members or relabel a collection the batch brought nothing. + const changed = + !unchanged || + !sameDescription(previous, committed) || + committed.members.some((key) => supplied.has(key)); + 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 header facts 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; +} diff --git a/src/dicom/core/collections/multiframeGeometry.ts b/src/dicom/core/collections/multiframeGeometry.ts new file mode 100644 index 000000000..94f46fd03 --- /dev/null +++ b/src/dicom/core/collections/multiframeGeometry.ts @@ -0,0 +1,76 @@ +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, + 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]; + 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[]) => + [STACK_ID, TEMPORAL_POSITION_INDEX].every((tag) => { + const values = groups + .map((group) => + trimDicomPadding( + getDatasetTag(sequenceItems(group, FRAME_CONTENT)[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, SHARED_GROUPS); + if (count < 2 || (shared.length === 0 && groups.length === 0)) return null; + // 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); + 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, + }; + return { ...first, direction, reconstruction: validated }; +} diff --git a/src/dicom/core/collections/orientation.ts b/src/dicom/core/collections/orientation.ts new file mode 100644 index 000000000..1529fe569 --- /dev/null +++ b/src/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/src/dicom/core/collections/planDicomCollections.ts b/src/dicom/core/collections/planDicomCollections.ts new file mode 100644 index 000000000..37d7ca924 --- /dev/null +++ b/src/dicom/core/collections/planDicomCollections.ts @@ -0,0 +1,401 @@ +import { orientationsAgree } from './orientation'; +import { groupBy } from './groupBy'; +import { instanceKey } from './instanceKey'; +import { + 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 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. + 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; + /** Geometry of the frames within one instance. */ + 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 DicomCollection = { + key: CollectionKey; + // Ordered by position when every one reads, else by instance number when + // every one reads, else as given. + members: InstanceFacts[]; + // 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; + // Conditions the user should hear about: the collection loads, but not as + // the sound volume its series promised. + warnings: string[]; +}; + +type PlanInput = { + seriesKey: string; + instances: InstanceFacts[]; +}; + +// The hard facts, in the order they appear in a collection key. +const HARD_FACT_RULES = [ + 'rows', + 'columns', + 'samplesPerPixel', + 'numberOfFrames', +] as const; + +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 ' + + '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 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 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]; +}; + +// 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); + +// 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; +}; + +// 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) || + compareNumber(left.projectedPosition, right.projectedPosition) || + compareNumber(left.instanceNumber, right.instanceNumber); + +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]); + +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 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. +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); + +const orderMembers = (members: InstanceFacts[], positionOf: PositionOf) => { + if (members.every((m) => readableNumber(positionOf(m)))) + return [...members].sort(comparePosition(positionOf)); + if (members.every((m) => readableNumber(m.instanceNumber))) + return [...members].sort(compareInstanceNumber); + return [...members]; +}; + +export function planDicomCollections({ seriesKey, instances }: PlanInput) { + const labelHardFacts = hardFactLabeler(instances); + + const multiframe = (instance: InstanceFacts) => + Number(instance.numberOfFrames) > 1; + const groups = [ + ...groupBy( + instances.filter((instance) => !multiframe(instance)), + hardFactSignature + ).values(), + ...instances.filter(multiframe).map((instance) => [instance]), + ]; + const parts = 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, + })) + ); + + // Only a slice kept out of a volume of its series is named for its position. + const placed = parts.some(({ part }) => !part.unreadablePositions); + const unreadableLabel = (unreadable: boolean) => + unreadable && placed ? UNREADABLE_POSITION_LABEL : null; + + return parts + .map(({ group, bucket, positionOf, part }) => { + const members = orderMembers(part.members, positionOf); + const reconstruction = reconstructInstances(members, bucket.normal); + const key: CollectionKey = { + seriesKey, + parts: [ + ...hardFactParts(group[0]), + [ORIENTATION_RULE, bucket.value], + ...part.parts, + ...(multiframe(group[0]) + ? [['instance', instanceKey(group[0])] as [string, string]] + : []), + ], + }; + return { + key, + members, + orientation: bucket.orientation, + reconstruction, + label: + [ + labelHardFacts(group[0]), + part.label, + unreadableLabel(part.unreadablePositions), + ] + .filter(Boolean) + .join(', ') || null, + warnings: [ + ...(part.repeatedPositions ? [REPEATED_POSITIONS_WARNING] : []), + ...reconstructionWarnings( + reconstruction, + members.length === 1 && !!members[0].frameReconstruction + ), + ...(nonparallel(bucket.orientation, members) + ? [NONPARALLEL_SLICES_WARNING] + : []), + ], + }; + }) + .sort((left, right) => + canonicalKey(left.key) < canonicalKey(right.key) ? -1 : 1 + ); +} diff --git a/src/dicom/core/collections/reconstructVolume.ts b/src/dicom/core/collections/reconstructVolume.ts new file mode 100644 index 000000000..a619843f3 --- /dev/null +++ b/src/dicom/core/collections/reconstructVolume.ts @@ -0,0 +1,213 @@ +import type { InstanceFacts } from './planDicomCollections'; +import { projectOnNormal, sliceNormalOf } from './instanceFacts'; + +/** The geometry a reconstruction judges. Nothing else about an instance. */ +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 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 } + | { + kind: 'irregular'; + reason: IrregularReason; + sliceSpacing: number | null; + }; + +/** + * 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. + */ +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. */ +export const IN_PLANE_TOLERANCE_MM = 0.1; + +/** How far two in-plane sample spacings may differ and still be one grid. */ +const PIXEL_SPACING_TOLERANCE_MM = 1e-4; + +const spacingTolerance = (gap: number) => + Math.max( + Math.min( + SLICE_SPACING_TOLERANCE_MM, + Math.abs(gap) * SLICE_SPACING_TOLERANCE_CAP + ), + Math.abs(gap) * SLICE_SPACING_RELATIVE_TOLERANCE + ); + +// 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) + ]; + +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. + * 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); + 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 +): Reconstruction => ({ kind: 'irregular', reason, sliceSpacing }); + +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 }; + + const gaps = along.slice(1).map((position, index) => position - along[index]); + const step = median(gaps); + const count = along.length; + // 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) + return irregular('repeated-position', fallback); + if (gaps.some((gap) => Math.abs(gap - step) > spacingTolerance(step))) + return irregular('uneven-slice-spacing', fallback); + + // Every gap matches, so the endpoints fit the members better than any single + // printed gap does. + const drifts = along.some( + (position, index) => Math.round((position - along[0]) / mean) !== index + ); + return drifts + ? irregular('uneven-slice-spacing', fallback) + : { kind: 'regular', sliceSpacing: mean }; +}; + +/** + * 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 }; + + 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)); +} + +/** One instance holding many frames is judged by its own frame geometry. */ +export function reconstructInstances( + members: ReconstructionMember[], + normal?: number[] | null +) { + const framePlan = + members.length === 1 ? members[0].frameReconstruction : undefined; + return framePlan ?? reconstructVolume(members, normal); +} diff --git a/src/dicom/core/collections/splitOverlappingAcquisitions.ts b/src/dicom/core/collections/splitOverlappingAcquisitions.ts new file mode 100644 index 000000000..32453a7ae --- /dev/null +++ b/src/dicom/core/collections/splitOverlappingAcquisitions.ts @@ -0,0 +1,250 @@ +import type { InstanceFacts } from './planDicomCollections'; +import { groupBy } from './groupBy'; + +/** + * 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. + */ +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]; + +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 nothing 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. +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. + */ +export type PositionOf = (member: InstanceFacts) => number | null; + +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 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 && axis.kind === 'descriptor'; + 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. + const eligible = new Map( + [...tagged].filter( + ([, group]) => + axis.kind === 'contrast' || independentImages || group.length > 1 + ) + ); + const remainder = members.filter( + (member) => !eligible.has(member[axis.fact]) + ); + return { tagged: eligible, remainder }; +}; + +/** + * 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, + }, +]; + +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'}`; +}; + +// 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])) + ).values(), + ]; + const differing = descriptors.filter( + (axis) => new Set(members.map((member) => member[axis.fact])).size > 1 + ); + 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( + 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 distinctPositions = new Set(members.map(positionOf)).size; + const singlePlane = distinctPositions === 1; + const found = firstSplittingAxis( + members, + singlePlane ? axes.filter((axis) => axis.kind !== 'counter') : axes, + positionOf, + singlePlane + ); + if (!found) + 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 = [ + ...[...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 +): 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/src/core/streaming/__tests__/byteDeque.spec.ts b/src/dicom/core/header/__tests__/byteDeque.spec.ts similarity index 51% rename from src/core/streaming/__tests__/byteDeque.spec.ts rename to src/dicom/core/header/__tests__/byteDeque.spec.ts index 70d8777a1..fda59164d 100644 --- a/src/core/streaming/__tests__/byteDeque.spec.ts +++ b/src/dicom/core/header/__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', () => { @@ -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/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts b/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts new file mode 100644 index 000000000..fc68e31c5 --- /dev/null +++ b/src/dicom/core/header/__tests__/dicomHeaderEncodings.spec.ts @@ -0,0 +1,198 @@ +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 { + pixelDataStart, + readHeader, + syntheticSlice, +} from '@/tests/dicomSourceFixtures'; +import { + rawElement, + sequenceItem, + toImplicitVr, + 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('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) => { + 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.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 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([ + 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()), + 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/src/core/streaming/__tests__/streamingByteReader.spec.ts b/src/dicom/core/header/__tests__/streamingByteReader.spec.ts similarity index 93% rename from src/core/streaming/__tests__/streamingByteReader.spec.ts rename to src/dicom/core/header/__tests__/streamingByteReader.spec.ts index cbd4e5dd5..6133c5421 100644 --- a/src/core/streaming/__tests__/streamingByteReader.spec.ts +++ b/src/dicom/core/header/__tests__/streamingByteReader.spec.ts @@ -1,5 +1,5 @@ -import StreamingByteReader from '@/src/core/streaming/streamingByteReader'; -import { asCoroutine } from '@/src/utils'; +import StreamingByteReader from '../streamingByteReader'; +import { asCoroutine } from '../../utils'; import { describe, it, expect } from 'vitest'; describe('StreamingByteReader', () => { diff --git a/src/dicom/core/header/byteDeque.ts b/src/dicom/core/header/byteDeque.ts new file mode 100644 index 000000000..0b7811130 --- /dev/null +++ b/src/dicom/core/header/byteDeque.ts @@ -0,0 +1,46 @@ +/** A queue of byte chunks, consumed from the start. */ +export default class ByteDeque { + private arrays: Uint8Array[] = []; + private _size = 0; + + get size() { + return this._size; + } + + pushEnd(bytes: Uint8Array) { + this.arrays.push(bytes); + this._size += bytes.length; + } + + pushStart(bytes: Uint8Array) { + this.arrays.unshift(bytes); + this._size += bytes.length; + } + + /** 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; + } + + /** Removes up to `count` bytes off the start without copying them. */ + eraseStart(count: number) { + this.consumeStart(count); + } + + private consumeStart( + count: number, + copy?: (bytes: Uint8Array, offset: number) => void + ) { + let processed = 0; + while (processed < count && this.arrays.length) { + const bytes = this.arrays.shift()!; + 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); + } +} diff --git a/src/dicom/core/header/dicomParser.ts b/src/dicom/core/header/dicomParser.ts new file mode 100644 index 000000000..26c8f4b25 --- /dev/null +++ b/src/dicom/core/header/dicomParser.ts @@ -0,0 +1,337 @@ +import StreamingByteReader from './streamingByteReader'; +import { toAscii, asCoroutine, trimDicomPadding } 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'; + +// [Group, Element] +type Tag = [number, number]; + +export type DataElement = { + group: number; + element: number; + vr: string; + length: number; + /** Absent for sequences and encapsulated values, which are only stepped over. */ + data: Uint8Array | undefined; +}; + +type DataElementCallback = (el: DataElement) => void; + +type ParseOptions = { + littleEndian?: boolean; + explicitVr?: boolean; + onDataElement?: DataElementCallback; +}; + +// 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 isEncapsulatedValue = (vr: string, length: number) => + length === UNDEFINED_LENGTH && (vr === 'OB' || vr === 'OW'); + +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 +// See: https://dicom.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.2 +// prettier-ignore +const ExplicitVrLegacyDataElementFormat = new Set(["AE", "AS", "AT", "CS", "DA", "DS", "DT", "FL", "FD", "IS", "LO", "LT", "PN", "SH", "SL", "SS", "ST", "TM", "UI", "UL", "US"]); +// prettier-ignore +const ExplicitVrCannotHaveUndefinedLength = new Set(["SV", "UC", "UR", "UV", "UT"]); + +function equalsToTag(tag: Tag) { + return (group: number, element: number) => + group === tag[0] && element === tag[1]; +} + +function* readElementTag( + reader: StreamingByteReader, + { littleEndian = false } = {} +) { + const group = yield* reader.readUint16({ littleEndian }); + const element = yield* reader.readUint16({ littleEndian }); + return [group, element] as Tag; +} + +/** + * Peeks the data element group num and element num + * + * Assumes the reader is pointing to the start of a Data Element. + */ +function* peekElementTag( + reader: StreamingByteReader, + { littleEndian = false } = {} +) { + const bytes = yield* reader.read(4, { peek: true }); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return [ + view.getUint16(0, littleEndian), + view.getUint16(2, littleEndian), + ] as Tag; +} + +/** + * Reads an element value. + * + * Assumes the reader is pointing to the first byte of an element's value. + * + * 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 }: ParseOptions = {} +): Generator { + // 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 === UNDEFINED_LENGTH) { + yield* skipSequenceValue(reader, length, { + explicitVr: false, + littleEndian: true, + }); + return undefined; + } + + if (vr === 'SQ') { + yield* skipSequenceValue(reader, length, { explicitVr, littleEndian }); + return undefined; + } + + if (isEncapsulatedValue(vr, length)) { + yield* readFragments(reader, { littleEndian }); + return undefined; + } + + if (length === UNDEFINED_LENGTH) + 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 (;;) { + const [group, element] = yield* readElementTag(reader, opts); + const length = yield* reader.readUint32(opts); + 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); + } +} + +/** + * Reads the data element at point. + * + * Does not parse the value according to VR or transfer syntax. + * + * 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) { + const { littleEndian = false, explicitVr = false } = opts; + const [group, element] = yield* readElementTag(reader, { littleEndian }); + let vr = ''; + let length: number; + + if (explicitVr) { + vr = yield* reader.readAscii(2); + if (ExplicitVrLegacyDataElementFormat.has(vr)) { + length = yield* reader.readUint16({ littleEndian }); + } else { + // 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`); + } else { + length = yield* reader.readUint32({ littleEndian }); + // 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 }; +} + +/** + * Stops the reader at the beginning of the data element that satisfies untilFn. + * + * Assumes the reader is pointing to the start of a Data Element. + * + * untilFn is passed (group, element) + */ +function* readDataElementsUntil( + reader: StreamingByteReader, + untilFn: (group: number, element: number) => boolean, + opts: ParseOptions +) { + while (true) { + const [group, element] = yield* peekElementTag(reader, opts); + if (untilFn(group, element)) { + return; + } + const el = yield* readDataElement(reader, opts); + opts.onDataElement?.(el); + } +} + +function* skipSequenceItem(reader: StreamingByteReader, opts: ParseOptions) { + const itemByteLength = yield* reader.readUint32(opts); + if (itemByteLength !== UNDEFINED_LENGTH) { + yield* reader.seek(itemByteLength); + return; + } + 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* skipSequenceValue( + reader: StreamingByteReader, + byteLength: number, + opts: ParseOptions +) { + if (byteLength !== UNDEFINED_LENGTH) { + yield* reader.seek(byteLength); + return; + } + for (;;) { + const [group, element] = yield* readElementTag(reader, opts); + if (equalsToTag(Tags.Item)(group, element)) { + yield* skipSequenceItem(reader, opts); + } else if (equalsToTag(Tags.SequenceDelimiter)(group, element)) { + yield* reader.seek(4); + return; + } else { + throw new Error( + `Expected a sequence item, found (${group.toString( + 16 + )},${element.toString(16)})` + ); + } + } +} + +// 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, + onDataElement: DataElementCallback | undefined +) { + 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, + 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'); + + // 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. + if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) + return transferSyntaxUid; + + // 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, { + ...FILE_META_ENCODING, + onDataElement, + }); + + return transferSyntaxUid; +} + +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; + /** Called once the file meta information or the layout names the syntax. */ + onTransferSyntax?(transferSyntaxUid: string): void; +}; + +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); + if (layout.preamble) yield* reader.seek(PART_10_HEADER_LENGTH); + + const transferSyntaxUid = layout.fileMeta + ? yield* readFileMetaInfo(reader, opts.onDataElement) + : layout.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, opts.stopAtElement, { + explicitVr, + littleEndian, + onDataElement: opts.onDataElement, + }); + + return { position: reader.position }; +} + +export const createDicomParser = (callbacks: ReadDicomOptions) => + asCoroutine(readDicomUntilPixelData(callbacks)); diff --git a/src/dicom/core/header/readDicomHeader.ts b/src/dicom/core/header/readDicomHeader.ts new file mode 100644 index 000000000..198935a8d --- /dev/null +++ b/src/dicom/core/header/readDicomHeader.ts @@ -0,0 +1,153 @@ +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'; + +/** 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 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() { + const found = { + modality: undefined as string | undefined, + layout: null as DicomLayout | null, + transferSyntaxUid: null as string | null, + atPixelData: false, + }; + const parse = createDicomParser({ + stopAtElement: (group, element) => { + found.atPixelData = isTag(PIXEL_DATA, group, element); + return found.atPixelData || isRadiotherapy(found.modality); + }, + onLayout: (layout) => { + found.layout = layout; + }, + onTransferSyntax: (transferSyntaxUid) => { + found.transferSyntaxUid = transferSyntaxUid; + }, + 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 } | null = null; + const result = () => ({ + received, + total, + end: stop && stop.position >= 0 ? stop.position : undefined, + }); + 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 !== EXPLICIT_VR_BIG_ENDIAN; + 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) { + const { parse, found } = headerParser(); + 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) + ); + return { + header: bytes.subarray(0, end), + layout: found.layout, + transferSyntaxUid, + pixelData: + found.atPixelData && end !== undefined && transferSyntaxUid + ? pixelDataElement(bytes.subarray(end), end, transferSyntaxUid) + : null, + }; +} diff --git a/src/dicom/core/header/streamingByteReader.ts b/src/dicom/core/header/streamingByteReader.ts new file mode 100644 index 000000000..8a32712cb --- /dev/null +++ b/src/dicom/core/header/streamingByteReader.ts @@ -0,0 +1,74 @@ +import ByteDeque from './byteDeque'; +import { toAscii } from '../utils'; + +/** Reads values off a byte stream that a generator's caller feeds chunk by chunk. */ +export default class StreamingByteReader { + private leftover = new ByteDeque(); + private pos = 0; + + get position() { + return this.pos; + } + + /** Seeks along the byte stream. No negative values. */ + *seek(offset: number) { + if (offset < 0) { + throw new Error('Offset must not be negative'); + } + + while (this.leftover.size < offset) { + this.leftover.pushEnd(yield); + } + + this.leftover.eraseStart(offset); + this.pos += offset; + } + + /** Reads a number of bytes. */ + *read( + length: number, + { peek = false } = {} + ): Generator { + if (length < 0) { + throw new Error('Length must be a positive number'); + } + if (length === 0) return new Uint8Array(); + + while (this.leftover.size < length) { + this.leftover.pushEnd(yield); + } + + const data = this.leftover.popStart(length); + + if (peek) { + this.leftover.pushStart(data); + } else { + this.pos += length; + } + + return data; + } + + *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: boolean + ) { + const bytes = yield* this.read(length); + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return dv[method](0, littleEndian); + } + + *readUint16({ littleEndian = false } = {}) { + return yield* this.readDataView('getUint16', 2, littleEndian); + } + + *readUint32({ littleEndian = false } = {}) { + return yield* this.readDataView('getUint32', 4, littleEndian); + } +} diff --git a/src/dicom/core/instance/__tests__/readInstanceSources.spec.ts b/src/dicom/core/instance/__tests__/readInstanceSources.spec.ts new file mode 100644 index 000000000..b24704394 --- /dev/null +++ b/src/dicom/core/instance/__tests__/readInstanceSources.spec.ts @@ -0,0 +1,296 @@ +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 { readUltrasoundRegions } from '../../metadata/ultrasoundRegion'; +import { + EXPLICIT_VR_LITTLE_ENDIAN, + IMPLICIT_VR_LITTLE_ENDIAN, +} from '../../metadata/dicomLayout'; +import { fromBlob, fromUrl, readBytes } from '../../source/byteSource'; +import { trackedSource } from '@/tests/byteSourceFixtures'; +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; +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, + cols: 64, + modality: 'MR', + patientName: 'DOE^JANE', + extraElements: [ + rawElement(0x0029, 0x0010, 'LO', new TextEncoder().encode('VENDOR')), + ], + }); + +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 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' }); + + 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, readDataset } = recordingReader(); + 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 }) + ).rejects.toThrow('connection reset'); + expect(seen).toEqual([]); + }); + + it('hands the dataset reader the header bytes, once', async () => { + const bytes = syntheticSlice(); + const { seen, readDataset } = recordingReader(); + + await readInstance(trackedSource(bytes).source, never(), { readDataset }); + + 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)); + 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('reads every tag of an object that has no Pixel Data', async () => { + const bytes = withoutPixelData(syntheticSlice({ modality: 'SR' })); + + 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 no further than its modality', async () => { + const bytes = syntheticSlice({ modality: 'RTDOSE', patientName: 'DOE' }); + const skipped = trackedSource(bytes, 32); + + const shortcut = await readInstance(skipped.source, never()); + + 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)); + }); + + 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/src/dicom/core/instance/readInstance.ts b/src/dicom/core/instance/readInstance.ts new file mode 100644 index 000000000..cedb2dcdf --- /dev/null +++ b/src/dicom/core/instance/readInstance.ts @@ -0,0 +1,50 @@ +import type { ByteSource } from '../source/byteSource'; +import { readPublicDataset, type DicomDataset } from '../metadata/dicomDataset'; +import type { DicomLayout } from '../metadata/dicomLayout'; +import { + readDicomHeader, + type PixelDataElement, +} from '../header/readDicomHeader'; +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; + /** 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; +}; + +/** 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)); + signal.throwIfAborted(); + const dataset = await (options.readDataset ?? readPublicDataset)(header); + signal.throwIfAborted(); + return Object.freeze({ + source, + dataset, + layout, + transferSyntaxUid, + pixelData, + }); +} diff --git a/src/dicom/core/metadata/__tests__/dcmjsParser.spec.ts b/src/dicom/core/metadata/__tests__/dcmjsParser.spec.ts new file mode 100644 index 000000000..8b27dffbd --- /dev/null +++ b/src/dicom/core/metadata/__tests__/dcmjsParser.spec.ts @@ -0,0 +1,339 @@ +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'; +import { parseDicomElements } from '../dcmjsParser'; +import { PART_10_HEADER_LENGTH } from '../dicomLayout'; +import { concatBytes } from '../../utils'; +import { buildSlice } from '@/tests/specs/dicomElementFixtures'; +import { + pixelDataStart, + readHeader, + syntheticSlice, +} from '@/tests/dicomSourceFixtures'; +import { + rawElement, + sequenceItem, + toImplicitVr, + stripFileMeta, + stripPreamble, + undefinedLengthItem, + undefinedLengthSequence, +} 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) => + 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 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', () => { + 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('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, + 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 '); + 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', () => { + 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 [reference] = sequenceItems(dataset, '00081140'); + expect(findElement(reference, '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(readUltrasoundRegions(instance.dataset)).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 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 [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 dataset = readDicomDataset( + concatBytes([ + rawElement(0x0008, 0x0005, 'CS', encode('ISO_IR 192')), + rawElement( + 0x0008, + 0x1140, + 'SQ', + sequenceItem(rawElement(0x0010, 0x0010, 'UN', encode('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', encode('CT')), + rawElement(0x7fe0, 0x0010, 'UN', new Uint8Array(16)).subarray(0, 12), + ]); + expect(parseDicomElements(input)).toHaveLength(1); +}); diff --git a/src/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts b/src/dicom/core/metadata/__tests__/dicomCharacterSets.spec.ts new file mode 100644 index 000000000..25476b276 --- /dev/null +++ b/src/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 = '00380300'; +const STUDY_COMMENTS = '00324000'; +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/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts b/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts new file mode 100644 index 000000000..db716191b --- /dev/null +++ b/src/dicom/core/metadata/__tests__/dicomDataset.spec.ts @@ -0,0 +1,332 @@ +import { describe, expect, it } from 'vitest'; +import { DicomDataset, findElement, readDicomDataset } from '../dicomDataset'; +import { sequenceItems } from '../functionalGroups'; +import { concatBytes } from '../../utils'; +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 '@/tests/specs/dicomElementFixtures'; + +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 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 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( + concatBytes([ + 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('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] }) + ); + const outer = sequenceItems(dataset, REQUEST_ATTRIBUTES); + const inner = sequenceItems(outer[0], REFERENCED_STUDY); + + expect(outer).toHaveLength(1); + expect(valuesOf(outer[0], SCHEDULED_PROCEDURE_STEP_ID)).toEqual({ + kind: 'text', + values: ['SPS1 '], + }); + expect(inner).toHaveLength(1); + expect(valuesOf(inner[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( + concatBytes([ + ...localCharacterSet, + rawElement(0x0008, 0x0104, 'LO', ascii(UTF8_ITEM_TEXT)), + ]) + ) + ), + ], + }) + ); + const [requested] = sequenceItems(dataset, REQUEST_ATTRIBUTES); + + expect(valuesOf(requested, 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( + concatBytes([ + rawElement(0x0008, 0x0005, 'CS', ascii(JAPANESE_CHARACTER_SET)), + rawElement(0x0010, 0x0010, 'PN', JAPANESE_NAME_BYTES), + ]) + ), + ], + }) + ); + const [requested] = sequenceItems(dataset, REQUEST_ATTRIBUTES); + + expect(requested.specificCharacterSet).toEqual([ + 'ISO 2022 IR 6', + 'ISO 2022 IR 87', + ]); + expect(valuesOf(requested, 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 [region] = sequenceItems(dataset, ULTRASOUND_REGIONS); + + expect(region.elements.map(({ tag }) => tag)).toEqual([ + '00186024', + '00186026', + '0018602C', + '0018602E', + ]); + expect(valuesOf(region, 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('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/src/dicom/core/metadata/__tests__/dicomLayout.spec.ts b/src/dicom/core/metadata/__tests__/dicomLayout.spec.ts new file mode 100644 index 000000000..d4951f9ef --- /dev/null +++ b/src/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 '@/tests/specs/dicomElementFixtures'; + +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/src/dicom/core/metadata/__tests__/modalityRescale.spec.ts b/src/dicom/core/metadata/__tests__/modalityRescale.spec.ts new file mode 100644 index 000000000..618b7b596 --- /dev/null +++ b/src/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/src/dicom/core/metadata/__tests__/spatialMetadata.spec.ts b/src/dicom/core/metadata/__tests__/spatialMetadata.spec.ts new file mode 100644 index 000000000..f6cebffd3 --- /dev/null +++ b/src/dicom/core/metadata/__tests__/spatialMetadata.spec.ts @@ -0,0 +1,29 @@ +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', (raw, value) => { + const dataset = spacingDataset(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([1, 1]); + } + ); +}); diff --git a/src/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts b/src/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts new file mode 100644 index 000000000..de9043128 --- /dev/null +++ b/src/dicom/core/metadata/__tests__/ultrasoundRegion.spec.ts @@ -0,0 +1,87 @@ +import { describe, it, expect } from 'vitest'; +import { readDicomDataset } from '../dicomDataset'; +import { concatBytes } from '../../utils'; +import { syntheticSlice } from '@/tests/dicomSourceFixtures'; +import { rawElement, sequenceItem } from '@/tests/specs/syntheticDicom'; +import { readUltrasoundRegions, unitToMm } from '../ultrasoundRegion'; + +const US_UNIT_CENTIMETERS = 3; + +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/dicom/core/metadata/datasetAccess.ts b/src/dicom/core/metadata/datasetAccess.ts new file mode 100644 index 000000000..1dc97d227 --- /dev/null +++ b/src/dicom/core/metadata/datasetAccess.ts @@ -0,0 +1,26 @@ +import type { DicomDataset, DicomElement } from './dicomDataset'; +import { trimDicomPadding } from '../utils'; + +/** Text and numeric values retain multiplicity; sequences and opaque bytes do not become text. */ +function getElementText({ values }: DicomElement) { + 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 element = dataset?.elements.find((entry) => entry.tag === tag); + return element ? getElementText(element) : undefined; +} + +export const getDatasetModality = (dataset: DicomDataset | null | undefined) => + trimDicomPadding(getDatasetTag(dataset, '00080060') ?? '') || null; diff --git a/src/dicom/core/metadata/dcmjs.d.ts b/src/dicom/core/metadata/dcmjs.d.ts new file mode 100644 index 000000000..1e4cc1e35 --- /dev/null +++ b/src/dicom/core/metadata/dcmjs.d.ts @@ -0,0 +1,71 @@ +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; + }; + + 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; + readVR(): string; + readUint16(): number; + readUint32(): number; + setDecoder(decoder: DicomStringDecoder): void; + more(length: number): DicomReadStream; + slice(start: number, end: number): ArrayBuffer; + }; + + export type DicomDataElement = { + Value: unknown[]; + }; + + const dcmjs: { + constants: { + encodingMapping: Record; + }; + data: { + DicomMetaDictionary: { + dictionary: Record; + }; + ReadBufferStream: new (buffer: ArrayBuffer) => DicomReadStream; + DeflatedReadBufferStream: new ( + stream: DicomReadStream + ) => DicomReadStream; + DicomMessage: { + readFile(buffer: ArrayBuffer): { + dict: Record; + write(): ArrayBuffer; + }; + _readTag( + stream: DicomReadStream, + syntax: string, + options?: DicomReadOptions + ): DicomElement; + _normalizeSyntax(syntax: string): string; + }; + }; + }; + + export default dcmjs; +} diff --git a/src/dicom/core/metadata/dcmjsParser.ts b/src/dicom/core/metadata/dcmjsParser.ts new file mode 100644 index 000000000..d694ba0a0 --- /dev/null +++ b/src/dicom/core/metadata/dcmjsParser.ts @@ -0,0 +1,468 @@ +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'; + +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 RESERVED_LENGTH = 2; + +/** 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', + 'UV', +]); + +/** 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); + +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 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 peekElementHead = (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; + 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 + ? { + 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, +}; + +/** 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: NonNullable> +): ParsedElement => { + const { group, element, valueStart, end } = sequence; + if (end !== null && end > dataSet.endOffset) + throw new Error('Sequence exceeds the available dataset bytes'); + 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 bytes = implicitElement(group, element, takeValue(end)); + return readElements( + readsBytes(new ReadBufferStream(bytes.buffer)), + IMPLICIT_VR_LITTLE_ENDIAN, + { stopAtPixelData: false } + )[0]; + } + + const head = { + group, + element, + vr: sequence.unknown ? 'UN' : 'SQ', + values: [], + }; + dataSet.offset = valueStart; + try { + const itemSyntax = sequence.unknown ? IMPLICIT_VR_LITTLE_ENDIAN : syntax; + return { ...head, items: readSequenceItems(dataSet, itemSyntax, end) }; + } catch (error) { + if (end === null) throw error; + return { + ...head, + unread: { bytes: takeValue(end), 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 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 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, + syntax, + stopAtPixelData ? READ_OPTIONS : { forceStoreRaw: true } + ); + const done = stopAtPixelData && element.tag.toCleanString() === PIXEL_DATA; + 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 = ( + 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/src/dicom/core/metadata/dicomCharacterSet.ts b/src/dicom/core/metadata/dicomCharacterSet.ts new file mode 100644 index 000000000..e4ecf5375 --- /dev/null +++ b/src/dicom/core/metadata/dicomCharacterSet.ts @@ -0,0 +1,203 @@ +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']); + +/** 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/src/dicom/core/metadata/dicomDataset.ts b/src/dicom/core/metadata/dicomDataset.ts new file mode 100644 index 000000000..47b7deb5c --- /dev/null +++ b/src/dicom/core/metadata/dicomDataset.ts @@ -0,0 +1,212 @@ +import { + hex4, + ParsedElement, + ParsedValue, + parseDicomElements, +} from './dcmjsParser'; +import { trimDicomPadding } from '../utils'; +import { + CHARSET_VRS, + characterSetDecoder, + VALUE_DELIMITER, +} from './dicomCharacterSet'; + +const SPECIFIC_CHARACTER_SET = '00080005'; + +/** A tag as `ggggeeee` in upper case hexadecimal. */ +type DicomTagKey = string; + +type AttributeTag = { group: number; element: number }; + +/** 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']); + +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; +}; + +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; +}; + +const tagKey = (group: number, element: number) => + `${hex4(group)}${hex4(element)}`; + +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, +}); + +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; + 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 => ({ + 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. +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 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); + +/** Image loading uses public attributes; private payloads stay in the source. */ +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 + ), +}); + +/** The data set an instance carries, filtered where it is parsed. */ +export const readPublicDataset = (bytes: Uint8Array) => + withoutPrivateElements(readDicomDataset(bytes)); diff --git a/src/dicom/core/metadata/dicomLayout.ts b/src/dicom/core/metadata/dicomLayout.ts new file mode 100644 index 000000000..621e98830 --- /dev/null +++ b/src/dicom/core/metadata/dicomLayout.ts @@ -0,0 +1,95 @@ +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. + */ +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. */ + | { 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/dicom/core/metadata/dicomTags.ts b/src/dicom/core/metadata/dicomTags.ts new file mode 100644 index 000000000..bac8c166b --- /dev/null +++ b/src/dicom/core/metadata/dicomTags.ts @@ -0,0 +1,67 @@ +export const Tags = { + 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 +// 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 +// US-MONO2-8-8x-execho) still emit the retired UID. +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) { + const trimmed = uid.trim(); + return ( + trimmed === SOP_CLASS_ULTRASOUND_MULTIFRAME || + trimmed === SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED + ); +} diff --git a/src/dicom/core/metadata/functionalGroups.ts b/src/dicom/core/metadata/functionalGroups.ts new file mode 100644 index 000000000..3920515f9 --- /dev/null +++ b/src/dicom/core/metadata/functionalGroups.ts @@ -0,0 +1,52 @@ +import { findElement, type DicomDataset } from './dicomDataset'; +import { getDatasetTag } from './datasetAccess'; +import { getNmDetectorTag } from './nmReconstruction'; + +export 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 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, tag) ?? + macroValue(shared, macro, tag) ?? + getNmDetectorTag(dataset, tag) ?? + getDatasetTag(dataset, tag) + ); +} + +export const perFrameGroups = (dataset: DicomDataset) => + sequenceItems(dataset, PER_FRAME_GROUPS); diff --git a/src/dicom/core/metadata/modalityRescale.ts b/src/dicom/core/metadata/modalityRescale.ts new file mode 100644 index 000000000..4d503e118 --- /dev/null +++ b/src/dicom/core/metadata/modalityRescale.ts @@ -0,0 +1,53 @@ +import type { DicomDataset } from './dicomDataset'; +import { getDatasetTag } from './datasetAccess'; +import { getFrameTag, perFrameGroups } from './functionalGroups'; +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(rescaleTag(metadata, '00281053', frameIndex), 1) || 1, + rescaleIntercept: numberOr(rescaleTag(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 + ); + }); +} diff --git a/src/dicom/core/metadata/nmReconstruction.ts b/src/dicom/core/metadata/nmReconstruction.ts new file mode 100644 index 000000000..52723d68d --- /dev/null +++ b/src/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/src/dicom/core/metadata/readDicomDataset.worker.ts b/src/dicom/core/metadata/readDicomDataset.worker.ts new file mode 100644 index 000000000..0fcd78a32 --- /dev/null +++ b/src/dicom/core/metadata/readDicomDataset.worker.ts @@ -0,0 +1,7 @@ +import * as Comlink from 'comlink'; +import { readPublicDataset } from './dicomDataset'; + +export type DicomDatasetWorker = { + readPublicDataset: typeof readPublicDataset; +}; +Comlink.expose({ readPublicDataset }); diff --git a/src/dicom/core/metadata/spatialMetadata.ts b/src/dicom/core/metadata/spatialMetadata.ts new file mode 100644 index 000000000..0922743c6 --- /dev/null +++ b/src/dicom/core/metadata/spatialMetadata.ts @@ -0,0 +1,17 @@ +import type { DicomDataset } from './dicomDataset'; +import { getFrameTag } from './functionalGroups'; +import { trimDicomPadding } from '../utils'; + +/** 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; +} + +/** 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.split('\\'); + if (parts.length < 2) return [spacingOr1(parts[0]), spacingOr1(parts[0])]; + return [spacingOr1(parts[1]), spacingOr1(parts[0])]; +} diff --git a/src/dicom/core/metadata/ultrasoundRegion.ts b/src/dicom/core/metadata/ultrasoundRegion.ts new file mode 100644 index 000000000..284050488 --- /dev/null +++ b/src/dicom/core/metadata/ultrasoundRegion.ts @@ -0,0 +1,65 @@ +import { getDatasetTag } from './datasetAccess'; +import { sequenceItems } from './functionalGroups'; +import type { DicomDataset } from './dicomDataset'; +import { numberOr } 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 +// 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. +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; +}; + +/** 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) => numberOr(getDatasetTag(item, tag), 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 +// 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 regions = ultrasoundRegionsOf(metadata); + const [region] = regions; + return { + regionCount: regions.length, + ...(region && Object.values(region).every(Number.isFinite) + ? { region } + : {}), + }; +} diff --git a/src/dicom/core/pixels/__tests__/decoderTable.spec.ts b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts new file mode 100644 index 000000000..f108441d9 --- /dev/null +++ b/src/dicom/core/pixels/__tests__/decoderTable.spec.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest'; +import { + defaultDecoderTable, + planDecode, + 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 a native unit per frame for an uncompressed instance it reproduces', async () => { + const { instance } = await pixelInstance({ frames: 3 }); + + const plan = planDecode(table, instance, Uint16Array); + + 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('falls through to GDCM, whole, when native decoding declines', async () => { + const { instance } = await pixelInstance({ photometric: '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 GDCM', async (_name, syntax) => { + const { instance } = await pixelInstance({ transferSyntaxUid: syntax }); + + expect(planDecode(table, instance, Uint16Array)).toMatchObject({ + decoder: gdcm, + }); + }); + + 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(); + 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(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/src/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts b/src/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts new file mode 100644 index 000000000..bc1a7d2f8 --- /dev/null +++ b/src/dicom/core/pixels/__tests__/encapsulatedFrames.spec.ts @@ -0,0 +1,194 @@ +import { describe, expect, it } from 'vitest'; +import { + encapsulatedPixelData, + sequenceItem, +} 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( + sequenceItem(new Uint8Array()), + sequenceItem(jpeg(1)), + sequenceItem(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( + sequenceItem(new Uint8Array()), + sequenceItem(odd), + sequenceItem(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( + sequenceItem(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( + 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( + sequenceItem(Uint8Array.from([0, 0])), + sequenceItem(jpeg(1)), + DELIMITER + ), + /Basic Offset Table holds 2 bytes/, + ], + [ + 'an offset that starts no fragment', + concat( + sequenceItem(Uint8Array.from([0, 0, 0, 0, 3, 0, 0, 0])), + sequenceItem(jpeg(1)), + sequenceItem(jpeg(2)), + DELIMITER + ), + /entry 1 \(3\) starts no fragment/, + ], + [ + 'an offset table that skips the first fragment', + concat( + 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$/, + ], + ['no offset table item', DELIMITER, /no Basic Offset Table/], + [ + 'no fragments', + concat(sequenceItem(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/src/dicom/core/pixels/__tests__/frameIndex.spec.ts b/src/dicom/core/pixels/__tests__/frameIndex.spec.ts new file mode 100644 index 000000000..e9ca5c31f --- /dev/null +++ b/src/dicom/core/pixels/__tests__/frameIndex.spec.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest'; +import { indexFrames } from '../frameIndex'; +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' }, + /not indexable without a codec/, + ], + [ + 'truncated', + { extra: [{ tag: 0x00280008, vr: 'IS', value: '9' }] }, + /Pixel Data holds 30 bytes; its frames need 270/, + ], + [ + 'misshapen', + { rows: 0 }, + /Rows, Columns or Samples per Pixel 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))).toEqual({ + kind: 'unindexed', + detail: 'Bits Allocated 1 packs samples across bytes', + }); + }); + + it('reports an instance without Pixel Data as unindexed', () => { + expect( + indexFrames({ + source: { read: () => new ReadableStream() }, + dataset: { elements: [], specificCharacterSet: null }, + layout: null, + transferSyntaxUid: EXPLICIT_LE, + pixelData: null, + }) + ).toEqual({ + kind: 'unindexed', + detail: 'The header locates no Pixel Data', + }); + }); +}); diff --git a/src/dicom/core/pixels/__tests__/nativeFrame.spec.ts b/src/dicom/core/pixels/__tests__/nativeFrame.spec.ts new file mode 100644 index 000000000..b9cccdee4 --- /dev/null +++ b/src/dicom/core/pixels/__tests__/nativeFrame.spec.ts @@ -0,0 +1,240 @@ +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', + { + sopClassUid: '1.2.840.10008.5.1.4.1.1.2.1', + 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', + { + sopClassUid: '1.2.840.10008.5.1.4.1.1.2.1', + 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/src/dicom/core/pixels/__tests__/pixelFixture.ts b/src/dicom/core/pixels/__tests__/pixelFixture.ts new file mode 100644 index 000000000..a2df5c889 --- /dev/null +++ b/src/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/src/dicom/core/pixels/decoderTable.ts b/src/dicom/core/pixels/decoderTable.ts new file mode 100644 index 000000000..ca3460249 --- /dev/null +++ b/src/dicom/core/pixels/decoderTable.ts @@ -0,0 +1,113 @@ +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'; + +/** Candidates per transfer syntax in preference order; the first that does not decline wins. */ +export type DecoderTable = Readonly<{ + byTransferSyntax: ReadonlyMap; + /** For transfer syntaxes the table does not list. */ + fallback: readonly PixelDecoder[]; + /** Names of known transfer syntaxes, so an error can say which one has no decoder. */ + names: ReadonlyMap; +}>; + +/** 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 SYNTAXES: Array<[string, string, Codec]> = [ + [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'], + ['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.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'], +]; + +/** 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])), + }; +} + +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}`); +} + +type DecodePlan = + | Readonly<{ decoder: PixelDecoder; units: DecodeUnit[] }> + | Readonly<{ error: Error }>; + +/** The units the first willing decoder loads `instance` in. Pure: reads only the header. */ +export function planDecode( + table: DecoderTable, + instance: Instance, + target: VolumeBufferConstructor +): DecodePlan { + const syntax = instance.transferSyntaxUid; + const candidates = + (syntax && table.byTransferSyntax.get(syntax)) || table.fallback; + 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/src/dicom/core/pixels/encapsulatedFrames.ts b/src/dicom/core/pixels/encapsulatedFrames.ts new file mode 100644 index 000000000..7ece9ac87 --- /dev/null +++ b/src/dicom/core/pixels/encapsulatedFrames.ts @@ -0,0 +1,136 @@ +import { UNDEFINED_LENGTH } from '../metadata/dicomLayout'; +import { concatBytes } from '../utils'; + +const ITEM = 0xe000; +const SEQUENCE_DELIMITER = 0xe0dd; +const ITEM_GROUP = 0xfffe; +const ITEM_HEAD_LENGTH = 8; + +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[]) => + fragments.length === 1 + ? fragments[0].bytes + : 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 = indexAt.get(offset); + if (index === undefined) + 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; + if (rest.length === 0) throw malformed('no fragments'); + const fragments = rest.map(({ position, bytes }) => ({ + offset: position - rest[0].position, + bytes, + })); + 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/src/dicom/core/pixels/frameIndex.ts b/src/dicom/core/pixels/frameIndex.ts new file mode 100644 index 000000000..c8c64fe08 --- /dev/null +++ b/src/dicom/core/pixels/frameIndex.ts @@ -0,0 +1,132 @@ +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, trimDicomPadding } from '../utils'; +import { frameCount } from './pixelDecoder'; + +/** Transfer syntaxes whose Pixel Data is a plain run of fixed-size frames. */ +const NATIVE_ENCODINGS: ReadonlyMap = + new Map([ + [IMPLICIT_VR_LITTLE_ENDIAN, { littleEndian: true }], + [EXPLICIT_VR_LITTLE_ENDIAN, { littleEndian: true }], + [EXPLICIT_VR_BIG_ENDIAN, { littleEndian: false }], + ]); + +/** Where each frame's bytes live, for native encodings. */ +type FrameIndex = + | Readonly<{ + kind: 'indexed'; + littleEndian: boolean; + frameLength: number; + frames: readonly ByteRange[]; + }> + | Readonly<{ kind: 'unindexed'; detail: string }>; + +const unindexed = (detail: string): FrameIndex => ({ + kind: 'unindexed', + detail, +}); + +/** 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(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; + +// 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; + 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'); + if (transferSyntaxUid === DEFLATED_EXPLICIT_VR_LITTLE_ENDIAN) + return unindexed('The whole data set is deflated'); + const encoding = NATIVE_ENCODINGS.get(transferSyntaxUid); + if (!encoding) + return unindexed( + `Transfer syntax ${transferSyntaxUid} is not indexable without a codec` + ); + 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)) + 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` + ); + 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. + const detail = overrun(layout); + if (detail) return unindexed(detail); + const { littleEndian, frameLength, frames, valueOffset } = layout; + return { + kind: 'indexed', + littleEndian, + frameLength, + frames: Array.from({ length: frames }, (_, frame) => { + const start = valueOffset + frame * frameLength; + return { start, end: start + frameLength }; + }), + }; +} diff --git a/src/dicom/core/pixels/nativeFrame.ts b/src/dicom/core/pixels/nativeFrame.ts new file mode 100644 index 000000000..c77a46f19 --- /dev/null +++ b/src/dicom/core/pixels/nativeFrame.ts @@ -0,0 +1,251 @@ +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, shapeOf } from './frameIndex'; +import type { PixelDecoder } from './pixelDecoder'; + +/** 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; +}>; + +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. */ +function readNativePixelFormat( + instance: Instance, + littleEndian: boolean +): NativePixelFormat { + const { dataset } = instance; + const { rows, columns, samplesPerPixel, bitsAllocated } = shapeOf(instance); + return { + 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, Tags.PixelRepresentation) === 1, + littleEndian, + ...readModalityRescale(dataset), + }; +} + +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; + 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 }; +} + +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, + 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; + 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); + for (let index = 0; index < count; index += 1) + words[index] = + size === 2 + ? view.getUint16(index * 2, littleEndian) + : view.getUint32(index * 4, littleEndian); + return words; +} + +/** + * 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 { bitsStored, bitsAllocated, signed } = format; + const { rescaleSlope: slope, rescaleIntercept: intercept } = format; + const pixels = rows * columns; + const count = pixels * components; + 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 samples = new Target(count); + 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) { + // 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 < low) low = value; + if (value > high) high = value; + } + return [low, high] as [number, number]; + }); + return { samples, range }; +} + +/** 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/src/dicom/core/pixels/pixelDecoder.ts b/src/dicom/core/pixels/pixelDecoder.ts new file mode 100644 index 000000000..bef858148 --- /dev/null +++ b/src/dicom/core/pixels/pixelDecoder.ts @@ -0,0 +1,72 @@ +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'; + +/** 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 view a buffer other + * units share, so transfer it only when it spans its whole buffer. + */ + 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; + +// 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 = ( + name: string, + decode: WholeInstanceDecode +): PixelDecoder => ({ + name, + plan: (instance) => [ + { + firstFrame: 0, + frames: frameCount(instance.dataset), + range: null, + decode: (bytes, signal) => decode({ instance, bytes }, signal), + }, + ], +}); diff --git a/src/dicom/core/runtime/__tests__/dicomRuntime.spec.ts b/src/dicom/core/runtime/__tests__/dicomRuntime.spec.ts new file mode 100644 index 000000000..d2bd7ebc6 --- /dev/null +++ b/src/dicom/core/runtime/__tests__/dicomRuntime.spec.ts @@ -0,0 +1,180 @@ +import { describe, expect, it } from 'vitest'; +import { + createDicomRuntime, + defaultDecodeConcurrency, +} from '../createDicomRuntime'; +import { createGdcmDecoder, type GdcmLane } from '../gdcmDecoder'; +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'; + +const assets = { + pipelineWorkerUrl: '/unused-worker.js', + imageIOUrl: '/unused-image-io', +}; +const decodedPixels: DecodedPixels = { + size: [1, 1, 1], + data: new Uint16Array(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 = Promise.withResolvers(); + 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], + [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 its concurrency of GDCM decodes at once', async () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 2, lanes.createLane); + + const decodes = [0, 1, 2].map(() => decodeWith(gdcm)); + await lanes.started(2); + lanes.gate.resolve(); + await Promise.all(decodes); + + expect(lanes.peak()).toBe(2); + gdcm.dispose(new Error('done')); + }); + + it('settles running and queued GDCM decodes when disposed', async () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 1, lanes.createLane); + + 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 () => { + const lanes = controlledLanes(); + const gdcm = createGdcmDecoder(assets, 1, lanes.createLane); + const controller = new AbortController(); + + const decoding = decodeWith(gdcm, controller.signal); + await lanes.started(1); + const reason = new DOMException('stop', 'AbortError'); + controller.abort(reason); + + await expect(decoding).rejects.toBe(reason); + expect(lanes.resets).toEqual([reason]); + gdcm.dispose(reason); + }); + + it('reads instances with its own metadata reader, needing no decoder assets', 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'); + 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 })' + ); + }); + + 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/src/dicom/core/runtime/__tests__/metadataReader.spec.ts b/src/dicom/core/runtime/__tests__/metadataReader.spec.ts new file mode 100644 index 000000000..088e0856d --- /dev/null +++ b/src/dicom/core/runtime/__tests__/metadataReader.spec.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest'; +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'; + +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. +describe('readDicomDatasetOffThread', () => { + it('reads what the reader reads', async () => { + const bytes = buildSlice({ patientName: 'DOE^JOHN' }); + + expect(await readDicomDatasetOffThread(bytes)).toEqual( + readDicomDataset(bytes) + ); + }); + + 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); + 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(() => { + 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', + }); + }); + + it('transfers a copy, so the caller keeps its bytes', async () => { + const reader = createMetadataReader(() => { + 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/src/dicom/core/runtime/__tests__/requestPool.spec.ts b/src/dicom/core/runtime/__tests__/requestPool.spec.ts new file mode 100644 index 000000000..653db1a0c --- /dev/null +++ b/src/dicom/core/runtime/__tests__/requestPool.spec.ts @@ -0,0 +1,114 @@ +import { RequestPool } from '../requestPool'; +import { describe, it, expect } from 'vitest'; + +/** 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', () => { + const N = 4; + 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(started).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 = Promise.withResolvers(); + 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(); + } + ); +}); diff --git a/src/dicom/core/runtime/createDicomRuntime.ts b/src/dicom/core/runtime/createDicomRuntime.ts new file mode 100644 index 000000000..affc36a05 --- /dev/null +++ b/src/dicom/core/runtime/createDicomRuntime.ts @@ -0,0 +1,95 @@ +import type { ByteSource } from '../source/byteSource'; +import { readInstance } from '../instance/readInstance'; +import { RequestPool } from './requestPool'; +import { abortError, linkedController, untilAborted } from '../utils'; +import { createMetadataReader } from './metadataReader'; +import { defaultDecoderTable, type DecoderTable } from '../pixels/decoderTable'; +import type { PixelDecoder } from '../pixels/pixelDecoder'; +import { + createGdcmDecoder, + type CreateGdcmLane, + type DicomAssets, +} from './gdcmDecoder'; + +export type DicomRuntimeOptions = { + fetch?: typeof fetch; + assets?: DicomAssets; + /** Builds the decoder table around the runtime's GDCM decoder. */ + decoders?: (gdcm: PixelDecoder) => DecoderTable; + /** + * GDCM workers, and the decodes one volume runs at once. Each worker + * carries its own WASM heap. + */ + decodeConcurrency?: number; +}; + +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)) + ); + +/** + * 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 = {}, + createGdcmLane?: CreateGdcmLane +) { + 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(undefined, options.fetch); + const metadata = createMetadataReader(); + const gdcm = createGdcmDecoder( + options.assets, + decodeConcurrency, + createGdcmLane + ); + + const read = async (source: ByteSource, signal: AbortSignal) => { + const { controller, release } = linkedController(signal, lifetime.signal); + try { + return await untilAborted( + readInstance(source, controller.signal, { readDataset: metadata.read }), + controller.signal + ); + } finally { + release(); + } + }; + + const dispose = () => { + if (lifetime.signal.aborted) return; + const reason = abortError('DICOM runtime disposed'); + lifetime.abort(reason); + requests.dispose(reason); + metadata.dispose(reason); + 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 ?? defaultDecoderTable)(gdcm.decoder), + /** Requests awaiting headers at once; also how far reads run ahead of decoding. */ + readConcurrency: requests.poolSize, + readInstance: read, + dispose, + }; +} + +export type DicomRuntime = ReturnType; diff --git a/src/dicom/core/runtime/gdcmDecoder.ts b/src/dicom/core/runtime/gdcmDecoder.ts new file mode 100644 index 000000000..94f901922 --- /dev/null +++ b/src/dicom/core/runtime/gdcmDecoder.ts @@ -0,0 +1,207 @@ +import type { Image, runPipeline, TypedArray } from 'itk-wasm'; +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 }; + +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 core 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, + bytes: Uint8Array, + signal: AbortSignal + ) => { + signal.throwIfAborted(); + const lane = lanes[index]; + if (!lane) + throw new Error('GDCM decoding needs createDicomRuntime({ assets })'); + // 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 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 decodeOn(index, bytes, linked); + } finally { + 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); + lanes.forEach((lane) => lane.reset(reason)); + }; + + return { decoder, dispose }; +} diff --git a/src/dicom/core/runtime/metadataReader.ts b/src/dicom/core/runtime/metadataReader.ts new file mode 100644 index 000000000..ed2aefc63 --- /dev/null +++ b/src/dicom/core/runtime/metadataReader.ts @@ -0,0 +1,76 @@ +import * as Comlink from 'comlink'; +import { readPublicDataset, type DicomDataset } from '../metadata/dicomDataset'; +import type { DicomDatasetWorker } from '../metadata/readDicomDataset.worker'; +import { abortError } from '../utils'; + +const WORKER_COUNT = 2; + +/** Owns parser workers. Input bytes are copied before transfer; the caller keeps its buffer. */ +export function createMetadataReader(createWorker?: () => Worker) { + const workers: Array<{ + worker: Worker; + remote: Comlink.Remote; + }> = []; + const pending = new Set<(reason: unknown) => void>(); + let next = 0; + let disposal: unknown; + const spawn = + createWorker ?? + (() => + 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 (disposal) throw disposal; + if (typeof Worker === 'undefined' && !createWorker) + return readPublicDataset(bytes); + if (workers.length < WORKER_COUNT) { + const worker = spawn(); + 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 + .readPublicDataset(Comlink.transfer(owned, [owned.buffer])) + .then(resolve, reject) + .finally(() => pending.delete(reject)); + }); + }; + const dispose = ( + reason: unknown = abortError('Metadata reader disposed') + ) => { + if (disposal) return; + disposal = reason; + resetWorkers(reason); + }; + return { read, dispose }; +} diff --git a/src/dicom/core/runtime/requestPool.ts b/src/dicom/core/runtime/requestPool.ts new file mode 100644 index 000000000..d4313d830 --- /dev/null +++ b/src/dicom/core/runtime/requestPool.ts @@ -0,0 +1,108 @@ +import { abortError } from '../utils'; + +type FetchRequest = { + request: RequestInfo | URL; + init?: RequestInit; + resolve: (response: Response) => void; + reject: (reason?: unknown) => void; + 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 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'); + } + + fetch = (request: RequestInfo | URL, init?: RequestInit) => { + 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); + reject(sourceSignal?.reason); + this.queue = this.queue.filter((entry) => entry !== queued); + }; + const onDispose = () => { + controller.abort(disposal.reason); + reject(disposal.reason); + }; + const queued: FetchRequest = { + request, + init, + resolve, + reject, + controller, + cleanup: () => { + sourceSignal?.removeEventListener('abort', abort); + disposal.removeEventListener('abort', onDispose); + }, + }; + if (sourceSignal?.aborted) { + reject(sourceSignal.reason); + return response; + } + sourceSignal?.addEventListener('abort', abort, { once: true }); + disposal.addEventListener('abort', onDispose, { once: true }); + controller.signal.addEventListener('abort', queued.cleanup, { once: true }); + this.queue.push(queued); + this.processQueue(); + return response; + }; + + dispose(reason: unknown = abortError('Request pool disposed')) { + this.lifetime.abort(reason); + this.queue = []; + } + + private processQueue() { + while ( + !this.lifetime.signal.aborted && + this.inflight.size < this.poolSize && + this.queue.length + ) { + this.startRequest(this.queue.shift()!); + } + } + + 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, + signal: request.controller.signal, + }); + if (request.controller.signal.aborted) { + response.body?.cancel().catch(() => {}); + request.reject(request.controller.signal.reason); + } else request.resolve(response); + } catch (error) { + request.cleanup(); + request.reject(error); + } finally { + this.inflight.delete(request); + this.processQueue(); + } + } +} diff --git a/src/dicom/core/source/__tests__/byteSource.spec.ts b/src/dicom/core/source/__tests__/byteSource.spec.ts new file mode 100644 index 000000000..70bc55726 --- /dev/null +++ b/src/dicom/core/source/__tests__/byteSource.spec.ts @@ -0,0 +1,281 @@ +import { describe, expect, it } from 'vitest'; +import { fromBlob, fromUrl, type ByteRange } from '../byteSource'; +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) => + bytes.slice(range?.start ?? 0, range?.end ?? bytes.length); + +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; +}; + +/** 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 { 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'); + requests.push(range); + 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); + const headers = new Headers({ 'content-length': String(end - start) }); + if (span && exposeContentRange) + headers.set( + 'content-range', + contentRange ?? `bytes ${start}-${end - 1}/${bytes.length}` + ); + 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', () => { + it.each([ + undefined, + { start: 10, end: 20 }, + { start: 990 }, + { start: 5, end: 5000 }, + ])('reads %j', async (range) => { + const source = fromBlob(new Blob([bytes])); + expect(await readStream(source.read(signal(), range))).toEqual( + expected( + range && { + ...range, + end: Math.min(range.end ?? bytes.length, bytes.length), + } + ) + ); + }); + + 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); + controller.abort(new DOMException('stop', 'AbortError')); + await expect(readStream(stream)).rejects.toMatchObject({ + name: 'AbortError', + }); + }); +}); + +describe('URL byte source', () => { + it('reads the whole resource without a Range header', async () => { + const { http, source } = urlSource(); + expect(await readStream(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, source } = urlSource(options); + + const bounded = await readStream( + source.read(signal(), { start: 100, end: 300 }) + ); + const open = await readStream(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, source } = urlSource({ honorRange }); + expect(source.rangeSupport?.()).toBe('unknown'); + await readStream(source.read(signal())); + expect(source.rangeSupport?.()).toBe('unknown'); + await readStream(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, 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, 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 { source } = urlSource({ startShift: -50 }); + 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 { 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, source } = urlSource(); + await readStream(source.read(signal(), { start: 0, end: 10 })); + expect(http.signals[0]?.aborted).toBe(true); + }); + + it.each([ + [401, /HTTP 401/], + [404, /HTTP 404/], + [500, /HTTP 500/], + [416, /Range could not be satisfied/], + ])('fails a %i response', async (status, message) => { + const { source } = urlSource({ status }); + await expect( + readStream(source.read(signal(), { start: 0, end: 4 })) + ).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(); + await reader.read(); + await reader.cancel(); + expect(http.bodies[0].cancelled).toBe(true); + }); +}); diff --git a/src/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts b/src/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts new file mode 100644 index 000000000..ee149d52a --- /dev/null +++ b/src/dicom/core/source/__tests__/parseContentRangeHeader.spec.ts @@ -0,0 +1,26 @@ +import { parseContentRangeHeader } from '../parseContentRangeHeader'; +import { describe, expect, it } from 'vitest'; + +describe('parseContentRangeHeader', () => { + 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.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/src/dicom/core/source/byteSource.ts b/src/dicom/core/source/byteSource.ts new file mode 100644 index 000000000..4fd992fcf --- /dev/null +++ b/src/dicom/core/source/byteSource.ts @@ -0,0 +1,222 @@ +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 }; + +/** + * 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 = { + 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'; + +/** 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); + +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(); + if (offset >= end) { + controller.close(); + return; + } + const next = Math.min(end, offset + step); + step *= 2; + 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. */ +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; +}; + +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 Error(`HTTP ${response.status} for ${url}`); +} + +/** + * 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) => { + // 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 ranged = range + ? { cache: 'no-store' as const, headers: { Range: rangeHeader(range) } } + : {}; + const response = await fetchFn(url, { ...ranged, 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 } = 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(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: (stream) => + pull(stream).catch((error) => { + abort(); + throw error; + }), + 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/utils/parseContentRangeHeader.ts b/src/dicom/core/source/parseContentRangeHeader.ts similarity index 54% rename from src/utils/parseContentRangeHeader.ts rename to src/dicom/core/source/parseContentRangeHeader.ts index c0a00e02f..b43281f9c 100644 --- a/src/utils/parseContentRangeHeader.ts +++ b/src/dicom/core/source/parseContentRangeHeader.ts @@ -1,38 +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. - * @param headerValue - * @returns - */ +/** 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' }; - if (headerValue.length === 0) return { type: 'invalid-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/src/dicom/core/utils.ts b/src/dicom/core/utils.ts new file mode 100644 index 000000000..eb9801381 --- /dev/null +++ b/src/dicom/core/utils.ts @@ -0,0 +1,72 @@ +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, ''); + +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 const toAscii = (bytes: Uint8Array, { ignoreNulls = false } = {}) => + Array.from(ignoreNulls ? bytes.filter((byte) => byte !== 0) : bytes, (byte) => + String.fromCharCode(byte) + ).join(''); + +/** Starts a generator and returns a function that feeds it one value per step. */ +export function asCoroutine(gen: Generator) { + 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; +}; + +/** + * 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/src/dicom/core/volume/__tests__/allocateVolume.spec.ts b/src/dicom/core/volume/__tests__/allocateVolume.spec.ts new file mode 100644 index 000000000..5c4db6f6f --- /dev/null +++ b/src/dicom/core/volume/__tests__/allocateVolume.spec.ts @@ -0,0 +1,157 @@ +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'; +import { datasetFromTags } from '@/tests/dicomDataset'; +import { Tags } from '../../metadata/dicomTags'; + +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.data).toBeInstanceOf(Uint16Array); + expect(volume.data).toHaveLength(48); + expect([...volume.loaded]).toEqual([0, 0, 0]); + 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.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('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); + + expect(volume.dimensions[2]).toBe(3); + expect(volume.members).toEqual([members[1], members[2], members[0]]); + }); + + it('takes the planned slice spacing as given', () => { + const update = plannedUpdate([pixelSlice(1), pixelSlice(19)]); + const reconstruction = { + ...update.collection.reconstruction, + sliceSpacing: 9, + }; + + const volume = allocateVolume({ + ...update, + collection: { ...update.collection, reconstruction }, + }); + + expect(volume).toMatchObject({ + dimensions: [4, 4, 2], + spacing: [0.5, 0.5, 9], + }); + }); + + 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]); + + 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__/enhancedFixture.ts b/src/dicom/core/volume/__tests__/enhancedFixture.ts new file mode 100644 index 000000000..193bd3bf9 --- /dev/null +++ b/src/dicom/core/volume/__tests__/enhancedFixture.ts @@ -0,0 +1,70 @@ +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({ + '00080016': '1.2.840.10008.5.1.4.1.1.2.1', + '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/src/dicom/core/volume/__tests__/frameGeometry.spec.ts b/src/dicom/core/volume/__tests__/frameGeometry.spec.ts new file mode 100644 index 000000000..dd27ba4ec --- /dev/null +++ b/src/dicom/core/volume/__tests__/frameGeometry.spec.ts @@ -0,0 +1,370 @@ +import { describe, expect, it } from 'vitest'; +import type { DicomDataset } from '../../metadata/dicomDataset'; +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 { + 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)])); + +/** 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( + (component) => + volume.origin[component] + + index.reduce( + (sum, step, axis) => + sum + + step * volume.spacing[axis] * volume.direction[axis * 3 + component], + 0 + ) + ); + +describe('enhanced volume Functional Groups', () => { + 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); + 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]); + expect(volume.data).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); + 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); + 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, + ...decodingWith(async ({ instance }) => { + suppliedMetadata = instance.dataset; + return { size: [2, 2, 2], components: 1, data: decoded }; + }), + }); + const instance = instanceFor(metadata, fromBlob(new Blob(['pixels']))); + const volume = allocateVolume(plannedUpdate([instance])); + 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', + }), + ]), + ]), + ] + ); + expect(allocate(metadata).data).toBeInstanceOf(Float32Array); + }); + + it.each([ + ['repeated-position', [0, 0, 2]], + ['uneven-slice-spacing', [0, 1, 3]], + ])( + '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(metadata); + expect(reconstructionOf(metadata)).toEqual({ + kind: 'irregular', + reason, + }); + expect(volume.dimensions).toEqual([2, 2, 3]); + } + ); + + 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( + reconstructionOf(enhanced(ctShared(), [positioned('0\\0\\0'), second])) + ).toEqual({ kind: 'irregular', reason: 'unreadable-geometry' }); + }); + + 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( + reconstructionOf( + enhanced(ctShared(), [positioned('0\\0\\0'), changedSpacing]) + ) + ).toEqual({ kind: 'irregular', reason: '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(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', () => { + 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('reports shared-plane temporal frames as irregular', () => { + const metadata = sharedPlaneTemporal(); + expect(reconstructionOf(metadata).kind).toBe('irregular'); + }); + + it.each([1, -1])( + 'preserves stored frame direction %s through registration and image allocation', + (direction) => { + const positions = [0, 1, 2].map((index) => 10 + direction * index * 3); + const volume = allocate( + enhanced( + ctShared(), + positions.map((z) => positioned(`1\\2\\${z}`)) + ) + ); + expect(volume.spacing[2]).toBe(3); + positions.forEach((z, index) => + expect(indexToWorld(volume, [0, 0, index])).toEqual([1, 2, z]) + ); + } + ); +}); + +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); + expect(volume.dimensions).toEqual([2, 2, 3]); + 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]); + else expect(volume.spacing[tag === '00280030' ? 0 : 2]).toBe(1); + 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) }) + ); + 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); + 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('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/src/dicom/core/volume/__tests__/loadFrames.spec.ts b/src/dicom/core/volume/__tests__/loadFrames.spec.ts new file mode 100644 index 000000000..9169c83de --- /dev/null +++ b/src/dicom/core/volume/__tests__/loadFrames.spec.ts @@ -0,0 +1,367 @@ +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 { defaultDecoderTable } from '../../pixels/decoderTable'; +import type { DecodeUnit, PixelDecoder } from '../../pixels/pixelDecoder'; +import { allocated } from './volumeFixture'; +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: { + readConcurrency?: number; + abort?: AbortSignal; + runtime?: DicomRuntime; + } = {} +) => { + const volume = allocated(members); + const runtime = options.runtime ?? nativeOnly(); + const updates: VolumeUpdate[] = []; + for await (const update of loadVolume(volume, { + runtime: { + ...runtime, + readConcurrency: options.readConcurrency ?? runtime.readConcurrency, + }, + signal: options.abort ?? signal(), + })) + 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, + }), + }; +}; + +/** 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; + 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(); + const { source, ranges } = recorded(blobOf(bytes)); + const instance = await readInstance(source, signal()); + + const { volume, updates } = await load([instance], { readConcurrency: 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('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], { readConcurrency: 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('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()); + + 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, { readConcurrency: 1 }); + + 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([ + ['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 behaviour === 'honours' && 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]); + + 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('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(failsWhole(/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( + 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 () => { + 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], { + readConcurrency: 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); + }); +}); diff --git a/src/dicom/core/volume/__tests__/loadVolume.spec.ts b/src/dicom/core/volume/__tests__/loadVolume.spec.ts new file mode 100644 index 000000000..c777106d7 --- /dev/null +++ b/src/dicom/core/volume/__tests__/loadVolume.spec.ts @@ -0,0 +1,473 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { + createDicomRuntime, + type DicomRuntime, +} from '../../runtime/createDicomRuntime'; +import type { WholeInstanceDecode } from '../../pixels/pixelDecoder'; +import { singleDecoderTable } from '../../pixels/decoderTable'; +import type { GdcmLane } from '../../runtime/gdcmDecoder'; +import { hangingSource } from '@/tests/byteSourceFixtures'; +import { loadedRange, type Volume } from '../allocateVolume'; +import type { ByteSource } from '../../source/byteSource'; +import { + loadVolume, + type LoadVolumeOptions, + type VolumeUpdate, +} from '../loadVolume'; +import { + allocated, + pixelSlice, + slicePixels, + sliceValues, + valueDecoder, +} from './volumeFixture'; +import { decodingWith } from '@/tests/dicomVolumeFixtures'; +import { Tags } from '../../metadata/dicomTags'; + +const runtimes: DicomRuntime[] = []; +afterEach(() => runtimes.splice(0).forEach((runtime) => runtime.dispose())); + +const runtimeWith = (decoder: WholeInstanceDecode, decodeConcurrency = 1) => { + const runtime = createDicomRuntime({ + ...decodingWith(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, + { + readConcurrency = runtime.readConcurrency, + ...options + }: Pick & { readConcurrency?: number } = {} +) => + collect( + loadVolume(volume, { + runtime: { ...runtime, readConcurrency }, + 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)), { + readConcurrency: 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('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] === 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), { + readConcurrency: 1, + }); + + const errors = updates.flatMap((update) => + 'error' in update + ? [[update.slot, update.error.message, update.error.cause]] + : [] + ); + expect(errors).toEqual([ + [ + 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([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: { [Tags.Columns]: '1', [Tags.NumberOfFrames]: 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 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) => { + 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); + const resume = Promise.withResolvers(); + const decoder: WholeInstanceDecode = 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, + readConcurrency: 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 readConcurrency undecoded', async () => { + const readConcurrency = 3; + const decodesStarted: number[] = []; + const decode = valueDecoder(); + const { volume, reads, readStarted } = recordedStack(8); + let mostOutstanding = 0; + const ahead = readStarted(1 + readConcurrency); + const decoder: WholeInstanceDecode = 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), { + readConcurrency, + }); + + expect(updates).toHaveLength(8); + expect(reads).toHaveLength(8); + expect(mostOutstanding).toBeLessThanOrEqual(readConcurrency); + }); + + it('runs at most decodeConcurrency decodes at once', async () => { + let active = 0; + let peak = 0; + const gate = Promise.withResolvers(); + const twoStarted = Promise.withResolvers(); + 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('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(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, update.error.cause]] + : [] + ) + ).toEqual([ + [1, 'File pixel-1 (member 1) could not be read: connection reset', 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('keeps decoding while the consumer waits, marking slices loaded only as they are yielded', async () => { + const decoded: number[] = []; + const decode = valueDecoder(decoded); + const lastStarted = Promise.withResolvers(); + 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, + }) + ); + // 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); + expect(sliceValues(volume)).toEqual([null, null, null]); + }); + + it('ends and stops the GDCM worker when the runtime is disposed mid-decode', async () => { + const started = Promise.withResolvers(); + 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)); + 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/src/dicom/core/volume/__tests__/pixelFormat.spec.ts b/src/dicom/core/volume/__tests__/pixelFormat.spec.ts new file mode 100644 index 000000000..ae8367fb4 --- /dev/null +++ b/src/dicom/core/volume/__tests__/pixelFormat.spec.ts @@ -0,0 +1,288 @@ +import { datasetFromTags } from '@/tests/dicomDataset'; +import { describe, it, expect } from 'vitest'; +import { Tags } from '../../metadata/dicomTags'; +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. +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); + }); +}); + +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/src/dicom/core/volume/__tests__/pixelValidation.spec.ts b/src/dicom/core/volume/__tests__/pixelValidation.spec.ts new file mode 100644 index 000000000..c03609e9b --- /dev/null +++ b/src/dicom/core/volume/__tests__/pixelValidation.spec.ts @@ -0,0 +1,50 @@ +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/src/dicom/core/volume/__tests__/slotOrder.spec.ts b/src/dicom/core/volume/__tests__/slotOrder.spec.ts new file mode 100644 index 000000000..6c0006fe8 --- /dev/null +++ b/src/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/src/dicom/core/volume/__tests__/volumeFixture.ts b/src/dicom/core/volume/__tests__/volumeFixture.ts new file mode 100644 index 000000000..c831c0cbe --- /dev/null +++ b/src/dicom/core/volume/__tests__/volumeFixture.ts @@ -0,0 +1,59 @@ +import { + sliceDataset, + type SliceOptions, +} from '../../collections/__tests__/sliceFixture'; +import { instanceFor } from '@/tests/dicomDataset'; +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 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 allocated = (members: Instance[], previous?: Volume) => + allocateVolume(plannedUpdate(members), 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[] = []): WholeInstanceDecode => + async ({ bytes }) => { + const { value, ...pixels } = slicePixels(bytes); + decoded.push(value); + return pixels; + }; + +/** 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/dicom/core/volume/__tests__/volumeLayout.spec.ts b/src/dicom/core/volume/__tests__/volumeLayout.spec.ts new file mode 100644 index 000000000..0bd76656f --- /dev/null +++ b/src/dicom/core/volume/__tests__/volumeLayout.spec.ts @@ -0,0 +1,176 @@ +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 { volumeLayout, type VolumeSource } from '../volumeLayout'; + +function volumeSource(overrides: Record = {}) { + const metadata = { + [Tags.SOPInstanceUID]: '1.2.3', + [Tags.ImagePositionPatient]: '0\\0\\0', + [Tags.ImageOrientationPatient]: '1\\0\\0\\0\\1\\0', + [Tags.Rows]: '3', + [Tags.Columns]: '4', + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', + [Tags.SamplesPerPixel]: '1', + ...overrides, + }; + return { dataset: datasetFromTags(Object.entries(metadata)) }; +} + +function positionedSource(z: number, overrides: Record = {}) { + return volumeSource({ + [Tags.ImagePositionPatient]: `0\\0\\${z}`, + ...overrides, + }); +} + +const AXIAL = [1, 0, 0, 0, 1, 0]; + +/** 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); +} + +const spacingOf = (layout: ReturnType) => layout.spacing; + +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\\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 layout = layoutOf( + [volumeSource({ [Tags.PixelSpacing]: value })], + AXIAL + ); + expect(spacingOf(layout)).toEqual(expected); + } + ); + + it('allocates for the modality range of every member', () => { + const layout = layoutOf( + [ + positionedSource(0), + positionedSource(1, { + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', + [Tags.RescaleSlope]: '112067.85375182', + [Tags.RescaleIntercept]: '0', + }), + ], + AXIAL + ); + expect(layout.bufferType).toBe(Float32Array); + expect(dimensionsOf(layout)).toEqual([4, 3, 2]); + }); + + it('matches ITK spacing order for single-slice images with SpacingBetweenSlices', () => { + const layout = layoutOf( + [ + volumeSource({ + [Tags.PixelSpacing]: '2.5\\0.75', + [Tags.SpacingBetweenSlices]: '7.25', + }), + ], + AXIAL + ); + + expect(spacingOf(layout)).toEqual([0.75, 2.5, 7.25]); + }); + + it('uses declared inter-frame spacing for a multi-frame volume', () => { + const layout = layoutOf( + [ + volumeSource({ + [Tags.NumberOfFrames]: '32', + [Tags.PixelSpacing]: '0.0104\\0.046875', + [Tags.SpacingBetweenSlices]: '0.1875', + }), + ], + AXIAL + ); + 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 positions over a declared SpacingBetweenSlices', () => { + const layout = layoutOf( + [ + positionedSource(0, { + [Tags.PixelSpacing]: '2.5\\0.75', + [Tags.SpacingBetweenSlices]: '19', + }), + positionedSource(9), + positionedSource(18), + ], + AXIAL + ); + + expect(spacingOf(layout)).toEqual([0.75, 2.5, 9]); + }); + + it('orients the image along the validated slice normal', () => { + const layout = layoutOf( + [volumeSource({ [Tags.ImageOrientationPatient]: '0\\1\\0\\0\\0\\-1' })], + [0, 1, 0, 0, 0, -1] + ); + + expect(layout.direction).toEqual([0, 1, 0, 0, 0, -1, -1, 0, 0]); + }); + + 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(layout.direction).toBeNull(); + }); + + it('leaves the Z spacing alone when no position can be read', () => { + const layout = layoutOf( + [ + volumeSource({ [Tags.ImagePositionPatient]: '' }), + volumeSource({ [Tags.ImagePositionPatient]: '' }), + ], + AXIAL + ); + + expect(spacingOf(layout)[2]).toBe(1); + }); + + it('takes the declared SpacingBetweenSlices when no position can be read', () => { + const layout = layoutOf( + [ + volumeSource({ + [Tags.ImagePositionPatient]: '', + [Tags.SpacingBetweenSlices]: '2.5', + }), + volumeSource({ [Tags.ImagePositionPatient]: '' }), + ], + AXIAL + ); + + expect(spacingOf(layout)[2]).toBe(2.5); + }); +}); diff --git a/src/dicom/core/volume/allocateVolume.ts b/src/dicom/core/volume/allocateVolume.ts new file mode 100644 index 000000000..dc47c429e --- /dev/null +++ b/src/dicom/core/volume/allocateVolume.ts @@ -0,0 +1,150 @@ +import type { Instance } from '../instance/readInstance'; +import type { InstanceCollectionUpdate } from '../collections/instanceRegistry'; +import type { VolumeBuffer } from './pixelFormat'; +import { nativeFramesOverrun } from '../pixels/frameIndex'; +import { planVolumeAllocation } from './volumeLayout'; + +type Triple = [number, number, number]; +type Vector3 = Readonly; + +/** + * One buffer plus the geometry that places it. Everything is immutable except + * `data` and `loaded`, which only `loadVolume` writes. + */ +export type Volume = Readonly<{ + /** Planned order; in a multi-file volume member i fills slice i. */ + members: readonly Instance[]; + /** Columns, rows, slices. */ + dimensions: Vector3; + components: number; + origin: Vector3; + /** Row-major 3x3: row direction, column direction, slice direction. */ + direction: readonly number[]; + spacing: Vector3; + /** Allocation warnings as [title, details]. */ + warnings: ReadonlyArray; + data: VolumeBuffer; + /** 1 where a slice holds decoded pixels, indexed by slice. */ + loaded: Uint8Array; +}>; + +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 + ? [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 image collection fills. With `previous`, + * slices already decoded there are copied across, so growth never decodes + * again. + */ +export function allocateVolume( + update: Pick, + 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, + collection.reconstruction + ); + const { columns, rows, slices, samplesPerPixel } = layout; + const volume: Volume = Object.freeze({ + members: Object.freeze([...members]), + dimensions: [columns, rows, slices] as const, + components: samplesPerPixel, + origin: (layout.origin ?? [0, 0, 0]) as Triple, + direction: layout.direction ?? IDENTITY, + spacing: layout.spacing as Triple, + warnings, + data: new layout.bufferType(columns * rows * slices * samplesPerPixel), + loaded: new Uint8Array(slices), + }); + if (previous) copyDecoded(volume, previous); + return 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/src/dicom/core/volume/loadVolume.ts b/src/dicom/core/volume/loadVolume.ts new file mode 100644 index 000000000..7c0eeafd3 --- /dev/null +++ b/src/dicom/core/volume/loadVolume.ts @@ -0,0 +1,389 @@ +import type { DicomRuntime } from '../runtime/createDicomRuntime'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; +import { abortError, linkedController } from '../utils'; +import { readBytes } from '../source/byteSource'; +import { planDecode, type DecoderTable } from '../pixels/decoderTable'; +import type { DecodedPixels, DecodeUnit } from '../pixels/pixelDecoder'; +import { getPixelFormat, type VolumeBufferConstructor } from './pixelFormat'; +import { + componentRanges, + memberLoaded, + memberSlices, + sliceLength, + type Volume, +} from './allocateVolume'; +import { assertSamplesRepresentable, assertUnitFits } 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, + 'decoders' | 'decodeConcurrency' | 'readConcurrency' | 'signal' + >; + signal: AbortSignal; + /** Read before every read and decode; defaults to the middle member's slot. */ + focus?: () => 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)); + +// 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, + lowest(slices), + highest(slices), +]; + +const failure = ( + volume: Volume, + slices: readonly number[], + error: unknown +): VolumeUpdate => ({ + slot: lowest(slices), + extent: sliceExtent(volume, slices), + error: ensureError(error), +}); + +const memberName = (volume: Volume, member: number) => { + const sop = getDatasetTag( + volume.members[member].dataset, + Tags.SOPInstanceUID + ); + return `File ${sop ?? 'without SOP Instance UID'} (member ${member})`; +}; + +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}`; +}; + +/** A Float32 volume holds rounded values, so the range it reports is rounded too. */ +const storedRange = ( + volume: Volume, + range: ReadonlyArray +) => { + const stored = volume.data instanceof Float32Array ? Math.fround : Number; + return range.map(([min, max]): [number, number] => [ + stored(min), + stored(max), + ]); +}; + +/** 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 }, + { + dims: volume.dimensions, + components: volume.components, + frames: unit.frames, + multiFile: volume.members.length > 1, + }, + where + ); + const range = pixels.range ?? componentRanges(data, volume.components); + const { dataset } = volume.members[unit.member]; + assertSamplesRepresentable( + data, + { + min: Math.min(...range.map(([min]) => min)), + max: Math.max(...range.map(([, max]) => max)), + }, + volume.data, + { + where, + rescales: () => + Array.from({ length: unit.frames }, (_, index) => + getPixelFormat(dataset, unit.firstFrame + index) + ), + } + ); + volume.data.set(data, sliceLength(volume) * unit.slot); + return { + slot: unit.slot, + extent: sliceExtent(volume, unit.slices), + range: storedRange(volume, range), + }; +} + +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 new Error( + `${memberName(volume, member)} cannot be decoded: ${planned.error.message}`, + { cause: planned.error } + ); + 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. */ +function planUnits(volume: Volume, decoders: DecoderTable) { + const units: Unit[] = []; + const failures: VolumeUpdate[] = []; + 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 { 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]; + +type Loader = { + volume: Volume; + runtime: LoadVolumeOptions['runtime']; + stopped: AbortSignal; + focus: () => number; +}; + +/** + * Starts reads and decodes whenever one settles: decodes first, up to the + * decode concurrency, then reads while fewer than the read concurrency 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 }: 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 updates = [...failures]; + let reading = 0; + 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 = (update: VolumeUpdate) => { + if (!stopped.aborted) updates.push(update); + notify(); + }; + const failed = (lost: Unit[], error: unknown) => + failure( + volume, + lost.flatMap((unit) => unit.slices), + error + ); + 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 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.member === unit.member && other.range?.end !== undefined + ) + : [unit]; + + const readUnits = async (batch: Unit[]) => { + const [first] = batch; + if (batch.length === 1) + return [ + await readBytes(sourceOf(first), stopped, first.range ?? undefined), + ]; + 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) + ); + }; + + const startRead = (unit: Unit) => { + const batch = batchOf(unit); + batch.forEach((each) => waiting.delete(each.slot)); + const probe = + unit.range !== null && + rangeSupport(unit) === 'unknown' && + [...waiting.values()].some((other) => other.member === unit.member); + if (probe) probing.add(unit.member); + reading += 1; + readUnits(batch) + .then( + (bytes) => + batch.forEach((each, index) => + ready.set(each.slot, { unit: each, bytes: bytes[index] }) + ), + (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); + reading -= 1; + pump(); + }); + }; + + const written = (unit: Unit, pixels: DecodedPixels): VolumeUpdate => { + try { + return write(volume, unit, pixels); + } catch (error) { + return failed([unit], error); + } + }; + + const startDecode = (slot: number) => { + const { unit, bytes } = ready.get(slot)!; + ready.delete(slot); + decoding += 1; + Promise.resolve() + .then(() => { + stopped.throwIfAborted(); + return unit.decode(bytes, stopped); + }) + .then( + (pixels) => (stopped.aborted ? undefined : written(unit, pixels)), + (error) => + failed([unit], unitFailure(unitName(volume, unit), 'decoded', error)) + ) + .then((update) => { + decoding -= 1; + if (update) settle(update); + pump(); + }); + }; + + const claimable = () => + [...waiting.values()] + .filter((unit) => !probing.has(unit.member)) + .map((unit) => unit.slot); + + const nextDecode = () => + !stopped.aborted && decoding < runtime.decodeConcurrency + ? next(ready.keys()) + : undefined; + const nextRead = () => + !stopped.aborted && reading + ready.size < runtime.readConcurrency + ? next(claimable()) + : undefined; + + 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 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, + { runtime, signal, focus = () => middleSlot(volume) }: LoadVolumeOptions +) { + const { controller, release } = linkedController(signal, runtime.signal); + const stopped = controller.signal; + const loader = createLoader({ volume, runtime, stopped, focus }); + loader.start(); + try { + for (;;) { + const next = stopped.aborted ? undefined : loader.updates.shift(); + if (next) { + markLoaded(volume, next); + yield next; + } else if (stopped.aborted || loader.done()) return; + else await loader.changed(); + } + } finally { + controller.abort(abortError('DICOM volume loading stopped')); + release(); + } +} diff --git a/src/dicom/core/volume/nmGeometry.ts b/src/dicom/core/volume/nmGeometry.ts new file mode 100644 index 000000000..9e5e85c3e --- /dev/null +++ b/src/dicom/core/volume/nmGeometry.ts @@ -0,0 +1,19 @@ +import type { 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, + }; + return { ...geometry, direction, reconstruction }; +} diff --git a/src/dicom/core/volume/pixelFormat.ts b/src/dicom/core/volume/pixelFormat.ts new file mode 100644 index 000000000..599451b3a --- /dev/null +++ b/src/dicom/core/volume/pixelFormat.ts @@ -0,0 +1,207 @@ +import type { DicomDataset } from '../metadata/dicomDataset'; +import { Tags } from '../metadata/dicomTags'; +import { getFrameTag, perFrameGroups } from '../metadata/functionalGroups'; +import { readModalityRescale } from '../metadata/modalityRescale'; +import { frameCount } from '../pixels/pixelDecoder'; +import { numberOr } from '../utils'; + +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; + +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([ + [Uint8Array, { min: 0, max: 2 ** 8 - 1 }], + [Uint16Array, { min: 0, max: 2 ** 16 - 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 `buffer` can hold without wrapping, or undefined if its element + * type has no fixed integer range to enforce. + */ +export function getBufferValueRange(buffer: ArrayBufferView) { + return INTEGER_VALUE_RANGES.get( + buffer.constructor as IntegerArrayConstructor + ); +} + +/** + * Whether a decoded value range is representable in `buffer`'s element type. + * A buffer with no enforceable range accepts everything. + */ +export function valuesFitBuffer(range: ValueRange, buffer: ArrayBufferView) { + const bufferRange = getBufferValueRange(buffer); + return ( + !bufferRange || + (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) + ); +} + +/** + * 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(Tags.BitsStored), 0), + pixelRepresentation: numberOr(valueOf(Tags.PixelRepresentation), 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 }: ValueRange) => + Math.max(Math.abs(min), Math.abs(max)); + +const isIntegralRescale = (format: Rescale) => + Number.isInteger(format.rescaleSlope) && + Number.isInteger(format.rescaleIntercept); + +/** Float32 holds every integer up to 2^24 exactly. */ +const float32KeepsIntegers = (range: ValueRange) => + magnitude(range) <= FLOAT32_EXACT_INTEGER; + +/** Float32's spacing near `range` stays below one stored step of `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: ValueRange, format: Rescale) => + isIntegralRescale(format) + ? float32KeepsIntegers(range) + : float32KeepsSteps(range, format.rescaleSlope); + +type UsableFormat = { format: PixelFormat; range: ValueRange }; + +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 { + const min = Math.min(...usable.map(({ range }) => range.min)); + const max = Math.max(...usable.map(({ range }) => range.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; +} + +/** + * 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 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)) + ? fractionalBufferType(usable) + : integralBufferType(usable); +} + +/** + * 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: Math.min(frameCount(dataset), perFrameGroups(dataset).length + 1), + }, + (_, index) => getPixelFormat(dataset, index) + ); diff --git a/src/dicom/core/volume/pixelValidation.ts b/src/dicom/core/volume/pixelValidation.ts new file mode 100644 index 000000000..49bffd86e --- /dev/null +++ b/src/dicom/core/volume/pixelValidation.ts @@ -0,0 +1,106 @@ +import { + float32Holds, + 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. */ +type UnitShape = Readonly<{ + size: readonly number[]; + components: number; + samples: number; +}>; + +export function assertSamplesRepresentable( + decoded: ArrayLike, + range: ValueRange, + buffer: ArrayBufferView, + { + where, + rescales, + }: { + where: string; + /** Every frame calibration the samples went through; read only for Float32. */ + rescales: () => readonly Rescale[]; + } +) { + 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. ` + + UNCONVERTED + ); + } + 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}. ` + + UNCONVERTED + ); + } + 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. ` + + UNCONVERTED + ); + } +} + +// 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, components, frames, multiFile } = volume; + const [width, height, unitFrames = 1] = unit.size; + assertSampleCount(unit, where); + if ( + width !== dims[0] || + height !== dims[1] || + unitFrames !== frames || + unit.components !== components + ) { + // 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 ${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(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 ${unit.samples} samples; expected ${expected}` + ); +} diff --git a/src/dicom/core/volume/slotOrder.ts b/src/dicom/core/volume/slotOrder.ts new file mode 100644 index 000000000..f22b04df8 --- /dev/null +++ b/src/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/src/dicom/core/volume/ultrasoundSpacing.ts b/src/dicom/core/volume/ultrasoundSpacing.ts new file mode 100644 index 000000000..22e6a007a --- /dev/null +++ b/src/dicom/core/volume/ultrasoundSpacing.ts @@ -0,0 +1,42 @@ +import { getDatasetModality } from '../metadata/datasetAccess'; +import { readUltrasoundRegions, unitToMm } from '../metadata/ultrasoundRegion'; +import type { VolumeSource } from './volumeLayout'; + +const isUsableSpacing = (value: number) => + Number.isFinite(value) && value !== 0; + +/** Display spacing from the first ultrasound region; warnings are [title, details]. */ +export function applyUltrasoundSpacing( + spacing: number[], + sources: readonly VolumeSource[] +): { 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 { region } = readUltrasoundRegions(sources[0].dataset); + if (!region) return unchanged; + + 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) return unchanged; + + const spacingX = region.physicalDeltaX * xFactor; + const spacingY = region.physicalDeltaY * yFactor; + if (!isUsableSpacing(spacingX) || !isUsableSpacing(spacingY)) + return { + spacing, + warnings: [ + [ + 'Invalid ultrasound calibration', + `The ultrasound region declares PhysicalDeltaX=${region.physicalDeltaX} and PhysicalDeltaY=${region.physicalDeltaY}. Measurements use the image pixel spacing instead.`, + ], + ], + }; + + return { spacing: [spacingX, spacingY, spacing[2]], warnings: [] }; +} diff --git a/src/dicom/core/volume/volumeLayout.ts b/src/dicom/core/volume/volumeLayout.ts new file mode 100644 index 000000000..4c427c449 --- /dev/null +++ b/src/dicom/core/volume/volumeLayout.ts @@ -0,0 +1,115 @@ +import type { DicomDataset } from '../metadata/dicomDataset'; +import { getDatasetTag } from '../metadata/datasetAccess'; +import { Tags } from '../metadata/dicomTags'; +import { readGeometryFacts, sliceNormalOf } from '../collections/instanceFacts'; +import type { Reconstruction } from '../collections/reconstructVolume'; +import { readDatasetDetails } from '../collections/datasetDetails'; +import { readPixelSpacing, spacingOr1 } from '../metadata/spatialMetadata'; +import { getFrameTag } from '../metadata/functionalGroups'; +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. */ +export type VolumeSource = { dataset: DicomDataset }; + +const isPositiveFiniteNumber = (value: number) => + Number.isFinite(value) && value > 0; + +// 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 { frames: nm }; + return { + frames: + frameCount(dataset) < 2 + ? null + : 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 +) { + const { dataset } = sources[0]; + const { frames } = frameGeometry(sources); + const geometry = frames ?? readGeometryFacts(dataset); + const effectiveOrientation = orientation ?? geometry.orientation; + return { + ...geometry, + reconstruction: frames?.reconstruction ?? reconstruction, + direction: allocationDirection(effectiveOrientation, frames?.direction), + }; +} + +function allocationShape(sources: readonly VolumeSource[]) { + const { dataset } = sources[0]; + const valueOf = (tag: string) => getDatasetTag(dataset, tag); + return { + 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), + }; +} + +function allocationSpacing( + dataset: DicomDataset, + { reconstruction }: ReturnType +) { + const sliceSpacing = reconstruction.sliceSpacing ?? 0; + const z = isPositiveFiniteNumber(sliceSpacing) + ? sliceSpacing + : spacingOr1(getFrameTag(dataset, Tags.SpacingBetweenSlices)); + return [...readPixelSpacing(dataset), z]; +} + +/** + * 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 +) { + if (sources.length === 0) + throw new Error('Cannot allocate an image from zero instances'); + const shape = allocationShape(sources); + const geometry = allocationGeometry(sources, orientation, reconstruction); + return { + ...shape, + origin: geometry.position, + direction: geometry.direction, + spacing: allocationSpacing(sources[0].dataset, geometry), + bufferType: getVolumeBufferType( + sources.flatMap((source) => instancePixelFormats(source.dataset)) + ), + }; +} + +/** Lays out the planned members of an image collection, with allocation warnings. */ +export function planVolumeAllocation( + sources: readonly VolumeSource[], + orientation: number[] | null, + reconstruction: Reconstruction +) { + const layout = volumeLayout(sources, orientation, reconstruction); + const { spacing, warnings } = applyUltrasoundSpacing(layout.spacing, sources); + return { layout: { ...layout, spacing }, warnings }; +} diff --git a/src/dicom/vtk/__tests__/thumbnail.spec.ts b/src/dicom/vtk/__tests__/thumbnail.spec.ts new file mode 100644 index 000000000..0c79597fb --- /dev/null +++ b/src/dicom/vtk/__tests__/thumbnail.spec.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest'; +import { sliceToThumbnail } from '../thumbnail'; + +const bytes = (slice: { data: Uint8Array }) => Array.from(slice.data); + +describe('sliceToThumbnail', () => { + it('casts a slice onto the full 8 bit range of its window', () => { + const slice = sliceToThumbnail({ + data: [0, 10, 20, 30, 40, 50, 60, 70], + width: 4, + height: 2, + components: 1, + range: [0, 70], + }); + + expect(slice.width).toBe(4); + expect(slice.height).toBe(2); + expect(slice.data).toBeInstanceOf(Uint8Array); + expect(bytes(slice)).toEqual([0, 36, 73, 109, 146, 182, 219, 255]); + }); + + it('clamps samples outside the window', () => { + const slice = sliceToThumbnail({ + data: [0, 10, 15, 20, 30], + width: 5, + height: 1, + components: 1, + range: [10, 20], + }); + + expect(bytes(slice)).toEqual([0, 0, 128, 255, 255]); + }); + + it('reads an empty window as a blank slice instead of dividing by zero', () => { + const slice = sliceToThumbnail({ + data: [1, 5, 9], + width: 3, + height: 1, + components: 1, + range: [5, 5], + }); + + expect(bytes(slice)).toEqual([0, 0, 0]); + }); + + it('reads a sample that is not a finite number as blank', () => { + const slice = sliceToThumbnail({ + data: [NaN, Infinity, -Infinity, 1], + width: 4, + height: 1, + components: 1, + range: [0, 1], + }); + + expect(bytes(slice)).toEqual([0, 0, 0, 255]); + }); + + it('downsamples both axes by one stride to at most 256 on the longer side', () => { + const width = 512; + const slice = sliceToThumbnail({ + data: Uint16Array.from({ length: width * 2 }, (_, index) => index), + width, + height: 2, + components: 1, + range: [0, 255], + }); + + expect(slice.width).toBe(256); + expect(slice.height).toBe(1); + // 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('samples RGB luminance for color slices', () => { + const slice = sliceToThumbnail({ + data: [255, 0, 0, 0, 255, 0, 0, 0, 255], + width: 3, + height: 1, + components: 3, + range: [0, 255], + }); + + expect(bytes(slice)).toEqual([76, 150, 29]); + }); +}); diff --git a/src/dicom/vtk/__tests__/volumeImage.spec.ts b/src/dicom/vtk/__tests__/volumeImage.spec.ts new file mode 100644 index 000000000..8b6e751a0 --- /dev/null +++ b/src/dicom/vtk/__tests__/volumeImage.spec.ts @@ -0,0 +1,139 @@ +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 { decodingWith } from '@/tests/dicomVolumeFixtures'; +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), +]; + +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); + const runtime = createDicomRuntime({ + ...decodingWith(valueDecoder()), + decodeConcurrency: 1, + }); + const ranges: number[][] = []; + for await (const update of loadVolume(volume, { + runtime: { ...runtime, readConcurrency: 1 }, + signal: new AbortController().signal, + })) { + 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(decodingWith(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 = 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 = 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]); + image.delete(); + }); +}); diff --git a/src/dicom/vtk/thumbnail.ts b/src/dicom/vtk/thumbnail.ts new file mode 100644 index 000000000..4f8523c38 --- /dev/null +++ b/src/dicom/vtk/thumbnail.ts @@ -0,0 +1,100 @@ +/** An 8 bit greyscale slice, small enough to encode as a thumbnail. */ +export type ThumbnailSlice = { + width: number; + height: number; + data: Uint8Array; +}; + +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]; +}; + +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, + range, +}: SliceToThumbnailInput) { + 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) / THUMBNAIL_MAX_SIZE) + ); + 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/src/dicom/vtk/volumeImage.ts b/src/dicom/vtk/volumeImage.ts new file mode 100644 index 000000000..6ef7a701c --- /dev/null +++ b/src/dicom/vtk/volumeImage.ts @@ -0,0 +1,79 @@ +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, 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() + .subarray(slice * samplesPerSlice, (slice + 1) * samplesPerSlice); + return sliceToThumbnail({ + data, + width, + height, + components, + range: + components >= 3 + ? thumbnailRange(data, components) + : (scalars.getRange(0) as [number, number]), + }); +} diff --git a/src/enface/__tests__/availability.spec.ts b/src/enface/__tests__/availability.spec.ts index f2c88feb8..75bb3e2ed 100644 --- a/src/enface/__tests__/availability.spec.ts +++ b/src/enface/__tests__/availability.spec.ts @@ -1,18 +1,19 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; import { computed, markRaw, nextTick } from 'vue'; -import DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { useImageCacheStore } from '@/src/store/image-cache'; import { getEnFaceUnavailableReason } from '@/src/enface/availability'; -import { createOCTFixture } from '@/tests/unit/octFixture'; +import { createOCTFixture, volumeOf } from '@/tests/unit/octFixture'; 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 '@/src/core/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { setDicomTag } from './dicomMetadataFixture'; describe('OCT view availability', () => { - let emptyImage: DicomChunkImage | undefined; + let emptyImage: DicomVolumeImage | undefined; const decodeReleases: (() => void)[] = []; beforeEach(() => setActivePinia(createPinia())); @@ -22,8 +23,8 @@ describe('OCT view availability', () => { emptyImage = undefined; }); - it('keeps the view disabled while a cached DICOM image has no metadata chunks', () => { - emptyImage = new DicomChunkImage(); + it('keeps the view disabled while a cached DICOM image has no volume yet', async () => { + emptyImage = (await createOCTFixture()).image; useImageCacheStore().imageById.pending = markRaw(emptyImage); expect(getEnFaceUnavailableReason('pending')).toMatch(/volume/); }); @@ -33,14 +34,13 @@ describe('OCT view availability', () => { expect(getEnFaceUnavailableReason('deleted')).toMatch(/volume/); }); - it('reacts to metadata allocation and complete pixel loading after initially empty raw chunks', async () => { - const fixture = createOCTFixture({ deferDecode: true }); + it('reacts to allocation and complete pixel loading after starting empty', async () => { + const fixture = await createOCTFixture({ deferDecode: true }); decodeReleases.push(fixture.releaseDecode); useImageCacheStore().addProgressiveImage(fixture.image, { id: 'pending' }); const reason = computed(() => getEnFaceUnavailableReason('pending')); expect(reason.value).not.toBeNull(); - await fixture.chunk.loadMeta(); - await fixture.image.addChunks([fixture.chunk]); + fixture.image.setVolume(volumeOf([fixture.instance])); await nextTick(); expect(reason.value).toMatch(/complete volume/); fixture.image.startLoad(); @@ -91,20 +91,16 @@ describe('OCT view availability', () => { it.each(['CT', 'MR', 'PT'] as const)( 'allows a complete grayscale DICOM volume with modality %s', async (modality) => { - const fixture = createOCTFixture(); - const id = useImageCacheStore().addProgressiveImage(fixture.image); - await fixture.chunk.loadMeta(); + const fixture = await createOCTFixture(); const sop = { 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', }[modality]; - fixture.chunk.metadata!.forEach((pair) => { - if (pair[0] === Tags.Modality) pair[1] = modality; - if (pair[0] === Tags.SOPClassUID) pair[1] = sop; - }); - await fixture.image.addChunks([fixture.chunk]); - fixture.image.startLoad(); + setDicomTag(fixture.instance.dataset, Tags.Modality, modality); + setDicomTag(fixture.instance.dataset, Tags.SOPClassUID, sop); + fixture.image.setVolume(volumeOf([fixture.instance])); + const id = useImageCacheStore().addProgressiveImage(fixture.image); await untilLoaded(id); expect(getEnFaceUnavailableReason(id)).toBeNull(); } @@ -113,20 +109,19 @@ describe('OCT view availability', () => { it.each(['radial', 'nonvolumetric'])( 'does not bypass declared OCT geometry guards: %s', async (kind) => { - const fixture = createOCTFixture({ + const fixture = await createOCTFixture({ scanPattern: kind === 'radial' ? '128281' : undefined, }); + if (kind === 'nonvolumetric') + setDicomTag( + fixture.instance.dataset, + Tags.OphthalmicVolumetricPropertiesFlag, + 'NO' + ); + fixture.image.setVolume(volumeOf([fixture.instance])); useImageCacheStore().addProgressiveImage(fixture.image, { id: 'guarded', }); - await fixture.chunk.loadMeta(); - if (kind === 'nonvolumetric') - fixture.chunk.metadata!.push([ - Tags.OphthalmicVolumetricPropertiesFlag, - 'NO', - ]); - await fixture.image.addChunks([fixture.chunk]); - fixture.image.startLoad(); await untilLoaded('guarded'); expect(getEnFaceUnavailableReason('guarded')).toMatch( kind === 'radial' ? /reconstruction/ : /unsuitable/ diff --git a/src/enface/__tests__/calibration.spec.ts b/src/enface/__tests__/calibration.spec.ts index 7e7f6dc9a..0935c02fe 100644 --- a/src/enface/__tests__/calibration.spec.ts +++ b/src/enface/__tests__/calibration.spec.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from 'vitest'; -import type { Chunk } from '@/src/core/streaming/chunk'; -import { Tags } from '@/src/core/dicomTags'; -import { allocateImageFromChunks } from '@/src/utils/allocateImageFromChunks'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +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'; @@ -9,17 +10,19 @@ describe('OCT occupied depth through DICOM allocation', () => { it.each(['0.0104\\0', '0.0104\\NaN'])( 'measures the declared A-line spacing when another axis is unavailable: %s', (pixelSpacing) => { - const metadata = Object.entries({ - [Tags.SOPClassUID]: OPHTHALMIC_TOMOGRAPHY_SOP, - [Tags.Rows]: '2', - [Tags.Columns]: '2', - [Tags.NumberOfFrames]: '2', - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '0', - [Tags.PixelSpacing]: pixelSpacing, - [Tags.SpacingBetweenSlices]: '0.1', - }); - const image = allocateImageFromChunks([{ metadata } as unknown as Chunk]); + const metadata = datasetFromTags( + Object.entries({ + [Tags.SOPClassUID]: OPHTHALMIC_TOMOGRAPHY_SOP, + [Tags.Rows]: '2', + [Tags.Columns]: '2', + [Tags.NumberOfFrames]: '2', + [Tags.BitsStored]: '16', + [Tags.PixelRepresentation]: '0', + [Tags.PixelSpacing]: pixelSpacing, + [Tags.SpacingBetweenSlices]: '0.1', + }) + ); + const image = toVtkImageData(volumeOf([instanceFor(metadata)])); expect(image.getSpacing()).toEqual([1, 0.0104, 0.1]); const result = measureOccupiedDepth({ dimensions: image.getDimensions(), diff --git a/src/enface/__tests__/dicomMetadataFixture.ts b/src/enface/__tests__/dicomMetadataFixture.ts new file mode 100644 index 000000000..884472c26 --- /dev/null +++ b/src/enface/__tests__/dicomMetadataFixture.ts @@ -0,0 +1,45 @@ +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; +import { datasetFromTags } from '@/tests/dicomDataset'; + +const keyOf = (tag: string) => tag.replace('|', '').toUpperCase(); + +function nestedDatasets(dataset: DicomDataset): DicomDataset[] { + return dataset.elements.flatMap(({ values }) => + values.kind === 'sequence' ? values.items : [] + ); +} + +/** Change a fixture declaration wherever its functional groups supply it. */ +export function setDicomTag(dataset: DicomDataset, tag: string, value: string) { + const key = keyOf(tag); + let found = false; + const replace = (data: DicomDataset) => { + data.elements = data.elements.map((element) => { + if (element.tag !== key) return element; + found = true; + return datasetFromTags([[tag, value]]).elements[0]; + }); + nestedDatasets(data).forEach(replace); + }; + replace(dataset); + if (!found) + dataset.elements.push(datasetFromTags([[tag, value]]).elements[0]); +} + +export function removeDicomTag(dataset: DicomDataset, tag: string) { + const key = keyOf(tag); + dataset.elements = dataset.elements.filter((element) => element.tag !== key); + nestedDatasets(dataset).forEach((item) => removeDicomTag(item, tag)); +} + +export function setDicomSequence( + dataset: DicomDataset, + tag: string, + items: DicomDataset[] +) { + const element = datasetFromTags([[tag, '']]).elements[0]; + element.vr = 'SQ'; + element.values = { kind: 'sequence', items }; + removeDicomTag(dataset, tag); + dataset.elements.push(element); +} diff --git a/src/enface/__tests__/inputCalibration.spec.ts b/src/enface/__tests__/inputCalibration.spec.ts index 83d907b2a..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 '@/src/core/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'; @@ -15,11 +15,12 @@ import { useSegmentStore } from '@/src/segmentation/segments'; import { useSegmentationStore } from '@/src/segmentation/store'; import { allocateMask } from '@/src/segmentation/masks/storage'; import { measureOccupiedDepth } from '@/src/segmentation/measurements/occupiedDepth'; -import { createOCTFixture } from '@/tests/unit/octFixture'; +import { createOCTFixture, volumeOf } from '@/tests/unit/octFixture'; import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; import type { mat3 } from 'gl-matrix'; import type { Extent3D } from '@/src/segmentation/geometry'; +import { setDicomTag } from './dicomMetadataFixture'; beforeEach(() => setActivePinia(createPinia())); afterEach(() => { @@ -28,13 +29,10 @@ afterEach(() => { }); async function inputFor(pixelSpacing: string, oblique = false) { - const fixture = createOCTFixture(); - await fixture.chunk.loadMeta(); - fixture.chunk.metadata!.push([Tags.PixelSpacing, pixelSpacing]); - await fixture.image.addChunks([fixture.chunk]); - const cache = useImageCacheStore(); - const id = cache.addProgressiveImage(fixture.image); - fixture.image.startLoad(); + const fixture = await createOCTFixture(); + setDicomTag(fixture.instance.dataset, Tags.PixelSpacing, pixelSpacing); + fixture.image.setVolume(volumeOf([fixture.instance])); + const id = useImageCacheStore().addProgressiveImage(fixture.image); await untilLoaded(id); if (oblique) { const angle = (3 * Math.PI) / 180; diff --git a/src/enface/__tests__/occupiedDepthSupport.spec.ts b/src/enface/__tests__/occupiedDepthSupport.spec.ts index 6e58b8502..03f14cf33 100644 --- a/src/enface/__tests__/occupiedDepthSupport.spec.ts +++ b/src/enface/__tests__/occupiedDepthSupport.spec.ts @@ -1,18 +1,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; import { markRaw } from 'vue'; -import DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; import { useImageCacheStore } from '@/src/store/image-cache'; import { getOccupiedDepthSupport } from '@/src/enface/occupiedDepthSupport'; -import { createOCTFixture } from '@/tests/unit/octFixture'; +import { createOCTFixture, volumeOf } from '@/tests/unit/octFixture'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; import { untilLoaded } from '@/src/composables/untilLoaded'; -import { Tags } from '@/src/core/dicomTags'; -import { Chunk } from '@/src/core/streaming/chunk'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { datasetFromTags } from '@/tests/dicomDataset'; +import { + removeDicomTag, + setDicomSequence, + setDicomTag, +} from './dicomMetadataFixture'; describe('occupied-depth support for loaded volumes', () => { const pendingReads: (() => void)[] = []; - let emptyImage: DicomChunkImage | undefined; + let emptyImage: { dispose: () => void } | undefined; beforeEach(() => setActivePinia(createPinia())); afterEach(async () => { @@ -22,9 +26,10 @@ describe('occupied-depth support for loaded volumes', () => { emptyImage = undefined; }); - it('reports no measurement blocker while a cached DICOM image has no metadata chunks', () => { - emptyImage = new DicomChunkImage(); - useImageCacheStore().imageById.pending = markRaw(emptyImage); + it('reports no measurement blocker while a cached DICOM image has no volume yet', async () => { + const { image } = await createOCTFixture(); + emptyImage = image; + useImageCacheStore().imageById.pending = markRaw(image); expect(getOccupiedDepthSupport('pending')).toEqual({ reason: null, calibratedAxes: undefined, @@ -32,30 +37,28 @@ describe('occupied-depth support for loaded volumes', () => { }); it('defers metadata inspection until complete loading and reuses it for an unchanged grid', async () => { - const fixture = createOCTFixture({ deferDecode: true }); + const fixture = await createOCTFixture({ deferDecode: true }); pendingReads.push(fixture.releaseDecode); + fixture.image.setVolume(volumeOf([fixture.instance])); const id = useImageCacheStore().addProgressiveImage(fixture.image); - await fixture.chunk.loadMeta(); - await fixture.image.addChunks([fixture.chunk]); - const chunks = vi.spyOn(fixture.image, 'getChunks'); + const getInstances = vi.spyOn(fixture.image, 'getInstances'); expect(getOccupiedDepthSupport(id).calibratedAxes).toBeUndefined(); - expect(chunks).not.toHaveBeenCalled(); - fixture.image.startLoad(); + 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([ @@ -64,35 +67,23 @@ describe('occupied-depth support for loaded volumes', () => { ])( 'calibrates ultrasound with $regionCount regions without PixelSpacing: $calibrated', async ({ regionCount, calibrated }) => { - const fixture = createOCTFixture(); - await fixture.chunk.loadMeta(); - const metadata = fixture.chunk.metadata!.filter( - ([tag]) => ![Tags.Modality, Tags.PixelSpacing].includes(tag) + const fixture = await createOCTFixture(); + const { dataset } = fixture.instance; + removeDicomTag(dataset, Tags.PixelSpacing); + setDicomTag(dataset, Tags.Modality, 'US'); + 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) ); - metadata.push([Tags.Modality, 'US']); - const blob = fixture.chunk.metaBlob!; - const chunk = new Chunk({ - metaLoader: { - meta: metadata, - metaBlob: blob, - ultrasoundRegions: { - regionCount, - region: { - physicalUnitsXDirection: 3, - physicalUnitsYDirection: 3, - physicalDeltaX: 0.002, - physicalDeltaY: 0.00104, - }, - }, - load: () => {}, - stop: () => {}, - }, - dataLoader: { data: blob, load: () => {}, stop: () => {} }, - }); - fixture.chunk.dispose(); + fixture.image.setVolume(volumeOf([fixture.instance])); const id = useImageCacheStore().addProgressiveImage(fixture.image); - await fixture.image.addChunks([chunk]); - fixture.image.startLoad(); await untilLoaded(id); expect(fixture.image.getVtkImageData().getSpacing()[1]).toBeCloseTo( 0.0104, diff --git a/src/enface/__tests__/seriesGeometry.spec.ts b/src/enface/__tests__/seriesGeometry.spec.ts index 3753d594d..194ffc09c 100644 --- a/src/enface/__tests__/seriesGeometry.spec.ts +++ b/src/enface/__tests__/seriesGeometry.spec.ts @@ -1,63 +1,70 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import { Chunk } from '@/src/core/streaming/chunk'; -import { DicomFileMetaLoader } from '@/src/core/streaming/dicom/dicomFileMetaLoader'; -import { DicomFileDataLoader } from '@/src/core/streaming/dicom/dicomFileDataLoader'; -import { Tags } from '@/src/core/dicomTags'; +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 { createOCTFixture, readDicomTags } from '@/tests/unit/octFixture'; +import { + createOCTFixture, + readFixtureInstance, + volumeOf, +} from '@/tests/unit/octFixture'; 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 { - OCT_GEOMETRY_ERROR, - OCT_SCAN_PATTERN, -} from '@/src/core/streaming/dicom/octMetadataTags'; +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'; +import { + removeDicomTag, + setDicomTag, + setDicomSequence, +} from './dicomMetadataFixture'; -describe('assembled OCT series through real chunk and file collaborators', () => { +const displayMetadata = (instance: Instance) => + new Map(enFaceTags(instance.dataset)); + +describe('assembled OCT series through real header and file collaborators', () => { beforeEach(() => setActivePinia(createPinia())); afterEach(() => cleanupCachedImages([])); async function assemble( positions = [0, 0.2, 0.4], - change?: (chunks: Chunk[]) => void, + change?: (instances: Instance[]) => void, modality = 'OPT' ) { - const chunks = positions.map((z, index) => { - const bytes = buildSyntheticDicom({ - studyUid: '1.2.3.1', - seriesUid: '1.2.3.2', - sopUid: '1.2.3.3.' + index, - instanceNumber: index + 1, - modality, - imageOrientationPatient: [1, 0, 0, 0, 1, 0], - imagePositionPatient: [0, 0, z], - pixelSpacing: [0.0104, 0.02], - rows: 2, - cols: 2, - pixelValue: index + 1, - }); - const file = new File([Uint8Array.from(bytes)], 'oct-' + index + '.dcm'); - return new Chunk({ - metaLoader: new DicomFileMetaLoader(file, readDicomTags), - dataLoader: new DicomFileDataLoader(file), - }); - }); - await Promise.all(chunks.map((chunk) => chunk.loadMeta())); - change?.(chunks); - // Existing real-pixel fixture supplies a deterministic parser/decoder; only - // grouping is injected because production grouping needs a browser WASM worker. - const fixture = createOCTFixture(); - fixture.chunk.dispose(); - const id = useImageCacheStore().addProgressiveImage(fixture.image); - await fixture.image.addChunks(chunks); - fixture.image.startLoad(); + const instances = await Promise.all( + positions.map((z, index) => { + const bytes = buildSyntheticDicom({ + studyUid: '1.2.3.1', + seriesUid: '1.2.3.2', + sopUid: '1.2.3.3.' + index, + instanceNumber: index + 1, + modality, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, z], + pixelSpacing: [0.0104, 0.02], + rows: 2, + cols: 2, + pixelValue: index + 1, + }); + const file = new File( + [Uint8Array.from(bytes)], + 'oct-' + index + '.dcm' + ); + return readFixtureInstance(file); + }) + ); + 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(instances)); + const id = useImageCacheStore().addProgressiveImage(image); await untilLoaded(id); - return { id, image: fixture.image, chunks }; + return { id, image, instances }; } it('derives slow spacing from complete uniform positions when optional spacing is absent', async () => { @@ -122,9 +129,9 @@ describe('assembled OCT series through real chunk and file collaborators', () => }); it('uses uniform file positions when optional slice spacing disagrees', async () => { - const { id, image } = await assemble(undefined, (chunks) => { - chunks.forEach((chunk) => - chunk.metadata!.push([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); @@ -132,24 +139,22 @@ describe('assembled OCT series through real chunk and file collaborators', () => }); it('accepts orthogonal direction cosines rounded to four decimals', async () => { - const { id } = await assemble(undefined, (chunks) => { - chunks.forEach((chunk) => - chunk.metadata!.push([ + const { id } = await assemble(undefined, (instances) => { + instances.forEach((instance) => + setDicomTag( + instance.dataset, Tags.ImageOrientationPatient, - '0.9986\\0.0523\\0\\-0.0523\\0.9986\\0', - ]) + '0.9986\\0.0523\\0\\-0.0523\\0.9986\\0' + ) ); }); expect(getOccupiedDepthSupport(id).reason).toBeNull(); }); it('does not calibrate in-plane axes when every file omits pixel spacing', async () => { - const { id } = await assemble(undefined, (chunks) => { - chunks.forEach((chunk) => { - const index = chunk.metadata!.findIndex( - ([tag]) => tag === Tags.PixelSpacing - ); - chunk.metadata!.splice(index, 1); + const { id } = await assemble(undefined, (instances) => { + instances.forEach((instance) => { + removeDicomTag(instance.dataset, Tags.PixelSpacing); }); }); expect(getOccupiedDepthSupport(id).calibratedAxes).toEqual([ @@ -160,32 +165,52 @@ describe('assembled OCT series through real chunk and file collaborators', () => }); it.each([ - { positions: [0, 0.1, 0.4] }, - { positions: [0, 0.2, 0.4003, 0.6, 0.8] }, + { 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', - async ({ positions }) => { - const { id, image, chunks } = await assemble(positions); - expect(image.getVtkImageData().getSpacing()[2]).toBeCloseTo(0.2, 7); + async ({ positions, displayedSpacing }) => { + 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((chunk) => new Map(chunk.metadata!))) - .reason + dicomSeriesGeometry(instances.map(displayMetadata)).reason ).toMatch(/nonuniform/); } ); it.each([ - [Tags.OphthalmicVolumetricPropertiesFlag, 'NO', /unsuitable/], - [OCT_SCAN_PATTERN, '128282', /scan pattern/], - [OCT_GEOMETRY_ERROR, 'Later OCT spatial metadata is corrupt.', /corrupt/], - ])( - 'rejects an unsupported later acquisition declaration %s', - async (tag, value, reason) => { - const { id } = await assemble(undefined, (chunks) => - chunks[2].metadata!.push([tag, value]) - ); + ['nonvolumetric', /unsuitable/], + ['radial', /scan pattern/], + ['invalid orientation', /orientation.*invalid/], + ['incomplete frame geometry', /geometry.*Number of Frames/], + ] as const)( + 'rejects an unsupported later structured acquisition: %s', + async (kind, reason) => { + const { id } = await assemble(undefined, (instances) => { + const metadata = instances[2].dataset; + if (kind === 'nonvolumetric') + setDicomTag(metadata, Tags.OphthalmicVolumetricPropertiesFlag, 'NO'); + else if (kind === 'radial') + setDicomSequence(metadata, '00221618', [ + datasetFromTags([['00080100', '128282']]), + ]); + else if (kind === 'invalid orientation') + setDicomTag( + metadata, + Tags.ImageOrientationPatient, + '2\\0\\0\\0\\1\\0' + ); + else + setDicomSequence(metadata, '52009230', [ + datasetFromTags([]), + datasetFromTags([]), + ]); + }); expect(getEnFaceUnavailableReason(id)).toMatch(reason); } ); @@ -193,18 +218,16 @@ describe('assembled OCT series through real chunk and file collaborators', () => it.each([ [Tags.PixelSpacing, '0.02\\0.02', /pixel spacing/], [Tags.ImageOrientationPatient, '0\\1\\0\\1\\0\\0', /orientation/], - [Tags.ImageOrientationPatient, '2\\0\\0\\0\\1\\0', /orientation/], ])( 'keeps inconsistent %s geometry projection-only', async (tag, value, reason) => { - const { id, chunks } = await assemble(undefined, (pending) => - pending[2].metadata!.push([tag, value]) + 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((chunk) => new Map(chunk.metadata!))) - .reason + dicomSeriesGeometry(instances.map(displayMetadata)).reason ).toMatch(reason); } ); @@ -212,39 +235,32 @@ describe('assembled OCT series through real chunk and file collaborators', () => 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) => { - const index = chunk.metadata!.findIndex( - ([tag]) => tag === Tags.ImagePositionPatient - ); - chunk.metadata!.splice(index, 1); + selected.forEach((instance) => { + removeDicomTag(instance.dataset, Tags.ImagePositionPatient); }); }); expect(getEnFaceUnavailableReason(id)).toBeNull(); expect(getOccupiedDepthSupport(id).reason).toMatch(/incomplete/); expect( - dicomSeriesGeometry(chunks.map((chunk) => new Map(chunk.metadata!))) - .reason + 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((chunk) => new Map(chunk.metadata!)), - { - spacing: data.getSpacing(), - direction: data.getDirection(), - origin: data.getOrigin(), - } - ).reason + dicomSeriesGeometry(instances.map(displayMetadata), { + spacing: data.getSpacing(), + direction: data.getDirection(), + origin: data.getOrigin(), + }).reason ).toMatch(/loaded.*grid/); }); }); diff --git a/src/enface/__tests__/viewer.spec.ts b/src/enface/__tests__/viewer.spec.ts index 4952827ef..d50a2dce4 100644 --- a/src/enface/__tests__/viewer.spec.ts +++ b/src/enface/__tests__/viewer.spec.ts @@ -20,6 +20,7 @@ import { activateEnFace, createOCTFixture, loadOCT, + volumeOf, } from '@/tests/unit/octFixture'; import { cleanupCachedImages } from '@/tests/unit/imageCacheCleanup'; @@ -62,12 +63,10 @@ it('enables pane interactions only when their projection source supports them', scalarMax: 768, autoRangeValues: {}, }; - const fixture = createOCTFixture({ deferDecode: true }); + const fixture = await createOCTFixture({ deferDecode: true }); releases.push(fixture.releaseDecode); + fixture.image.setVolume(volumeOf([fixture.instance])); useImageCacheStore().addProgressiveImage(fixture.image, { id: 'oct' }); - await fixture.chunk.loadMeta(); - await fixture.image.addChunks([fixture.chunk]); - fixture.image.startLoad(); views.setDataForView(viewID, 'oct'); await nextTick(); expect(button()).toBe(-1); diff --git a/src/enface/availability.ts b/src/enface/availability.ts index 145fcdc23..4183eb753 100644 --- a/src/enface/availability.ts +++ b/src/enface/availability.ts @@ -1,9 +1,11 @@ +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 DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; import type { ProgressiveImage } from '@/src/core/progressiveImage'; -import { Tags } from '@/src/core/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import type { DicomDataset } from '@/src/dicom/core/metadata/dicomDataset'; import { OCT_GEOMETRY_ERROR, OCT_SCAN_PATTERN, @@ -44,17 +46,16 @@ function acquisitionMetadataReason(metadata: Iterable<[string, string]>) { return tags.get(OCT_GEOMETRY_ERROR) ?? null; } -// A chunk's tag list is fixed once loaded, so each is scanned at most once. -const metadataReasons = new WeakMap(); +// An instance's dataset never changes, so each is scanned at most once. +const datasetReasons = new WeakMap(); function acquisitionReason(image: ProgressiveImage) { - if (!(image instanceof DicomChunkImage)) return null; - for (const { metadata } of image.getChunks()) { - if (!metadata) continue; - let reason = metadataReasons.get(metadata); + if (!(image instanceof DicomVolumeImage)) return null; + for (const { dataset } of image.getInstances()) { + let reason = datasetReasons.get(dataset); if (reason === undefined) { - reason = acquisitionMetadataReason(metadata); - metadataReasons.set(metadata, reason); + reason = acquisitionMetadataReason(enFaceTags(dataset)); + datasetReasons.set(dataset, reason); } if (reason !== null) return reason; } @@ -64,7 +65,6 @@ function acquisitionReason(image: ProgressiveImage) { export function getEnFaceUnavailableReason(imageID: Maybe) { const cache = useImageCacheStore(); const image = cache.imageById[imageID || '']; - // Track allocation and progress even before raw DICOM chunks arrive. const loaded = Boolean(image?.isLoaded()); const loading = Boolean(image?.isLoading()); const data = cache.getVtkImageData(imageID); diff --git a/src/enface/occupiedDepthSupport.ts b/src/enface/occupiedDepthSupport.ts index abf0ee84c..203023223 100644 --- a/src/enface/occupiedDepthSupport.ts +++ b/src/enface/occupiedDepthSupport.ts @@ -1,21 +1,21 @@ +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 DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import type { Maybe } from '@/src/types'; -import { Tags } from '@/src/core/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { + readUltrasoundRegions, + unitToMm, +} from '@/src/dicom/core/metadata/ultrasoundRegion'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; import { dicomSeriesGeometry } from '@/src/core/streaming/dicom/seriesGeometry'; -import type { Chunk } from '@/src/core/streaming/chunk'; -import { unitToMm } from '@/src/core/streaming/dicom/ultrasoundRegion'; -function measurementMetadata(chunk: Chunk) { - const tags = new Map(chunk.metadata ?? []); - const regions = chunk.ultrasoundRegions; - if ( - tags.get(Tags.Modality)?.trim() !== 'US' || - !regions?.region || - regions.regionCount > 1 - ) - return tags; +function measurementMetadata(instance: Instance) { + const tags = new Map(enFaceTags(instance.dataset)); + 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); @@ -29,9 +29,9 @@ function measurementMetadata(chunk: Chunk) { return tags; } -function dicomSupport(image: DicomChunkImage, data: vtkImageData) { +function dicomSupport(image: DicomVolumeImage, data: vtkImageData) { const series = dicomSeriesGeometry( - image.getChunks().map(measurementMetadata), + image.getInstances().map(measurementMetadata), { spacing: data.getSpacing(), direction: data.getDirection(), @@ -57,7 +57,7 @@ export function getOccupiedDepthSupport(imageID: Maybe) { const image = cache.imageById[imageID || '']; const loaded = Boolean(image?.isLoaded()) && !image?.isLoading(); const data = cache.getVtkImageData(imageID); - if (!(image instanceof DicomChunkImage) || !loaded || !data) + if (!(image instanceof DicomVolumeImage) || !loaded || !data) return { reason: null, calibratedAxes: undefined }; const key = [ ...data.getSpacing(), diff --git a/src/io/dicom.ts b/src/io/dicom.ts index 5f8815509..b9f84f764 100644 --- a/src/io/dicom.ts +++ b/src/io/dicom.ts @@ -1,194 +1,10 @@ -import { runPipeline, TextStream, InterfaceTypes, Image } from 'itk-wasm'; - import { - readDicomTags, readOverlappingSegmentation, ReadOverlappingSegmentationResult, } from '@itk-wasm/dicom'; -import itkConfig from '@/src/io/itk/itkConfig'; import { getWorker } from '@/src/io/itk/worker'; -export interface TagSpec { - name: string; - tag: string; -} - -export type SpatialParameters = Pick< - Image, - 'size' | 'spacing' | 'origin' | 'direction' ->; - -// volume ID => file names -export type VolumesToFileNamesMap = Record; - -/** - * 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)); -} - -async function runTask( - module: string, - args: any[], - inputs: any[], - outputs: any[] -) { - const result = await runPipeline(module, args, outputs, inputs, { - webWorker: getWorker(), - pipelineBaseUrl: itkConfig.pipelinesUrl, - pipelineWorkerUrl: itkConfig.pipelineWorkerUrl, - }).catch((error) => { - throw new Error( - `itk-wasm pipeline "${module}" crashed (check browser console for details)`, - { cause: error } - ); - }); - if (result.returnValue !== 0) { - const detail = result.stderr?.trim() || 'unknown error'; - throw new Error( - `itk-wasm pipeline "${module}" exited with code ${result.returnValue}: ${detail}` - ); - } - return result; -} - -/** - * Split and sort DICOM files - * @async - * @returns volumeID => file names mapping - */ -export async function splitAndSort( - instances: T[], - mapToBlob: (inst: T, index: number) => Blob -) { - const inputs = await Promise.all( - instances.map(async (instance, index) => { - const blob = mapToBlob(instance, index); - const buffer = await blob.arrayBuffer(); - return { - type: InterfaceTypes.BinaryFile, - data: { - path: index.toString(), // make each file name unique - data: new Uint8Array(buffer), - }, - }; - }) - ); - - const args = [ - '--action', - 'categorize', - '--memory-io', - '0', - '--files', - ...inputs.map((fd) => fd.data.path), - ]; - - const outputs = [{ type: InterfaceTypes.TextStream }]; - - const result = await runTask('dicom', args, inputs, outputs); - - // File names are indexes into input files array - const volumeToFileIndexes = JSON.parse( - (result.outputs[0].data as TextStream).data - ) as VolumesToFileNamesMap; - - const volumeToInstances = Object.fromEntries( - Object.entries(volumeToFileIndexes).map(([volumeKey, fileIndexes]) => [ - volumeKey, - // file indexes to Files - fileIndexes.map((fileIndex) => instances[parseInt(fileIndex, 10)]), - ]) - ); - - return volumeToInstances; -} - -/** - * Reads a list of tags out from a given file. - * - * @param {File} file - * @param {[]Tag} tags - */ -export async function readTags( - file: File, - tags: T -): Promise> { - const tagsArgs = { tagsToRead: { tags: tags.map(({ tag }) => tag) } }; - - const result = await readDicomTags(sanitizeFile(file), { - ...tagsArgs, - webWorker: getWorker(), - }); - const tagValues = new Map(result.tags); - - return tags.reduce( - (info, t) => { - const { tag, name } = t; - if (tagValues.has(tag)) { - return { ...info, [name]: tagValues.get(tag) }; - } - return info; - }, - {} as Record - ); -} - -/** - * Retrieves a slice of a volume. - * @async - * @param {File} file containing the slice - * @param {Boolean} asThumbnail cast image to unsigned char. Defaults to false. - * @returns ItkImage - */ -export async function readVolumeSlice( - file: File, - asThumbnail: boolean = false -) { - const buffer = await file.arrayBuffer(); - - const inputs = [ - { - type: InterfaceTypes.BinaryFile, - data: { - path: sanitizeFileName(file.name), - data: new Uint8Array(buffer), - }, - }, - ]; - - const args = [ - '--action', - 'getSliceImage', - '--thumbnail', - asThumbnail.toString(), - '--file', - sanitizeFileName(file.name), - '--memory-io', - '0', - ]; - - const outputs = [{ type: InterfaceTypes.Image }]; - - const result = await runTask('dicom', args, inputs, outputs); - - return result.outputs[0].data as Image; -} - type DicomSegmentAttributes = { SegmentLabel: string; labelID: number; @@ -205,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__/dataSource.spec.ts b/src/io/import/__tests__/dataSource.spec.ts index d594a15b9..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 { Chunk } from '@/src/core/streaming/chunk'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; describe('isRemoteDatasource', () => { it('should work', () => { @@ -65,17 +65,15 @@ describe('getDataSourceName', () => { expect( getDataSourceName({ - type: 'chunk', - chunk: {} as Chunk, - mime: 'mime', + type: 'dicom', + instance: {} as Instance, }) ).to.equal(null); expect( getDataSourceName({ - type: 'chunk', - chunk: {} as Chunk, - mime: 'mime', + type: 'dicom', + instance: {} as Instance, parent: { type: 'file', file: new File([], 'name'), diff --git a/src/io/import/__tests__/importDicomInstanceSources.spec.ts b/src/io/import/__tests__/importDicomInstanceSources.spec.ts new file mode 100644 index 000000000..27f8b6868 --- /dev/null +++ b/src/io/import/__tests__/importDicomInstanceSources.spec.ts @@ -0,0 +1,242 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; +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 { + acquisition, + 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 loadSources = (sources: DicomInstanceSource[]) => { + const { createImage } = imageFactory(); + 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 }) => [ + 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 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. + 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) + ); + }); + + it('binds both saved volumes to the one they now restore as', () => { + // 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({ + '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 b16dab9f1..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,12 +60,25 @@ 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), [], { '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( @@ -73,6 +87,24 @@ describe('restore with a partially missing dataset archive', () => { expect(warning?.options.details).toContain('b.dcm'); }); + it('names a dataset whose files now load as several volumes as split, not missing', async () => { + await completeStateFileRestore( + ManifestSchema.parse(manifest), + [], + {}, + { splitDatasets: { 'ds-ct': ['store-acq1', 'store-acq2'] } } + ); + + 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 2 volumes' + ); + expect(warning?.options.details).toContain('not restored'); + 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/__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 f480ffa19..b1d0203ee 100644 --- a/src/io/import/__tests__/restoreStateFileLeaves.spec.ts +++ b/src/io/import/__tests__/restoreStateFileLeaves.spec.ts @@ -1,8 +1,21 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +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 { leafStateId } from '@/src/io/import/dataSource'; -import type { StateFileSetupResult } from '@/src/io/import/common'; +import { buildStateIDToStoreID } from '@/src/io/import/importDataSources'; +import { + asLoadableResult, + type ImportContext, + type IntermediateResult, + 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'; // --------------------------------------------------------------------------- @@ -93,3 +106,125 @@ describe('prepareLeafDataSources: composed-manifest artifacts', () => { expect(leaves.some((leaf) => leaf.uri === BASE_URI)).toBe(true); }); }); + +/** 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([ + ['nested', 'series-a/slice.dcm', 'series-b/slice.dcm'], + ['flat', 'a.dcm', 'b.dcm'], + ['root-relative', '/a.dcm', '/b.dcm'], + ])( + 'restores each dataset from its recorded %s member of a shared archive', + async (_kind, pathA, pathB) => { + const inner = new JSZip(); + inner.file(pathA.replace(/^\/+/, ''), 'series A'); + inner.file(pathB.replace(/^\/+/, ''), 'series B'); + const manifest = { + version: MANIFEST_VERSION, + dataSources: [ + { id: 1, type: 'file', fileId: 10, fileType: 'application/zip' }, + { id: 2, type: 'archive', parent: 1, path: pathA }, + { id: 3, type: 'archive', parent: 1, path: pathB }, + ], + datasetFilePath: { '10': 'data/series.zip' }, + datasets: [ + { id: 'saved-a', dataSourceId: 2 }, + { id: 'saved-b', dataSourceId: 3 }, + ], + }; + const outer = new JSZip(); + outer.file('manifest.json', JSON.stringify(manifest)); + outer.file( + 'data/series.zip', + await inner.generateAsync({ type: 'blob' }) + ); + const file = new File( + [await outer.generateAsync({ type: 'blob' })], + 'session.volview.zip' + ); + const setup = (await restoreStateFile({ + type: 'file', + file, + fileType: 'application/zip', + })) as StateFileSetupResult; + const loadables = await Promise.all( + setup.dataSources.map(async (source, index) => { + const member = await extractedMember(source); + expect(await member.file.text()).toBe( + index === 0 ? 'series A' : 'series B' + ); + expect(findStateFileLeaves(member)).toEqual([ + { stateID: index === 0 ? 'saved-a' : 'saved-b' }, + ]); + return asLoadableResult('loaded-' + index, member, 'image'); + }) + ); + expect(buildStateIDToStoreID(loadables)).toEqual({ + 'saved-a': 'loaded-0', + 'saved-b': 'loaded-1', + }); + } + ); +}); + +it('downloads a saved source archive once and reuses extracted members', async () => { + const zip = new JSZip(); + zip.file('a.dcm', 'A'); + zip.file('b.dcm', 'B'); + const bytes = await zip.generateAsync({ type: 'uint8array' }); + const request = vi.spyOn(globalThis, 'fetch').mockImplementation( + async () => + new Response(new Uint8Array(bytes), { + headers: { 'content-type': 'application/zip' }, + }) + ); + const context: ImportContext = { + fetchFileCache: new Map(), + archiveCache: new Map(), + }; + try { + const opened = await Promise.all( + ['a', 'b'].map((name) => + openUriStream( + { + type: 'uri', + uri: 'https://example.test/series.zip', + name: 'series.zip', + mime: 'application/zip', + stateFileLeaf: { stateID: name, archivePaths: [name + '.dcm'] }, + }, + context + ) + ) + ); + const sources = opened.map( + (result) => (result as IntermediateResult).dataSources[0] + ); + expect(request).toHaveBeenCalledOnce(); + if (sources[0].type !== 'file' || sources[1].type !== 'file') + throw new Error('Expected archive files'); + expect(sources[0].file).toBe(sources[1].file); + 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.file).toBe(a.file); + expect(findStateFileLeaves(a)).toEqual([{ stateID: 'a' }]); + expect(findStateFileLeaves(b)).toEqual([{ stateID: 'b' }]); + } finally { + request.mockRestore(); + } +}); diff --git a/src/io/import/__tests__/stateFileLeaves.spec.ts b/src/io/import/__tests__/stateFileLeaves.spec.ts index f33221ee7..883a21203 100644 --- a/src/io/import/__tests__/stateFileLeaves.spec.ts +++ b/src/io/import/__tests__/stateFileLeaves.spec.ts @@ -4,8 +4,11 @@ import { findStateFileLeaves, type DataSource, } from '@/src/io/import/dataSource'; -import { buildStateIDToStoreID } from '@/src/io/import/importDataSources'; -import type { LoadableResult } from '@/src/io/import/common'; +import { + buildStateIDToStoreID, + findSplitStateDatasets, +} from '@/src/io/import/importDataSources'; +import { asLoadableResult, type LoadableResult } from '@/src/io/import/common'; // --------------------------------------------------------------------------- // Multi-file DICOM ephemeral open: the backend's @@ -24,18 +27,20 @@ const uriLeaf = (uri: string, stateID: string): DataSource => ({ stateFileLeaf: { stateID }, }); -// A merged DICOM volume's dataSource: a fresh collection over the chunk -// sources, each chunk parented by its own per-file uri leaf. +// A merged DICOM volume's dataSource: a fresh collection over the instance +// sources, each instance parented by its own per-file uri leaf. const mergedDicomSource = (stateIDs: string[]): DataSource => ({ type: 'collection', sources: stateIDs.map((stateID, i) => ({ - type: 'chunk', - chunk: {} as never, - mime: 'application/dicom', + type: 'dicom', + instance: {} as never, parent: uriLeaf(`https://girder.example/file/${i}`, stateID), })), }); +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 = { @@ -78,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', @@ -104,4 +104,32 @@ describe('buildStateIDToStoreID', () => { 'leaf:4': 'store-seg', }); }); + + it('leaves a dataset unmapped when its leaves load as several volumes', () => { + // A series saved as one dataset that a later build splits into several + // 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 = [ + loadedDicom('store-acq1', ['ds-split', 'ds-split']), + loadedDicom('store-acq2', ['ds-split']), + loadedDicom('store-whole', ['ds-whole']), + ]; + + expect(buildStateIDToStoreID(loadables)).toEqual({ + 'ds-whole': 'store-whole', + }); + }); + + it('names the volumes a split dataset now loads as', () => { + const loadables = [ + loadedDicom('store-acq1', ['ds-split']), + loadedDicom('store-acq2', ['ds-split']), + loadedDicom('store-whole', ['ds-whole']), + ]; + + expect(findSplitStateDatasets(loadables)).toEqual({ + 'ds-split': ['store-acq1', 'store-acq2'], + }); + }); }); diff --git a/src/io/import/dataSource.ts b/src/io/import/dataSource.ts index 8f4c3d29b..db43b4896 100644 --- a/src/io/import/dataSource.ts +++ b/src/io/import/dataSource.ts @@ -1,5 +1,5 @@ -import { Chunk } from '@/src/core/streaming/chunk'; -import { Fetcher } from '@/src/core/streaming/types'; +import type { Instance } from '@/src/dicom/core/instance/readInstance'; +import type { Fetcher } from '@/src/core/streaming/types'; import { Maybe } from '@/src/types'; /** @@ -43,12 +43,11 @@ export type CollectionSource = { }; /** - * Represents a data chunk for further processing and import. + * A DICOM instance whose header was read, waiting to be planned into volumes. */ -export type ChunkSource = { - type: 'chunk'; - chunk: Chunk; - mime: string; +export type DicomInstanceSource = { + type: 'dicom'; + instance: Instance; }; /** @@ -56,6 +55,8 @@ export type ChunkSource = { */ export type StateFileLeaf = { stateID: string; + /** Archive members to select in order, from the outermost archive inwards. */ + archivePaths?: string[]; }; /** @@ -76,7 +77,13 @@ export const leafStateId = (dataSourceId: number): string => export type DataSource = { parent?: DataSource; stateFileLeaf?: StateFileLeaf; -} & (FileSource | UriSource | ArchiveSource | ChunkSource | CollectionSource); +} & ( + | FileSource + | UriSource + | ArchiveSource + | DicomInstanceSource + | CollectionSource +); /** * Every state-file leaf a data source covers, provenance-first. diff --git a/src/io/import/importDataSources.ts b/src/io/import/importDataSources.ts index b3936c94b..0c5523a23 100644 --- a/src/io/import/importDataSources.ts +++ b/src/io/import/importDataSources.ts @@ -1,6 +1,6 @@ import { - ImportContext, ImportHandler, + type ImportContext, ImportResult, asErrorResult, asLoadableResult, @@ -15,13 +15,12 @@ import { } from '@/src/io/import/common'; import { DataSource, - ChunkSource, + DicomInstanceSource, findStateFileLeaves, getDataSourceName, } from '@/src/io/import/dataSource'; -import handleDicomFile from '@/src/io/import/processors/handleDicomFile'; +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'; @@ -39,14 +38,16 @@ import { import updateUriType from '@/src/io/import/processors/updateUriType'; import openUriStream from '@/src/io/import/processors/openUriStream'; import downloadStream from '@/src/io/import/processors/downloadStream'; -import handleDicomStream from '@/src/io/import/processors/handleDicomStream'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { asyncSelect } from '@/src/utils/asyncSelect'; import { evaluateChain, Skip } from '@/src/utils/evaluateChain'; -import { ensureError, partition } from '@/src/utils'; -import { Chunk } from '@/src/core/streaming/chunk'; +import { ensureError } from '@/src/utils'; +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 } from '@/src/store/datasets-dicom'; +import { + useDICOMStore, + type ImportInstancesDeps, +} from '@/src/store/datasets-dicom'; import { useMessageStore } from '@/src/store/messages'; import { shouldSkipImportSource } from '@/src/io/import/shouldSkipImportSource'; @@ -82,44 +83,143 @@ const applyConfigsPostState = ( } }); +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]; + } + return a.length - b.length; +}; + // 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. +// 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 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 stateIDToStoreID: Record = {}; - loadables.forEach((loadable) => { - findStateFileLeaves(loadable.dataSource).forEach((leaf) => { - stateIDToStoreID[leaf.stateID] = loadable.dataID; - }); - }); - return stateIDToStoreID; + return Object.fromEntries( + [...storeIDsByStateID(loadables)] + .filter(([, storeIDs]) => storeIDs.size === 1) + .map(([stateID, storeIDs]) => [stateID, [...storeIDs][0]]) + ); } -async function importDicomChunkSources(sources: ChunkSource[]) { - if (sources.length === 0) return []; - - const volumeChunks = await useDICOMStore().importChunks( - sources.map((src) => src.chunk) +/** + * The state-file datasets the map above leaves out because their leaves now + * load as several volumes, with those volumes. The restore names them as + * split rather than as missing: every one of them is on screen. + */ +export function findSplitStateDatasets( + loadables: readonly LoadableResult[] +): Record { + return Object.fromEntries( + [...storeIDsByStateID(loadables)] + .filter(([, storeIDs]) => storeIDs.size > 1) + .map(([stateID, storeIDs]) => [stateID, [...storeIDs]]) ); +} - // this is used to reconstruct the ChunkSource list - const chunkToDataSource = new Map(); - sources.forEach((src) => { - chunkToDataSource.set(src.chunk, src); - }); +const stateLeavesOf = (loadables: readonly LoadableResult[]) => + loadables.flatMap((loadable) => + findStateFileLeaves(loadable.dataSource).map( + (leaf) => [leaf.stateID, loadable.dataID] as const + ) + ); - return Object.entries(volumeChunks).map(([id, chunks]) => - asLoadableResult( - id, - { - type: 'collection', - sources: chunks.map((chunk) => chunkToDataSource.get(chunk)!), - }, - 'image' +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. +const instanceToDataSource = new WeakMap(); + +const sourcesOf = (instances: Instance[]) => + instances + .map((instance) => instanceToDataSource.get(instance)) + .filter((src): src is DicomInstanceSource => src !== undefined); + +/** What the import needs of its caller: how to remove a dissolved dataset. */ +type ImportInstancesHooks = Required< + Pick +>; + +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 { loadables: [], failures: [] }; + + sources.forEach((src) => instanceToDataSource.set(src.instance, src)); + + const supplied = new Set(sources); + const datasetStore = useDatasetStore(); + // The dataset store's removal clears every store that names a dissolved + // dataset, in the order eviction needs. + 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 + ) + .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), + })), + }; +} + +/** Only the sources of a series that failed are blamed for its failure. */ +function importDicomResults( + sources: DicomInstanceSource[] +): ImportDataSourcesResult[] { + 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'; @@ -144,24 +244,29 @@ async function processImportQueue( handlers: ImportHandler[], importContext: ImportContext ) { - const chunkSources: DataSource[] = []; + const instanceSources: Array<{ + source: DicomInstanceSource; + order: number[]; + }> = []; const configResults: ConfigResult[] = []; const stateFileSetups: StateFileSetupResult[] = []; const results: ImportDataSourcesResult[] = []; + const queuedSource = (src: DataSource, order: number[]) => ({ + promise: evaluateChain(src, handlers, importContext), + source: src, + order, + }); const enqueue = (sources: DataSource[]) => sources .filter((src) => !shouldSkipImportSource(src)) - .map((src) => ({ - promise: evaluateChain(src, handlers, importContext), - source: src, - })); + .map((src, index) => queuedSource(src, [index])); let queue = enqueue(dataSources); while (queue.length) { const { index } = await asyncSelect(queue.map((item) => item.promise)); - const { promise, source } = queue[index]; + const { promise, source, order } = queue[index]; const result = await promise.catch((err) => asErrorResult(err, source)); queue = queue.filter((_, i) => i !== index); @@ -170,13 +275,13 @@ async function processImportQueue( stateFileSetups.push(result); // fallthrough to handle dataSources case 'intermediate': { - const [chunks, otherSources] = partition( - (ds) => ds.type === 'chunk', - result.dataSources - ); - chunkSources.push(...chunks); - - queue.push(...enqueue(otherSources)); + result.dataSources.forEach((src, childIndex) => { + if (shouldSkipImportSource(src)) return; + const childOrder = [...order, childIndex]; + if (src.type === 'dicom') + instanceSources.push({ source: src, order: childOrder }); + else queue.push(queuedSource(src, childOrder)); + }); break; } case 'config': @@ -197,7 +302,7 @@ async function processImportQueue( } } - return { chunkSources, configResults, stateFileSetups, results }; + return { instanceSources, configResults, stateFileSetups, results }; } async function importDataSourcesWithPolicy( @@ -213,8 +318,9 @@ async function importDataSourcesWithPolicy( while (cleanupHandlers.length) cleanupHandlers.pop()!(); }; - const importContext = { - fetchFileCache: new Map(), + const importContext: ImportContext = { + fetchFileCache: new Map(), + archiveCache: new Map(), onCleanup, importDataSources: (sources: DataSource[]) => importDataSourcesWithPolicy(sources, policy, restore), @@ -240,44 +346,40 @@ async function importDataSourcesWithPolicy( handleAmazonS3, // stream handling - handleDicomStream, + // before downloadStream and extractArchive: a DICOM source reads its own + // header, whether it is a file or a uri + handleDicom, downloadStream, extractArchive, - extractArchiveTarget, - // should be before importSingleFile, since DICOM is more specific - handleDicomFile, // collect DICOM files to import later importSingleFile, // catch any unhandled resource unhandledResource, ]; - const { chunkSources, configResults, stateFileSetups, results } = + const { instanceSources, configResults, stateFileSetups, results } = await processImportQueue(dataSources, handlers, importContext); cleanup(); - const dicomChunkSources = chunkSources.filter( - (src): src is ChunkSource => - src.type === 'chunk' && src.mime === FILE_EXT_TO_MIME.dcm - ); + const dicomInstanceSources = instanceSources + .sort((a, b) => compareSourceOrder(a.order, b.order)) + .map(({ source }) => source); - try { - const dicomResults = await importDicomChunkSources(dicomChunkSources); - results.push(...dicomResults); - } catch (err) { - const errorSource = - dicomChunkSources.length === 1 - ? dicomChunkSources[0] - : ({ type: 'collection', sources: dicomChunkSources } as DataSource); - results.push(asErrorResult(ensureError(err), errorSource)); - } + const dicomResults = importDicomResults(dicomInstanceSources); + results.push(...dicomResults); const loadableResults = results.filter( (r): r is LoadableResult => r.type === 'data' ); - useDatasetStore().addDataSources(loadableResults); + // A DICOM dataset was published with its series commit, so adding it + // again here would restore the membership that import saw rather than the + // membership the series now holds. + const published = new Set(dicomResults); + useDatasetStore().addDataSources( + loadableResults.filter((result) => !published.has(result)) + ); // Failed leaves (e.g. a 404'd uri member of a multi-leaf dataset) feed the // restore's consolidated notice: a dataset that still resolves from its @@ -292,6 +394,7 @@ async function importDataSourcesWithPolicy( ); const stateIDToStoreID = buildStateIDToStoreID(loadableResults); + const splitDatasets = findSplitStateDatasets(loadableResults); // Leaf stateIDs covered by a consolidated notice that actually ran — only // their errors may be suppressed below. const reportedStateIDs = new Set(); @@ -301,8 +404,11 @@ async function importDataSourcesWithPolicy( setup.manifest, setup.stateFiles, stateIDToStoreID, - setup.missingFiles, - failedLeaves + { + 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 new file mode 100644 index 000000000..36aeb1093 --- /dev/null +++ b/src/io/import/processors/__tests__/handleDicom.spec.ts @@ -0,0 +1,259 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; + +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'; +import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; +import { Skip } from '@/src/utils/evaluateChain'; +import { useMessageStore } from '@/src/store/messages'; +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'; + +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. */ +const bytesFetcher = (bytes: Uint8Array) => { + let abortController: AbortController | null = null; + + const fetcher: Fetcher = { + connect: async () => { + abortController ??= new AbortController(); + }, + getStream: () => { + let done = false; + return new ReadableStream({ + pull: (controller) => { + if (done) { + controller.close(); + return; + } + done = true; + controller.enqueue(bytes); + }, + }); + }, + blob: async () => + new Blob([bytes as BlobPart], { type: FILE_EXT_TO_MIME.dcm }), + close: () => { + abortController?.abort(StopSignal); + }, + get connected() { + return !!abortController; + }, + contentType: FILE_EXT_TO_MIME.dcm, + }; + return fetcher; +}; + +const REGION = { physicalDeltaX: 0.0625, physicalDeltaY: 0.125 }; + +const fileSource = (bytes: Uint8Array, name = 'slice.dcm'): DataSource => + fileToDataSource(dicomFile(bytes, name)); + +const uriSource = (bytes: Uint8Array, name = 'slice.dcm'): DataSource => ({ + type: 'uri', + uri: `https://example.com/${name}`, + name, + mime: FILE_EXT_TO_MIME.dcm, + fetcher: bytesFetcher(bytes), +}); + +const kinds = [ + { kind: 'file', source: fileSource }, + { kind: 'uri', source: uriSource }, +] as const; + +const instanceOf = (result: unknown) => { + const intermediate = result as { type: string; dataSources: DataSource[] }; + expect(intermediate.type).toBe('intermediate'); + expect(intermediate.dataSources).toHaveLength(1); + const [source] = intermediate.dataSources; + if (source.type !== 'dicom') throw new Error('expected a DICOM source'); + return source; +}; + +// Synthetic slices carry no private elements, so the instance keeps them all. +const headerOf = readDicomDataset; + +describe('handleDicom', () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it.each(kinds)('emits an instance for a $kind source', async ({ source }) => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN' }); + + const { instance } = instanceOf(await handleDicom(source(bytes))); + + expect(instance.dataset).toEqual(headerOf(bytes)); + }); + + it.each(kinds)( + 'reads a $kind source that has no preamble without comment', + async ({ source }) => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN' }); + + const { instance } = instanceOf( + await handleDicom(source(stripPreamble(bytes), 'bare.dcm')) + ); + + expect(instance.dataset).toEqual(headerOf(bytes)); + expect(useMessageStore().messages).toHaveLength(0); + } + ); + + it('reads a bare data set and says once that its syntax was assumed', async () => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN' }); + const bare = stripFileMeta(bytes); + + const first = instanceOf(await handleDicom(fileSource(bare, 'first.dcm'))); + const second = instanceOf( + await handleDicom(fileSource(bare, 'second.dcm')) + ); + + expect(first.instance.dataset).toEqual(headerOf(bytes)); + expect(second.instance.dataset).toEqual(headerOf(bytes)); + const { messages } = useMessageStore(); + expect(messages).toHaveLength(1); + expect(messages[0].title).toContain('no file meta information'); + expect(messages[0].options.details).toContain('first.dcm'); + expect(messages[0].options.details).toContain('Explicit VR Little Endian'); + }); + + it('reads the same metadata from a file and from a uri', async () => { + const bytes = syntheticSlice({ patientName: 'DOE^JOHN', modality: 'CT' }); + + const fromFile = instanceOf(await handleDicom(fileSource(bytes))); + const fromUri = instanceOf(await handleDicom(uriSource(bytes))); + + expect(fromFile.instance.dataset).toEqual(fromUri.instance.dataset); + expect(fromUri.parent).not.toHaveProperty('fetcher'); + }); + + it.each(kinds)( + 'reads every byte of the $kind source back from its instance', + async ({ source }) => { + const bytes = syntheticSlice(); + // A uri instance fetches its bytes again rather than keeping them. + vi.stubGlobal('fetch', async () => new Response(bytes as BlobPart)); + + const { instance } = instanceOf(await handleDicom(source(bytes))); + const read = await readBytes( + instance.source, + new AbortController().signal + ); + + expect(read).toEqual(bytes); + } + ); + + it.each(kinds)( + 'carries ultrasound regions on a $kind source', + async ({ source }) => { + const bytes = syntheticSlice({ + modality: 'US', + ultrasoundRegion: REGION, + }); + + const { instance } = instanceOf(await handleDicom(source(bytes))); + + const regions = readUltrasoundRegions(instance.dataset); + expect(regions.regionCount).toBe(1); + expect(regions.region?.physicalDeltaX).toBeCloseTo(REGION.physicalDeltaX); + expect(regions.region?.physicalDeltaY).toBeCloseTo(REGION.physicalDeltaY); + } + ); + + it.each(kinds)( + 'skips an RT modality on a $kind source and warns', + async ({ source, kind }) => { + const name = `rt-${kind}.dcm`; + const bytes = withoutPixelData(syntheticSlice({ modality: 'RTSTRUCT' })); + + const result = await handleDicom(source(bytes, name)); + + expect(result).toEqual({ + type: 'ok', + dataSource: expect.objectContaining({ type: kind }), + }); + const [warning] = useMessageStore().messages; + expect(warning.title).toContain('RTSTRUCT'); + expect(warning.title).toContain(name); + } + ); + + 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' }); + + const { instance } = instanceOf(await handleDicom(fileSource(bytes))); + + expect(getDatasetTag(instance.dataset, Tags.Modality)).toBe('RG'); + expect(useMessageStore().messages).toHaveLength(0); + }); + + it('skips a file source that is not DICOM', async () => { + const source: DataSource = { + type: 'file', + file: new File([new Uint8Array(4)], 'volume.nrrd', { + type: FILE_EXT_TO_MIME.nrrd, + }), + fileType: FILE_EXT_TO_MIME.nrrd, + }; + + expect(await handleDicom(source)).toBe(Skip); + }); + + it('skips a uri source that is not DICOM', async () => { + const source: DataSource = { + type: 'uri', + uri: 'https://example.com/volume.nrrd', + name: 'volume.nrrd', + mime: FILE_EXT_TO_MIME.nrrd, + }; + + expect(await handleDicom(source)).toBe(Skip); + }); + + it.each(kinds)( + 'names the $kind source when its bytes are not DICOM', + async ({ source }) => { + const broken = source(new Uint8Array(512), 'broken.dcm'); + + await expect(handleDicom(broken)).rejects.toThrow(/broken\.dcm/); + } + ); +}); diff --git a/src/io/import/processors/extractArchive.ts b/src/io/import/processors/extractArchive.ts index 44f306f95..eb8b5b033 100644 --- a/src/io/import/processors/extractArchive.ts +++ b/src/io/import/processors/extractArchive.ts @@ -1,27 +1,60 @@ import { extractFilesFromZip } from '@/src/io/zip'; import { ImportHandler, + type ArchiveCache, asIntermediateResult, isArchive, } from '@/src/io/import/common'; import { Skip } from '@/src/utils/evaluateChain'; -import { DataSource } from '@/src/io/import/dataSource'; +import { DataSource, findStateFileLeaves } from '@/src/io/import/dataSource'; + +const readArchive = (file: File, cache?: ArchiveCache) => { + const cached = cache?.get(file); + if (cached) return cached; + const pending = extractFilesFromZip(file).then((entries) => + Object.fromEntries( + entries.map((entry) => [ + entry.archivePath.replace(/^\/+/, ''), + entry.file, + ]) + ) + ); + cache?.set(file, pending); + return pending; +}; /** * Extracts all files from an archive. * @param dataSource */ -const extractArchive: ImportHandler = async (dataSource) => { +const extractArchive: ImportHandler = async (dataSource, context) => { if (isArchive(dataSource)) { - const files = await extractFilesFromZip(dataSource.file); - const newSources = files.map((entry): DataSource => { + const leaf = findStateFileLeaves(dataSource)[0]; + const [target, ...remaining] = leaf?.archivePaths ?? []; + const contents = await readArchive(dataSource.file, context?.archiveCache); + const entries = target + ? ([[target, contents[target.replace(/^\/+/, '')]]] as const) + : Object.entries(contents); + const newSources = entries.map(([archivePath, file]): DataSource => { + if (!file) + throw new Error( + 'File ' + archivePath + ' does not exist in the zip file' + ); return { type: 'file', - file: entry.file, + file, fileType: '', + ...(leaf + ? { + stateFileLeaf: { + stateID: leaf.stateID, + ...(remaining.length ? { archivePaths: remaining } : {}), + }, + } + : {}), parent: { type: 'archive', - path: entry.archivePath, + path: archivePath, parent: dataSource, }, }; 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/import/processors/handleDicom.ts b/src/io/import/processors/handleDicom.ts new file mode 100644 index 000000000..55513e218 --- /dev/null +++ b/src/io/import/processors/handleDicom.ts @@ -0,0 +1,128 @@ +import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; +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, +} 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 { + ImportHandler, + asIntermediateResult, + asOkayResult, +} from '@/src/io/import/common'; +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 { Maybe } from '@/src/types'; + +// 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. +const noticed = new WeakMap>(); + +const noticeOnce = (key: string, title: string, details: string) => { + const store = useMessageStore(); + const seen = noticed.get(store) ?? new Set(); + noticed.set(store, seen); + if (seen.has(key)) return; + seen.add(key); + surfaceWarning(title, details); +}; + +/** + * A data set with no file meta information names no transfer syntax, so the + * one it was read in is an assumption the user should hear about. + */ +const reportLayout = (name: Maybe, layout: Maybe) => { + if (!layout || layout.fileMeta) return; + const syntax = + layout.transferSyntaxUid === IMPLICIT_VR_LITTLE_ENDIAN + ? 'Implicit' + : 'Explicit'; + noticeOnce( + `assumed-syntax:${syntax}`, + 'A DICOM file has no file meta information', + `${name ?? 'A file'} has no preamble and no file meta information, so it was read ` + + `as ${syntax} VR Little Endian. Other files that open the same way ` + + 'were read the same way without further notice.' + ); +}; + +const isDicom = (dataSource: DataSource) => + (dataSource.type === 'file' && + dataSource.fileType === FILE_EXT_TO_MIME.dcm) || + (dataSource.type === 'uri' && dataSource.mime === FILE_EXT_TO_MIME.dcm); + +// A remote header is read from the stream already opened to sniff its type; +// pixels are fetched again later, so that stream closes after the header. +async function readHeader(dataSource: DataSource, runtime: DicomRuntime) { + const never = new AbortController().signal; + if (dataSource.type === 'file') + return runtime.readInstance(fromBlob(dataSource.file), never); + if (dataSource.type !== 'uri') throw new Error('Not a DICOM source'); + const source = fromUrl(dataSource.uri, { fetch: runtime.fetch }); + const { fetcher } = dataSource; + if (!fetcher) return runtime.readInstance(source, never); + try { + const header = await runtime.readInstance( + { read: () => fetcher.getStream() }, + never + ); + return Object.freeze({ ...header, source }); + } finally { + fetcher.close(); + } +} + +/** + * 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; + + const name = getDataSourceName(dataSource); + const { runtime } = useDicomRuntimeStore(); + + 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)' + ); + throw new Error(`Failed to read DICOM tags from ${name}: ${detail}`, { + cause: error, + }); + }); + reportLayout(name, instance.layout); + + const skipped = whySkipped(instance.dataset, name); + if (skipped) { + useMessageStore().addWarning(skipped); + return asOkayResult(dataSource); + } + + // Provenance only needs the URI or file; the instance reads its own bytes. + const parent = { ...dataSource }; + if (parent.type === 'uri') delete parent.fetcher; + + return asIntermediateResult([{ type: 'dicom', instance, parent }]); +}; + +export default handleDicom; diff --git a/src/io/import/processors/handleDicomFile.ts b/src/io/import/processors/handleDicomFile.ts deleted file mode 100644 index a1e74beb1..000000000 --- a/src/io/import/processors/handleDicomFile.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Skip } from '@/src/utils/evaluateChain'; -import { Chunk } from '@/src/core/streaming/chunk'; -import { DicomFileDataLoader } from '@/src/core/streaming/dicom/dicomFileDataLoader'; -import { DicomFileMetaLoader } from '@/src/core/streaming/dicom/dicomFileMetaLoader'; -import { ReadDicomTagsFunction } from '@/src/core/streaming/dicom/dicomMetaLoader'; -import { ImportHandler, asIntermediateResult } from '@/src/io/import/common'; -import { getWorker } from '@/src/io/itk/worker'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; -import { getErrorDetail } from '@/src/utils'; -import { readDicomTags } from '@itk-wasm/dicom'; - -/** - * Adds DICOM files to the extra context. - * @param dataSource - * @returns - */ -const handleDicomFile: ImportHandler = async (dataSource) => { - if ( - dataSource.type !== 'file' || - dataSource.fileType !== FILE_EXT_TO_MIME.dcm - ) { - return Skip; - } - - const readTags: ReadDicomTagsFunction = async (file) => { - try { - const result = await readDicomTags(file, { webWorker: getWorker() }); - return result.tags; - } catch (error) { - const detail = getErrorDetail( - error, - 'the file could not be parsed as valid DICOM (check browser console for details)' - ); - throw new Error(`Failed to read DICOM tags: ${detail}`, { - cause: error, - }); - } - }; - - const metaLoader = new DicomFileMetaLoader(dataSource.file, readTags); - const dataLoader = new DicomFileDataLoader(dataSource.file); - const chunk = new Chunk({ - metaLoader, - dataLoader, - }); - - await chunk.loadMeta(); - - return asIntermediateResult([ - { - type: 'chunk', - chunk, - mime: FILE_EXT_TO_MIME.dcm, - parent: dataSource, - }, - ]); -}; - -export default handleDicomFile; diff --git a/src/io/import/processors/handleDicomStream.ts b/src/io/import/processors/handleDicomStream.ts deleted file mode 100644 index f6c3ace80..000000000 --- a/src/io/import/processors/handleDicomStream.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { Skip } from '@/src/utils/evaluateChain'; -import { CachedStreamFetcher } from '@/src/core/streaming/cachedStreamFetcher'; -import { Chunk } from '@/src/core/streaming/chunk'; -import { DicomDataLoader } from '@/src/core/streaming/dicom/dicomDataLoader'; -import { - DicomMetaLoader, - ReadDicomTagsFunction, -} from '@/src/core/streaming/dicom/dicomMetaLoader'; -import { getRequestPool } from '@/src/core/streaming/requestPool'; -import { - ImportHandler, - asIntermediateResult, - asOkayResult, -} from '@/src/io/import/common'; -import { getWorker } from '@/src/io/itk/worker'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; -import { getErrorDetail } from '@/src/utils'; -import { readDicomTags } from '@itk-wasm/dicom'; -import { Tags } from '@/src/core/dicomTags'; -import { useMessageStore } from '@/src/store/messages'; - -const handleDicomStream: ImportHandler = async (dataSource) => { - if (dataSource.type !== 'uri' || dataSource?.mime !== FILE_EXT_TO_MIME.dcm) { - return Skip; - } - - const fetcher = - dataSource.fetcher ?? - new CachedStreamFetcher(dataSource.uri, { - fetch: (...args) => getRequestPool().fetch(...args), - }); - - const readTags: ReadDicomTagsFunction = async (file) => { - try { - const result = await readDicomTags(file, { webWorker: getWorker() }); - return result.tags; - } catch (error) { - const detail = getErrorDetail( - error, - 'the file could not be parsed as valid DICOM (check browser console for details)' - ); - throw new Error( - `Failed to read DICOM tags from ${dataSource.uri}: ${detail}`, - { cause: error } - ); - } - }; - - const metaLoader = new DicomMetaLoader(fetcher, readTags); - const dataLoader = new DicomDataLoader(fetcher); - const chunk = new Chunk({ - metaLoader, - dataLoader, - }); - - await chunk.loadMeta(); - - const metadata = chunk.metadata; - if (metadata) { - const modalityEntry = metadata.find(([tag]) => tag === Tags.Modality); - const modality = modalityEntry?.[1]?.trim(); - if (modality?.startsWith('RT')) { - const messageStore = useMessageStore(); - messageStore.addWarning( - `DICOM ${modality} modality is not supported. File ${dataSource.name} will be skipped.` - ); - return asOkayResult(dataSource); - } - } - - return asIntermediateResult([ - { - type: 'chunk', - chunk, - mime: FILE_EXT_TO_MIME.dcm, - parent: dataSource, - }, - ]); -}; - -export default handleDicomStream; diff --git a/src/io/import/processors/openUriStream.ts b/src/io/import/processors/openUriStream.ts index 8c8ac0307..7732f402f 100644 --- a/src/io/import/processors/openUriStream.ts +++ b/src/io/import/processors/openUriStream.ts @@ -1,10 +1,35 @@ import { Skip } from '@/src/utils/evaluateChain'; import { CachedStreamFetcher } from '@/src/core/streaming/cachedStreamFetcher'; -import { getRequestPool } from '@/src/core/streaming/requestPool'; -import { ImportHandler, asIntermediateResult } from '@/src/io/import/common'; -import { canFetchUrl } from '@/src/utils/fetch'; +import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; +import { + ImportHandler, + asIntermediateResult, + type ImportContext, +} from '@/src/io/import/common'; +import { canFetchUrl, fetchFile } from '@/src/utils/fetch'; import { extractFilenameFromContentDisposition } from '@/src/utils/parseContentDispositionHeader'; import { basename } from '@/src/utils/path'; +import { + findStateFileLeaves, + type DataSource, + type UriSource, +} from '@/src/io/import/dataSource'; + +const savedArchiveFile = async ( + dataSource: DataSource & UriSource, + context?: ImportContext +) => { + if (!findStateFileLeaves(dataSource)[0]?.archivePaths?.length) return null; + const file = await fetchFile(dataSource.uri, dataSource.name, { + cache: context?.fetchFileCache, + }); + return { + type: 'file' as const, + file, + fileType: dataSource.mime ?? file.type, + parent: dataSource, + }; +}; const openUriStream: ImportHandler = async (dataSource, context) => { if (dataSource.type !== 'uri' || !canFetchUrl(dataSource.uri)) { @@ -15,8 +40,11 @@ const openUriStream: ImportHandler = async (dataSource, context) => { return Skip; } + const archive = await savedArchiveFile(dataSource, context); + if (archive) return asIntermediateResult([archive]); + const fetcher = new CachedStreamFetcher(dataSource.uri, { - fetch: (...args) => getRequestPool().fetch(...args), + fetch: useDicomRuntimeStore().runtime.fetch, }); await fetcher.connect(); diff --git a/src/io/import/processors/restoreStateFile.ts b/src/io/import/processors/restoreStateFile.ts index 9f3917253..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'; @@ -25,17 +29,23 @@ import { useViewConfigStore } from '@/src/store/view-configs'; import { migrateManifest } from '@/src/io/state-file/migrations'; import { useMessageStore } from '@/src/store/messages'; -type LeafSource = +type LeafSource = ( | { type: 'uri'; uri: string; name: string; mime?: string } - | { type: 'file'; file: File; fileType: string }; + | { type: 'file'; file: File; fileType: string } +) & { archivePaths?: string[] }; + +type LeafSourceContext = { + byId: Record; + datasetFilePath: Record | undefined; + pathToFile: Record; + onMissingFile?: (path: string) => void; +}; function resolveToLeafSources( id: number, - byId: Record, - datasetFilePath: Record | undefined, - pathToFile: Record, - onMissingFile?: (path: string) => void + context: LeafSourceContext ): LeafSource[] { + const { byId, datasetFilePath, pathToFile, onMissingFile } = context; const src = byId[id]; if (!src) return []; @@ -64,23 +74,14 @@ function resolveToLeafSources( } case 'archive': - return resolveToLeafSources( - src.parent, - byId, - datasetFilePath, - pathToFile, - onMissingFile - ); + return resolveToLeafSources(src.parent, context).map((parent) => ({ + ...parent, + archivePaths: [...(parent.archivePaths ?? []), src.path], + })); case 'collection': return src.sources.flatMap((sourceId) => - resolveToLeafSources( - sourceId, - byId, - datasetFilePath, - pathToFile, - onMissingFile - ) + resolveToLeafSources(sourceId, context) ); default: @@ -150,31 +151,55 @@ function prepareLeafDataSources(manifest: Manifest, datasetFiles: FileEntry[]) { ...datasets, ...planLabelmapSources(manifest).leaves, ].flatMap((ds) => { - const sources = resolveToLeafSources( - ds.dataSourceId, + const sources = resolveToLeafSources(ds.dataSourceId, { byId, - manifest.datasetFilePath, + datasetFilePath: manifest.datasetFilePath, pathToFile, - (path) => missingFiles.push({ stateID: ds.id, path }) - ); + onMissingFile: (path) => missingFiles.push({ stateID: ds.id, path }), + }); const seen = new Set(); const uniqueSources = sources.filter((src) => { if (src.type !== 'uri') return true; - if (seen.has(src.uri)) return false; - seen.add(src.uri); + const key = JSON.stringify([src.uri, src.archivePaths]); + if (seen.has(key)) return false; + seen.add(key); return true; }); - return uniqueSources.map((src) => ({ + return uniqueSources.map(({ archivePaths, ...src }) => ({ ...src, - stateFileLeaf: { stateID: ds.id }, + stateFileLeaf: { + stateID: ds.id, + ...(archivePaths ? { archivePaths } : {}), + }, })); }); return { dataSources, missingFiles }; } +const defaultRestoredDataset = ( + manifest: Manifest, + stateIDToStoreID: Record +) => { + const primary = manifest.primarySelection + ? stateIDToStoreID[manifest.primarySelection] + : undefined; + const first = manifestDatasets(manifest).find( + (ds) => ds.id in stateIDToStoreID + ); + 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< @@ -191,13 +216,15 @@ export const createStateFileRestorer = ({ manifest: Manifest, stateFiles: FileEntry[], stateIDToStoreID: Record, - missingFiles: Array<{ stateID: string; path: string }> = [], - failedLeaves: Array<{ stateID: string; name: string }> = [] + { + missingFiles = [], + failedLeaves = [], + splitDatasets = {}, + }: RestoreReports = {} ) { const viewStore = views ?? useViewStore(); const byId = dataSourcesById(manifest); const datasets = manifestDatasets(manifest); - const resolvedDatasets = datasets.filter((ds) => ds.id in stateIDToStoreID); const unresolvedDatasets = datasets.filter( (ds) => !(ds.id in stateIDToStoreID) ); @@ -216,13 +243,7 @@ export const createStateFileRestorer = ({ viewStore.bindViewsToData(stateID, storeID, manifest); }); - const defaultStoreID = - (manifest.primarySelection - ? stateIDToStoreID[manifest.primarySelection] - : undefined) ?? - (resolvedDatasets.length > 0 - ? stateIDToStoreID[resolvedDatasets[0].id] - : undefined); + const defaultStoreID = defaultRestoredDataset(manifest, stateIDToStoreID); if (defaultStoreID !== undefined) { if (!manifest.viewByID) { @@ -254,14 +275,25 @@ export const createStateFileRestorer = ({ useToolStore().deserialize(manifest, segmentIdMap, stateIDToStoreID); - const missingBases = unresolvedDatasets.map((ds) => + const summarize = (ds: (typeof datasets)[number]) => summarizeDataSource( ds.dataSourceId, byId, manifest.datasetFilePath, String(ds.id) - ) - ); + ); + const missingBases = unresolvedDatasets + .filter((ds) => !(ds.id in splitDatasets)) + .map(summarize); + // Saved state has no single target when its dataset becomes several volumes. + const splitBases = unresolvedDatasets + .filter((ds) => ds.id in splitDatasets) + .map( + (ds) => + `- image: ${summarize(ds)} (loaded as ${splitDatasets[ds.id].length} ` + + 'volumes; 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) @@ -285,6 +317,7 @@ export const createStateFileRestorer = ({ ]; const missing = [ ...missingBases.map((name) => `- image: ${name}`), + ...splitBases, ...missingMembers, ...failedMembers, ...skippedLabelmaps.map( @@ -325,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) diff --git a/src/io/import/processors/updateUriType.ts b/src/io/import/processors/updateUriType.ts index ef78ec248..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 '@/src/core/streaming/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 '@/src/utils'; +import { asCoroutine } from '@/src/dicom/core/utils'; const DoneSignal = Symbol('DoneSignal'); diff --git a/src/io/itk-dicom/.gitignore b/src/io/itk-dicom/.gitignore deleted file mode 100644 index cdf3003ca..000000000 --- a/src/io/itk-dicom/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -* -!*.cpp -!*.hpp -!emscripten-build/ -!emscripten-build/dicom* \ No newline at end of file diff --git a/src/io/itk-dicom/CMakeLists.txt b/src/io/itk-dicom/CMakeLists.txt deleted file mode 100644 index d55df7747..000000000 --- a/src/io/itk-dicom/CMakeLists.txt +++ /dev/null @@ -1,71 +0,0 @@ -cmake_minimum_required(VERSION 3.10) - -project(dicom) - -include(FetchContent) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -set(dicom_SRCS dicom.cpp) - -if(EMSCRIPTEN) - add_definitions(-DWEB_BUILD) -endif() - -############################################ -# setup ITK -############################################ - -set(io_components ITKImageIO) -find_package(ITK REQUIRED - COMPONENTS ${io_components} - ITKSmoothing - # for rescale image intensity - ITKImageIntensity - # for GDCMSeriesFileNames.h - ITKIOGDCM - ITKGDCM - # spatial objects - ITKMesh - ITKSpatialObjects - ITKIOSpatialObjects - WebAssemblyInterface - ) - -include(${ITK_USE_FILE}) - -############################################ -# setup third party directory -############################################ - -set(THIRDPARTY_DIR ${CMAKE_BINARY_DIR}/thirdparty) -file(MAKE_DIRECTORY ${THIRDPARTY_DIR}) - -############################################ -# download json.hpp -############################################ - -set(JSON_DIR ${THIRDPARTY_DIR}/json) -FetchContent_Declare(json - PREFIX ${JSON_DIR} - GIT_REPOSITORY https://github.com/nlohmann/json.git - GIT_TAG v3.9.0 - GIT_SHALLOW ON) - -FetchContent_GetProperties(json) -if(NOT json_POPULATED) - FetchContent_Populate(json) - add_subdirectory(${json_SOURCE_DIR} ${json_BINARY_DIR} EXCLUDE_FROM_ALL) -endif() - -############################################ -# parent project -############################################ - -add_executable(dicom ${dicom_SRCS}) -target_link_libraries(dicom PRIVATE ${ITK_LIBRARIES} nlohmann_json::nlohmann_json) - -if(NOT EMSCRIPTEN) - target_link_libraries(dicom PRIVATE stdc++fs) -endif() diff --git a/src/io/itk-dicom/dicom.cpp b/src/io/itk-dicom/dicom.cpp deleted file mode 100644 index 38dd80d74..000000000 --- a/src/io/itk-dicom/dicom.cpp +++ /dev/null @@ -1,319 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef WEB_BUILD -// Building with the itk.js docker container has a more recent gcc version -#include -namespace fs = std::filesystem; -#else -// Building locally with gcc 7.5.0 means I need -lstdc++fs and -// experimental/filesystem -#include -namespace fs = std::experimental::filesystem; -#endif - -#ifdef WEB_BUILD -#include -#endif - -#include -#include -#include - -#include "itkCastImageFilter.h" -#include "itkGDCMImageIO.h" -#include "itkGDCMSeriesFileNames.h" -#include "itkImage.h" -#include "itkImageFileReader.h" -#include "itkImageIOBase.h" -#include "itkImageSeriesReader.h" -#include "itkRescaleIntensityImageFilter.h" -#include "itkVectorImage.h" - -#include "itkOutputImage.h" -#include "itkOutputTextStream.h" -#include "itkPipeline.h" - -#include "gdcmImageHelper.h" -#include "gdcmReader.h" - -using json = nlohmann::json; -using ImageType = itk::Image; -using ReaderType = itk::ImageFileReader; -using SeriesReaderType = itk::ImageSeriesReader; -using FileNamesContainer = std::vector; -using DicomIO = itk::GDCMImageIO; -// volumeID -> filenames[] -using VolumeMapType = std::unordered_map>; -// VolumeID[] -using VolumeIDList = std::vector; - -static const double EPSILON = 10e-5; - -#ifdef WEB_BUILD -extern "C" const char *EMSCRIPTEN_KEEPALIVE unpack_error_what(intptr_t ptr) { - auto error = reinterpret_cast(ptr); - return error->what(); -} -#endif - -void replaceChars(std::string &str, char search, char replaceChar) { - int pos; - std::string replace(1, replaceChar); - while ((pos = str.find(search)) != std::string::npos) { - str.replace(pos, 1, replace); - } -} - -std::vector ReadImageOrientationValue(const std::string &filename) { - gdcm::Reader reader; - reader.SetFileName(filename.c_str()); - if (!reader.Read()) { - throw std::runtime_error("gdcm: failed to read file"); - } - const gdcm::File &file = reader.GetFile(); - // This helper method asserts that the vector has length 6. - return gdcm::ImageHelper::GetDirectionCosinesValue(file); -} - -bool areCosinesAlmostEqual(const std::vector &cosines1, - const std::vector &cosines2, - double epsilon = EPSILON) { - // ImageOrientationPatient is two row vectors: X cosines at [0..2] and - // Y cosines at [3..5]. Compare each row. - for (int row = 0; row < 2; row++) { - const int offset = row * 3; - double dot = 0; - for (int i = 0; i < 3; i++) { - dot += cosines1.at(offset + i) * cosines2.at(offset + i); - } - if (dot < (1 - epsilon)) { - return false; - } - } - return true; -} - -VolumeMapType SeparateOnImageOrientation(const VolumeMapType &volumeMap) { - VolumeMapType newVolumeMap; - - // append unique ID part to the volume ID, based on cosines - // The format replaces non-alphanumeric chars to be semi-consistent with DICOM - // UID spec, - // and to make debugging easier when looking at the full volume IDs. - // Format: COSINE || "S" || COSINE || "S" || ... - // COSINE: A decimal number -DD.DDDD gets reformatted into NDDSDDDD - auto encodeCosinesAsIDPart = [](const std::vector &cosines) { - std::string concatenated; - for (auto it = cosines.begin(); it != cosines.end(); ++it) { - concatenated += std::to_string(*it); - if (it != cosines.end() - 1) { - concatenated += 'S'; - } - } - - replaceChars(concatenated, '-', 'N'); - replaceChars(concatenated, '.', 'D'); - - return concatenated; - }; - - for (const auto &[volumeID, names] : volumeMap) { - // Scope the orientation lookup to a single input volume so distinct - // series with identical orientations stay separate. - std::vector, std::string>> cosinesToID; - - for (const auto &filename : names) { - std::vector curCosines = ReadImageOrientationValue(filename); - - bool inserted = false; - for (const auto &entry : cosinesToID) { - if (areCosinesAlmostEqual(curCosines, entry.first)) { - newVolumeMap[entry.second].push_back(filename); - inserted = true; - break; - } - } - - if (!inserted) { - const auto encodedIDPart = encodeCosinesAsIDPart(curCosines); - auto newID = volumeID + '.' + encodedIDPart; - newVolumeMap[newID].push_back(filename); - cosinesToID.push_back(std::make_pair(curCosines, newID)); - } - } - } - - return newVolumeMap; -} - -/** - * categorizeFiles extracts out the volumes contained within a set of DICOM - * files. - * - * Return a mapping of volume ID to the files containing the volume. - */ -int categorizeFiles(itk::wasm::Pipeline &pipeline) { - - // inputs - FileNamesContainer files; - pipeline.add_option("-f,--files", files, "File names to categorize") - ->required() - ->check(CLI::ExistingFile) - ->expected(1, -1); - - // outputs - itk::wasm::OutputTextStream volumeMapJSONStream; - pipeline - .add_option("volumeMap", volumeMapJSONStream, - "JSON object encoding volumeID => filenames.") - ->required(); - - ITK_WASM_PARSE(pipeline); - - std::string path = "./"; - - // parse out series - typedef itk::GDCMSeriesFileNames SeriesFileNames; - SeriesFileNames::Pointer seriesFileNames = SeriesFileNames::New(); - // files are all default dumped to cwd - seriesFileNames->SetDirectory(path); - seriesFileNames->SetUseSeriesDetails(true); - seriesFileNames->SetGlobalWarningDisplay(false); - seriesFileNames->AddSeriesRestriction("0008|0021"); - seriesFileNames->SetRecursive(false); - // Does this affect series organization? - seriesFileNames->SetLoadPrivateTags(false); - - // Obtain the initial separation of imported files into distinct volumes. - auto &gdcmSeriesUIDs = seriesFileNames->GetSeriesUIDs(); - - // The initial series UIDs are used as the basis for our volume IDs. - VolumeMapType volumeMap; - for (auto seriesUID : gdcmSeriesUIDs) { - volumeMap[seriesUID] = seriesFileNames->GetFileNames(seriesUID.c_str()); - } - - // further restrict on orientation - volumeMap = SeparateOnImageOrientation(volumeMap); - - // strip off tmp prefix - for (auto &entry : volumeMap) { - auto &fileNames = entry.second; - for (auto &f : fileNames) { - f = f.substr(path.size()); - } - } - - // Generate the JSON and add to output stream - auto volumeMapJSON = json(volumeMap); - volumeMapJSONStream.Get() << volumeMapJSON; - - // Clean up files - for (auto &file : files) { - remove(file.c_str()); - } - - return EXIT_SUCCESS; -} - -/** - * Reads an image slice and returns the optionally thumbnailed image. - */ -int getSliceImage(itk::wasm::Pipeline &pipeline) { - - // inputs - std::string fileName; - pipeline.add_option("-f,--file", fileName, "File name generate image for") - ->required() - ->check(CLI::ExistingFile) - ->expected(1); - - bool asThumbnail = false; - pipeline.add_option("-t,--thumbnail", asThumbnail, - "Generate thumbnail image"); - - ITK_WASM_PRE_PARSE(pipeline); - - // Setup reader - typename DicomIO::Pointer dicomIO = DicomIO::New(); - dicomIO->LoadPrivateTagsOff(); - typename ReaderType::Pointer reader = ReaderType::New(); - reader->SetFileName(fileName); - - if (asThumbnail) { - using InputImageType = ImageType; - using OutputPixelType = uint8_t; - using OutputImageType = itk::Image; - using RescaleFilter = - itk::RescaleIntensityImageFilter; - using CastImageFilter = - itk::CastImageFilter; - - // outputs - using WasmOutputImageType = itk::wasm::OutputImage; - WasmOutputImageType outputImage; - pipeline.add_option("OutputImage", outputImage, "The slice")->required(); - - ITK_WASM_PARSE(pipeline); - - auto rescaleFilter = RescaleFilter::New(); - rescaleFilter->SetInput(reader->GetOutput()); - rescaleFilter->SetOutputMinimum(0); - rescaleFilter->SetOutputMaximum(itk::NumericTraits::max()); - - auto castFilter = CastImageFilter::New(); - castFilter->SetInput(rescaleFilter->GetOutput()); - castFilter->Update(); - - // Set the output image - outputImage.Set(castFilter->GetOutput()); - } else { - // outputs - using WasmOutputImageType = itk::wasm::OutputImage; - WasmOutputImageType outputImage; - pipeline.add_option("OutputImage", outputImage, "The slice")->required(); - - ITK_WASM_PARSE(pipeline); - - reader->Update(); - outputImage.Set(reader->GetOutput()); - } - - // Clean up the file - remove(fileName.c_str()); - - return EXIT_SUCCESS; -} - -int main(int argc, char *argv[]) { - std::string action; - itk::wasm::Pipeline pipeline("DICOM-VolView", "VolView pipeline to access DICOM data", argc, - argv); - pipeline.add_option("-a,--action", action, "The action to run") - ->check(CLI::IsMember({"categorize", "getSliceImage"})); - - // Pre parse so we can get the action - ITK_WASM_PRE_PARSE(pipeline) - - if (action == "categorize") { - - ITK_WASM_CATCH_EXCEPTION(pipeline, categorizeFiles(pipeline)); - - } else if (action == "getSliceImage") { - - ITK_WASM_CATCH_EXCEPTION(pipeline, getSliceImage(pipeline)); - } - - return EXIT_SUCCESS; -} diff --git a/src/io/itk-dicom/emscripten-build/dicom.js b/src/io/itk-dicom/emscripten-build/dicom.js deleted file mode 100644 index 60a2bf780..000000000 --- a/src/io/itk-dicom/emscripten-build/dicom.js +++ /dev/null @@ -1,16 +0,0 @@ - -var dicom = (() => { - var _scriptName = import.meta.url; - - return ( -async function(moduleArg = {}) { - var moduleRtn; - -var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("module");let dirname=import.meta.url;if(dirname.startsWith("data:")){dirname="/"}var require=createRequire(dirname)}var mStdout=null;var mStderr=null;Module["resetModuleStdout"]=function(){mStdout=""};Module["resetModuleStderr"]=function(){mStderr=""};Module["print"]=function(text){console.log(text);mStdout+=text+"\n"};Module["printErr"]=function(text){console.error(text);mStderr+=text+"\n"};Module["getModuleStdout"]=function(){return mStdout};Module["getModuleStderr"]=function(){return mStderr};var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");if(!import.meta.url.startsWith("data:")){scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(!Module["thisProgram"]&&process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;if(!Module["noFSInit"]&&!FS.initialized)FS.init();FS.ignorePermissions=false;TTY.init();SOCKFS.root=FS.mount(SOCKFS,{},null);callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var dependenciesFulfilled=null;function getUniqueRunDependency(id){return id}function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);var isFileURI=filename=>filename.startsWith("file://");function findWasmBinary(){if(Module["locateFile"]){var f="dicom.wasm";if(!isDataURI(f)){return locateFile(f)}return f}return new URL("dicom.wasm",import.meta.url).href}var wasmBinaryFile;function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmExports=applySignatureConversions(wasmExports);wasmMemory=wasmExports["ea"];updateMemoryViews();wasmTable=wasmExports["ra"];addOnInit(wasmExports["fa"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}var info=getWasmImports();if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);readyPromiseReject(e)}}wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);receiveInstantiationResult(result);return result}catch(e){readyPromiseReject(e);return}}var tempDouble;var tempI64;class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var noExitRuntime=Module["noExitRuntime"]||true;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>>2>>>0]=type}get_type(){return HEAPU32[this.ptr+4>>>2>>>0]}set_destructor(destructor){HEAPU32[this.ptr+8>>>2>>>0]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>>2>>>0]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12>>>0]=caught}get_caught(){return HEAP8[this.ptr+12>>>0]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13>>>0]=rethrown}get_rethrown(){return HEAP8[this.ptr+13>>>0]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>>2>>>0]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>>2>>>0]}}var exceptionLast=0;var uncaughtExceptionCount=0;var convertI32PairToI53Checked=(lo,hi)=>hi+2097152>>>0<4194305-!!lo?(lo>>>0)+hi*4294967296:NaN;function ___cxa_throw(ptr,type,destructor){ptr>>>=0;type>>>=0;destructor>>>=0;var info=new ExceptionInfo(ptr);info.init(type,destructor);exceptionLast=ptr;uncaughtExceptionCount++;throw exceptionLast}var PATH={isAbs:path=>path.charAt(0)==="/",splitPath:filename=>{var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return splitPathRe.exec(filename).slice(1)},normalizeArray:(parts,allowAboveRoot)=>{var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up;up--){parts.unshift("..")}}return parts},normalize:path=>{var isAbsolute=PATH.isAbs(path),trailingSlash=path.substr(-1)==="/";path=PATH.normalizeArray(path.split("/").filter(p=>!!p),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path},dirname:path=>{var result=PATH.splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir},basename:path=>{if(path==="/")return"/";path=PATH.normalize(path);path=path.replace(/\/$/,"");var lastSlash=path.lastIndexOf("/");if(lastSlash===-1)return path;return path.substr(lastSlash+1)},join:(...paths)=>PATH.normalize(paths.join("/")),join2:(l,r)=>PATH.normalize(l+"/"+r)};var initRandomFill=()=>{if(typeof crypto=="object"&&typeof crypto["getRandomValues"]=="function"){return view=>crypto.getRandomValues(view)}else if(ENVIRONMENT_IS_NODE){try{var crypto_module=require("crypto");var randomFillSync=crypto_module["randomFillSync"];if(randomFillSync){return view=>crypto_module["randomFillSync"](view)}var randomBytes=crypto_module["randomBytes"];return view=>(view.set(randomBytes(view.byteLength)),view)}catch(e){}}abort("initRandomDevice")};var randomFill=view=>(randomFill=initRandomFill())(view);var PATH_FS={resolve:(...args)=>{var resolvedPath="",resolvedAbsolute=false;for(var i=args.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?args[i]:FS.cwd();if(typeof path!="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){return""}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=PATH.isAbs(path)}resolvedPath=PATH.normalizeArray(resolvedPath.split("/").filter(p=>!!p),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."},relative:(from,to)=>{from=PATH_FS.resolve(from).substr(1);to=PATH_FS.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i{idx>>>=0;var endIdx=idx+maxBytesToRead;var endPtr=idx;while(heapOrArray[endPtr]&&!(endPtr>=endIdx))++endPtr;if(endPtr-idx>16&&heapOrArray.buffer&&UTF8Decoder){return UTF8Decoder.decode(heapOrArray.subarray(idx,endPtr))}var str="";while(idx>10,56320|ch&1023)}}return str};var FS_stdin_getChar_buffer=[];var lengthBytesUTF8=str=>{var len=0;for(var i=0;i=55296&&c<=57343){len+=4;++i}else{len+=3}}return len};var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{outIdx>>>=0;if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i=55296&&u<=57343){var u1=str.charCodeAt(++i);u=65536+((u&1023)<<10)|u1&1023}if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++>>>0]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++>>>0]=192|u>>6;heap[outIdx++>>>0]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++>>>0]=224|u>>12;heap[outIdx++>>>0]=128|u>>6&63;heap[outIdx++>>>0]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++>>>0]=240|u>>18;heap[outIdx++>>>0]=128|u>>12&63;heap[outIdx++>>>0]=128|u>>6&63;heap[outIdx++>>>0]=128|u&63}}heap[outIdx>>>0]=0;return outIdx-startIdx};function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var result=null;if(ENVIRONMENT_IS_NODE){var BUFSIZE=256;var buf=Buffer.alloc(BUFSIZE);var bytesRead=0;var fd=process.stdin.fd;try{bytesRead=fs.readSync(fd,buf,0,BUFSIZE)}catch(e){if(e.toString().includes("EOF"))bytesRead=0;else throw e}if(bytesRead>0){result=buf.slice(0,bytesRead).toString("utf-8")}}else if(typeof window!="undefined"&&typeof window.prompt=="function"){result=window.prompt("Input: ");if(result!==null){result+="\n"}}else{}if(!result){return null}FS_stdin_getChar_buffer=intArrayFromString(result,true)}return FS_stdin_getChar_buffer.shift()};var TTY={ttys:[],init(){},shutdown(){},register(dev,ops){TTY.ttys[dev]={input:[],output:[],ops};FS.registerDevice(dev,TTY.stream_ops)},stream_ops:{open(stream){var tty=TTY.ttys[stream.node.rdev];if(!tty){throw new FS.ErrnoError(43)}stream.tty=tty;stream.seekable=false},close(stream){stream.tty.ops.fsync(stream.tty)},fsync(stream){stream.tty.ops.fsync(stream.tty)},read(stream,buffer,offset,length,pos){if(!stream.tty||!stream.tty.ops.get_char){throw new FS.ErrnoError(60)}var bytesRead=0;for(var i=0;i0){out(UTF8ArrayToString(tty.output));tty.output=[]}},ioctl_tcgets(tty){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(tty,optional_actions,data){return 0},ioctl_tiocgwinsz(tty){return[24,80]}},default_tty1_ops:{put_char(tty,val){if(val===null||val===10){err(UTF8ArrayToString(tty.output));tty.output=[]}else{if(val!=0)tty.output.push(val)}},fsync(tty){if(tty.output&&tty.output.length>0){err(UTF8ArrayToString(tty.output));tty.output=[]}}}};var zeroMemory=(address,size)=>{HEAPU8.fill(0,address,address+size)};var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var mmapAlloc=size=>{size=alignMemory(size,65536);var ptr=_emscripten_builtin_memalign(65536,size);if(ptr)zeroMemory(ptr,size);return ptr};var MEMFS={ops_table:null,mount(mount){return MEMFS.createNode(null,"/",16895,0)},createNode(parent,name,mode,dev){if(FS.isBlkdev(mode)||FS.isFIFO(mode)){throw new FS.ErrnoError(63)}MEMFS.ops_table||={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}};var node=FS.createNode(parent,name,mode,dev);if(FS.isDir(node.mode)){node.node_ops=MEMFS.ops_table.dir.node;node.stream_ops=MEMFS.ops_table.dir.stream;node.contents={}}else if(FS.isFile(node.mode)){node.node_ops=MEMFS.ops_table.file.node;node.stream_ops=MEMFS.ops_table.file.stream;node.usedBytes=0;node.contents=null}else if(FS.isLink(node.mode)){node.node_ops=MEMFS.ops_table.link.node;node.stream_ops=MEMFS.ops_table.link.stream}else if(FS.isChrdev(node.mode)){node.node_ops=MEMFS.ops_table.chrdev.node;node.stream_ops=MEMFS.ops_table.chrdev.stream}node.atime=node.mtime=node.ctime=Date.now();if(parent){parent.contents[name]=node;parent.atime=parent.mtime=parent.ctime=node.atime}return node},getFileDataAsTypedArray(node){if(!node.contents)return new Uint8Array(0);if(node.contents.subarray)return node.contents.subarray(0,node.usedBytes);return new Uint8Array(node.contents)},expandFileStorage(node,newCapacity){var prevCapacity=node.contents?node.contents.length:0;if(prevCapacity>=newCapacity)return;var CAPACITY_DOUBLING_MAX=1024*1024;newCapacity=Math.max(newCapacity,prevCapacity*(prevCapacity>>0);if(prevCapacity!=0)newCapacity=Math.max(newCapacity,256);var oldContents=node.contents;node.contents=new Uint8Array(newCapacity);if(node.usedBytes>0)node.contents.set(oldContents.subarray(0,node.usedBytes),0)},resizeFileStorage(node,newSize){if(node.usedBytes==newSize)return;if(newSize==0){node.contents=null;node.usedBytes=0}else{var oldContents=node.contents;node.contents=new Uint8Array(newSize);if(oldContents){node.contents.set(oldContents.subarray(0,Math.min(newSize,node.usedBytes)))}node.usedBytes=newSize}},node_ops:{getattr(node){var attr={};attr.dev=FS.isChrdev(node.mode)?node.id:1;attr.ino=node.id;attr.mode=node.mode;attr.nlink=1;attr.uid=0;attr.gid=0;attr.rdev=node.rdev;if(FS.isDir(node.mode)){attr.size=4096}else if(FS.isFile(node.mode)){attr.size=node.usedBytes}else if(FS.isLink(node.mode)){attr.size=node.link.length}else{attr.size=0}attr.atime=new Date(node.atime);attr.mtime=new Date(node.mtime);attr.ctime=new Date(node.ctime);attr.blksize=4096;attr.blocks=Math.ceil(attr.size/attr.blksize);return attr},setattr(node,attr){for(const key of["mode","atime","mtime","ctime"]){if(attr[key]){node[key]=attr[key]}}if(attr.size!==undefined){MEMFS.resizeFileStorage(node,attr.size)}},lookup(parent,name){throw MEMFS.doesNotExistError},mknod(parent,name,mode,dev){return MEMFS.createNode(parent,name,mode,dev)},rename(old_node,new_dir,new_name){var new_node;try{new_node=FS.lookupNode(new_dir,new_name)}catch(e){}if(new_node){if(FS.isDir(old_node.mode)){for(var i in new_node.contents){throw new FS.ErrnoError(55)}}FS.hashRemoveNode(new_node)}delete old_node.parent.contents[old_node.name];new_dir.contents[new_name]=old_node;old_node.name=new_name;new_dir.ctime=new_dir.mtime=old_node.parent.ctime=old_node.parent.mtime=Date.now()},unlink(parent,name){delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},rmdir(parent,name){var node=FS.lookupNode(parent,name);for(var i in node.contents){throw new FS.ErrnoError(55)}delete parent.contents[name];parent.ctime=parent.mtime=Date.now()},readdir(node){return[".","..",...Object.keys(node.contents)]},symlink(parent,newname,oldpath){var node=MEMFS.createNode(parent,newname,511|40960,0);node.link=oldpath;return node},readlink(node){if(!FS.isLink(node.mode)){throw new FS.ErrnoError(28)}return node.link}},stream_ops:{read(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=stream.node.usedBytes)return 0;var size=Math.min(stream.node.usedBytes-position,length);if(size>8&&contents.subarray){buffer.set(contents.subarray(position,position+size),offset)}else{for(var i=0;i0||position+length>>0)}}return{ptr,allocated}},msync(stream,buffer,offset,length,mmapFlags){MEMFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var asyncLoad=async url=>{var arrayBuffer=await readAsync(url);return new Uint8Array(arrayBuffer)};var FS_createDataFile=(parent,name,fileData,canRead,canWrite,canOwn)=>{FS.createDataFile(parent,name,fileData,canRead,canWrite,canOwn)};var preloadPlugins=Module["preloadPlugins"]||[];var FS_handledByPreloadPlugin=(byteArray,fullname,finish,onerror)=>{if(typeof Browser!="undefined")Browser.init();var handled=false;preloadPlugins.forEach(plugin=>{if(handled)return;if(plugin["canHandle"](fullname)){plugin["handle"](byteArray,fullname,finish,onerror);handled=true}});return handled};var FS_createPreloadedFile=(parent,name,url,canRead,canWrite,onload,onerror,dontCreateFile,canOwn,preFinish)=>{var fullname=name?PATH_FS.resolve(PATH.join2(parent,name)):parent;var dep=getUniqueRunDependency(`cp ${fullname}`);function processData(byteArray){function finish(byteArray){preFinish?.();if(!dontCreateFile){FS_createDataFile(parent,name,byteArray,canRead,canWrite,canOwn)}onload?.();removeRunDependency(dep)}if(FS_handledByPreloadPlugin(byteArray,fullname,finish,()=>{onerror?.();removeRunDependency(dep)})){return}finish(byteArray)}addRunDependency(dep);if(typeof url=="string"){asyncLoad(url).then(processData,onerror)}else{processData(url)}};var FS_modeStringToFlags=str=>{var flagModes={r:0,"r+":2,w:512|64|1,"w+":512|64|2,a:1024|64|1,"a+":1024|64|2};var flags=flagModes[str];if(typeof flags=="undefined"){throw new Error(`Unknown file open mode: ${str}`)}return flags};var FS_getMode=(canRead,canWrite)=>{var mode=0;if(canRead)mode|=292|73;if(canWrite)mode|=146;return mode};var ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};var NODEFS={isWindows:false,staticInit(){NODEFS.isWindows=!!process.platform.match(/^win/);var flags=process.binding("constants");if(flags["fs"]){flags=flags["fs"]}NODEFS.flagsForNodeMap={1024:flags["O_APPEND"],64:flags["O_CREAT"],128:flags["O_EXCL"],256:flags["O_NOCTTY"],0:flags["O_RDONLY"],2:flags["O_RDWR"],4096:flags["O_SYNC"],512:flags["O_TRUNC"],1:flags["O_WRONLY"],131072:flags["O_NOFOLLOW"]}},convertNodeCode(e){var code=e.code;return ERRNO_CODES[code]},tryFSOperation(f){try{return f()}catch(e){if(!e.code)throw e;if(e.code==="UNKNOWN")throw new FS.ErrnoError(28);throw new FS.ErrnoError(NODEFS.convertNodeCode(e))}},mount(mount){return NODEFS.createNode(null,"/",NODEFS.getMode(mount.opts.root),0)},createNode(parent,name,mode,dev){if(!FS.isDir(mode)&&!FS.isFile(mode)&&!FS.isLink(mode)){throw new FS.ErrnoError(28)}var node=FS.createNode(parent,name,mode);node.node_ops=NODEFS.node_ops;node.stream_ops=NODEFS.stream_ops;return node},getMode(path){return NODEFS.tryFSOperation(()=>{var mode=fs.lstatSync(path).mode;if(NODEFS.isWindows){mode|=(mode&292)>>2}return mode})},realPath(node){var parts=[];while(node.parent!==node){parts.push(node.name);node=node.parent}parts.push(node.mount.opts.root);parts.reverse();return PATH.join(...parts)},flagsForNode(flags){flags&=~2097152;flags&=~2048;flags&=~32768;flags&=~524288;flags&=~65536;var newFlags=0;for(var k in NODEFS.flagsForNodeMap){if(flags&k){newFlags|=NODEFS.flagsForNodeMap[k];flags^=k}}if(flags){throw new FS.ErrnoError(28)}return newFlags},node_ops:{getattr(node){var path=NODEFS.realPath(node);var stat;NODEFS.tryFSOperation(()=>stat=fs.lstatSync(path));if(NODEFS.isWindows){if(!stat.blksize){stat.blksize=4096}if(!stat.blocks){stat.blocks=(stat.size+stat.blksize-1)/stat.blksize|0}stat.mode|=(stat.mode&292)>>2}return{dev:stat.dev,ino:stat.ino,mode:stat.mode,nlink:stat.nlink,uid:stat.uid,gid:stat.gid,rdev:stat.rdev,size:stat.size,atime:stat.atime,mtime:stat.mtime,ctime:stat.ctime,blksize:stat.blksize,blocks:stat.blocks}},setattr(node,attr){var path=NODEFS.realPath(node);NODEFS.tryFSOperation(()=>{if(attr.mode!==undefined){var mode=attr.mode;if(NODEFS.isWindows){mode&=384}fs.chmodSync(path,mode);node.mode=attr.mode}if(attr.atime||attr.mtime){var atime=attr.atime&&new Date(attr.atime);var mtime=attr.mtime&&new Date(attr.mtime);fs.utimesSync(path,atime,mtime)}if(attr.size!==undefined){fs.truncateSync(path,attr.size)}})},lookup(parent,name){var path=PATH.join2(NODEFS.realPath(parent),name);var mode=NODEFS.getMode(path);return NODEFS.createNode(parent,name,mode)},mknod(parent,name,mode,dev){var node=NODEFS.createNode(parent,name,mode,dev);var path=NODEFS.realPath(node);NODEFS.tryFSOperation(()=>{if(FS.isDir(node.mode)){fs.mkdirSync(path,node.mode)}else{fs.writeFileSync(path,"",{mode:node.mode})}});return node},rename(oldNode,newDir,newName){var oldPath=NODEFS.realPath(oldNode);var newPath=PATH.join2(NODEFS.realPath(newDir),newName);try{FS.unlink(newPath)}catch(e){}NODEFS.tryFSOperation(()=>fs.renameSync(oldPath,newPath));oldNode.name=newName},unlink(parent,name){var path=PATH.join2(NODEFS.realPath(parent),name);NODEFS.tryFSOperation(()=>fs.unlinkSync(path))},rmdir(parent,name){var path=PATH.join2(NODEFS.realPath(parent),name);NODEFS.tryFSOperation(()=>fs.rmdirSync(path))},readdir(node){var path=NODEFS.realPath(node);return NODEFS.tryFSOperation(()=>fs.readdirSync(path))},symlink(parent,newName,oldPath){var newPath=PATH.join2(NODEFS.realPath(parent),newName);NODEFS.tryFSOperation(()=>fs.symlinkSync(oldPath,newPath))},readlink(node){var path=NODEFS.realPath(node);return NODEFS.tryFSOperation(()=>fs.readlinkSync(path))},statfs(path){var stats=NODEFS.tryFSOperation(()=>fs.statfsSync(path));stats.frsize=stats.bsize;return stats}},stream_ops:{open(stream){var path=NODEFS.realPath(stream.node);NODEFS.tryFSOperation(()=>{if(FS.isFile(stream.node.mode)){stream.shared.refcount=1;stream.nfd=fs.openSync(path,NODEFS.flagsForNode(stream.flags))}})},close(stream){NODEFS.tryFSOperation(()=>{if(FS.isFile(stream.node.mode)&&stream.nfd&&--stream.shared.refcount===0){fs.closeSync(stream.nfd)}})},dup(stream){stream.shared.refcount++},read(stream,buffer,offset,length,position){if(length===0)return 0;return NODEFS.tryFSOperation(()=>fs.readSync(stream.nfd,new Int8Array(buffer.buffer,offset,length),0,length,position))},write(stream,buffer,offset,length,position){return NODEFS.tryFSOperation(()=>fs.writeSync(stream.nfd,new Int8Array(buffer.buffer,offset,length),0,length,position))},llseek(stream,offset,whence){var position=offset;if(whence===1){position+=stream.position}else if(whence===2){if(FS.isFile(stream.node.mode)){NODEFS.tryFSOperation(()=>{var stat=fs.fstatSync(stream.nfd);position+=stat.size})}}if(position<0){throw new FS.ErrnoError(28)}return position},mmap(stream,length,position,prot,flags){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}var ptr=mmapAlloc(length);NODEFS.stream_ops.read(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}},msync(stream,buffer,offset,length,mmapFlags){NODEFS.stream_ops.write(stream,buffer,0,length,offset,false);return 0}}};var FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:false,ignorePermissions:true,ErrnoError:class{name="ErrnoError";constructor(errno){this.errno=errno}},filesystems:null,syncFSRequests:0,readFiles:{},FSStream:class{shared={};get object(){return this.node}set object(val){this.node=val}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(val){this.shared.flags=val}get position(){return this.shared.position}set position(val){this.shared.position=val}},FSNode:class{node_ops={};stream_ops={};readMode=292|73;writeMode=146;mounted=null;constructor(parent,name,mode,rdev){if(!parent){parent=this}this.parent=parent;this.mount=parent.mount;this.id=FS.nextInode++;this.name=name;this.mode=mode;this.rdev=rdev;this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(val){val?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(val){val?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(path,opts={}){if(!path)return{path:"",node:null};opts.follow_mount??=true;if(!PATH.isAbs(path)){path=FS.cwd()+"/"+path}linkloop:for(var nlinks=0;nlinks<40;nlinks++){var parts=path.split("/").filter(p=>!!p&&p!==".");var current=FS.root;var current_path="/";for(var i=0;i>>0)%FS.nameTable.length},hashAddNode(node){var hash=FS.hashName(node.parent.id,node.name);node.name_next=FS.nameTable[hash];FS.nameTable[hash]=node},hashRemoveNode(node){var hash=FS.hashName(node.parent.id,node.name);if(FS.nameTable[hash]===node){FS.nameTable[hash]=node.name_next}else{var current=FS.nameTable[hash];while(current){if(current.name_next===node){current.name_next=node.name_next;break}current=current.name_next}}},lookupNode(parent,name){var errCode=FS.mayLookup(parent);if(errCode){throw new FS.ErrnoError(errCode)}var hash=FS.hashName(parent.id,name);for(var node=FS.nameTable[hash];node;node=node.name_next){var nodeName=node.name;if(node.parent.id===parent.id&&nodeName===name){return node}}return FS.lookup(parent,name)},createNode(parent,name,mode,rdev){var node=new FS.FSNode(parent,name,mode,rdev);FS.hashAddNode(node);return node},destroyNode(node){FS.hashRemoveNode(node)},isRoot(node){return node===node.parent},isMountpoint(node){return!!node.mounted},isFile(mode){return(mode&61440)===32768},isDir(mode){return(mode&61440)===16384},isLink(mode){return(mode&61440)===40960},isChrdev(mode){return(mode&61440)===8192},isBlkdev(mode){return(mode&61440)===24576},isFIFO(mode){return(mode&61440)===4096},isSocket(mode){return(mode&49152)===49152},flagsToPermissionString(flag){var perms=["r","w","rw"][flag&3];if(flag&512){perms+="w"}return perms},nodePermissions(node,perms){if(FS.ignorePermissions){return 0}if(perms.includes("r")&&!(node.mode&292)){return 2}else if(perms.includes("w")&&!(node.mode&146)){return 2}else if(perms.includes("x")&&!(node.mode&73)){return 2}return 0},mayLookup(dir){if(!FS.isDir(dir.mode))return 54;var errCode=FS.nodePermissions(dir,"x");if(errCode)return errCode;if(!dir.node_ops.lookup)return 2;return 0},mayCreate(dir,name){if(!FS.isDir(dir.mode)){return 54}try{var node=FS.lookupNode(dir,name);return 20}catch(e){}return FS.nodePermissions(dir,"wx")},mayDelete(dir,name,isdir){var node;try{node=FS.lookupNode(dir,name)}catch(e){return e.errno}var errCode=FS.nodePermissions(dir,"wx");if(errCode){return errCode}if(isdir){if(!FS.isDir(node.mode)){return 54}if(FS.isRoot(node)||FS.getPath(node)===FS.cwd()){return 10}}else{if(FS.isDir(node.mode)){return 31}}return 0},mayOpen(node,flags){if(!node){return 44}if(FS.isLink(node.mode)){return 32}else if(FS.isDir(node.mode)){if(FS.flagsToPermissionString(flags)!=="r"||flags&512){return 31}}return FS.nodePermissions(node,FS.flagsToPermissionString(flags))},MAX_OPEN_FDS:4096,nextfd(){for(var fd=0;fd<=FS.MAX_OPEN_FDS;fd++){if(!FS.streams[fd]){return fd}}throw new FS.ErrnoError(33)},getStreamChecked(fd){var stream=FS.getStream(fd);if(!stream){throw new FS.ErrnoError(8)}return stream},getStream:fd=>FS.streams[fd],createStream(stream,fd=-1){stream=Object.assign(new FS.FSStream,stream);if(fd==-1){fd=FS.nextfd()}stream.fd=fd;FS.streams[fd]=stream;return stream},closeStream(fd){FS.streams[fd]=null},dupStream(origStream,fd=-1){var stream=FS.createStream(origStream,fd);stream.stream_ops?.dup?.(stream);return stream},chrdev_stream_ops:{open(stream){var device=FS.getDevice(stream.node.rdev);stream.stream_ops=device.stream_ops;stream.stream_ops.open?.(stream)},llseek(){throw new FS.ErrnoError(70)}},major:dev=>dev>>8,minor:dev=>dev&255,makedev:(ma,mi)=>ma<<8|mi,registerDevice(dev,ops){FS.devices[dev]={stream_ops:ops}},getDevice:dev=>FS.devices[dev],getMounts(mount){var mounts=[];var check=[mount];while(check.length){var m=check.pop();mounts.push(m);check.push(...m.mounts)}return mounts},syncfs(populate,callback){if(typeof populate=="function"){callback=populate;populate=false}FS.syncFSRequests++;if(FS.syncFSRequests>1){err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`)}var mounts=FS.getMounts(FS.root.mount);var completed=0;function doCallback(errCode){FS.syncFSRequests--;return callback(errCode)}function done(errCode){if(errCode){if(!done.errored){done.errored=true;return doCallback(errCode)}return}if(++completed>=mounts.length){doCallback(null)}}mounts.forEach(mount=>{if(!mount.type.syncfs){return done(null)}mount.type.syncfs(mount,populate,done)})},mount(type,opts,mountpoint){var root=mountpoint==="/";var pseudo=!mountpoint;var node;if(root&&FS.root){throw new FS.ErrnoError(10)}else if(!root&&!pseudo){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});mountpoint=lookup.path;node=lookup.node;if(FS.isMountpoint(node)){throw new FS.ErrnoError(10)}if(!FS.isDir(node.mode)){throw new FS.ErrnoError(54)}}var mount={type,opts,mountpoint,mounts:[]};var mountRoot=type.mount(mount);mountRoot.mount=mount;mount.root=mountRoot;if(root){FS.root=mountRoot}else if(node){node.mounted=mount;if(node.mount){node.mount.mounts.push(mount)}}return mountRoot},unmount(mountpoint){var lookup=FS.lookupPath(mountpoint,{follow_mount:false});if(!FS.isMountpoint(lookup.node)){throw new FS.ErrnoError(28)}var node=lookup.node;var mount=node.mounted;var mounts=FS.getMounts(mount);Object.keys(FS.nameTable).forEach(hash=>{var current=FS.nameTable[hash];while(current){var next=current.name_next;if(mounts.includes(current.mount)){FS.destroyNode(current)}current=next}});node.mounted=null;var idx=node.mount.mounts.indexOf(mount);node.mount.mounts.splice(idx,1)},lookup(parent,name){return parent.node_ops.lookup(parent,name)},mknod(path,mode,dev){var lookup=FS.lookupPath(path,{parent:true});var parent=lookup.node;var name=PATH.basename(path);if(!name||name==="."||name===".."){throw new FS.ErrnoError(28)}var errCode=FS.mayCreate(parent,name);if(errCode){throw new FS.ErrnoError(errCode)}if(!parent.node_ops.mknod){throw new FS.ErrnoError(63)}return parent.node_ops.mknod(parent,name,mode,dev)},statfs(path){var rtn={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255};var parent=FS.lookupPath(path,{follow:true}).node;if(parent?.node_ops.statfs){Object.assign(rtn,parent.node_ops.statfs(parent.mount.opts.root))}return rtn},create(path,mode=438){mode&=4095;mode|=32768;return FS.mknod(path,mode,0)},mkdir(path,mode=511){mode&=511|512;mode|=16384;return FS.mknod(path,mode,0)},mkdirTree(path,mode){var dirs=path.split("/");var d="";for(var i=0;iFS.currentPath,chdir(path){var lookup=FS.lookupPath(path,{follow:true});if(lookup.node===null){throw new FS.ErrnoError(44)}if(!FS.isDir(lookup.node.mode)){throw new FS.ErrnoError(54)}var errCode=FS.nodePermissions(lookup.node,"x");if(errCode){throw new FS.ErrnoError(errCode)}FS.currentPath=lookup.path},createDefaultDirectories(){FS.mkdir("/tmp");FS.mkdir("/home");FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev");FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(stream,buffer,offset,length,pos)=>length,llseek:()=>0});FS.mkdev("/dev/null",FS.makedev(1,3));TTY.register(FS.makedev(5,0),TTY.default_tty_ops);TTY.register(FS.makedev(6,0),TTY.default_tty1_ops);FS.mkdev("/dev/tty",FS.makedev(5,0));FS.mkdev("/dev/tty1",FS.makedev(6,0));var randomBuffer=new Uint8Array(1024),randomLeft=0;var randomByte=()=>{if(randomLeft===0){randomLeft=randomFill(randomBuffer).byteLength}return randomBuffer[--randomLeft]};FS.createDevice("/dev","random",randomByte);FS.createDevice("/dev","urandom",randomByte);FS.mkdir("/dev/shm");FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var proc_self=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd");FS.mount({mount(){var node=FS.createNode(proc_self,"fd",16895,73);node.stream_ops={llseek:MEMFS.stream_ops.llseek};node.node_ops={lookup(parent,name){var fd=+name;var stream=FS.getStreamChecked(fd);var ret={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>stream.path},id:fd+1};ret.parent=ret;return ret},readdir(){return Array.from(FS.streams.entries()).filter(([k,v])=>v).map(([k,v])=>k.toString())}};return node}},{},"/proc/self/fd")},createStandardStreams(input,output,error){if(input){FS.createDevice("/dev","stdin",input)}else{FS.symlink("/dev/tty","/dev/stdin")}if(output){FS.createDevice("/dev","stdout",null,output)}else{FS.symlink("/dev/tty","/dev/stdout")}if(error){FS.createDevice("/dev","stderr",null,error)}else{FS.symlink("/dev/tty1","/dev/stderr")}var stdin=FS.open("/dev/stdin",0);var stdout=FS.open("/dev/stdout",1);var stderr=FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096);FS.mount(MEMFS,{},"/");FS.createDefaultDirectories();FS.createDefaultDevices();FS.createSpecialDirectories();FS.filesystems={MEMFS,NODEFS}},init(input,output,error){FS.initialized=true;input??=Module["stdin"];output??=Module["stdout"];error??=Module["stderr"];FS.createStandardStreams(input,output,error)},quit(){FS.initialized=false;for(var i=0;ithis.length-1||idx<0){return undefined}var chunkOffset=idx%this.chunkSize;var chunkNum=idx/this.chunkSize|0;return this.getter(chunkNum)[chunkOffset]}setDataGetter(getter){this.getter=getter}cacheLength(){var xhr=new XMLHttpRequest;xhr.open("HEAD",url,false);xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);var datalength=Number(xhr.getResponseHeader("Content-length"));var header;var hasByteServing=(header=xhr.getResponseHeader("Accept-Ranges"))&&header==="bytes";var usesGzip=(header=xhr.getResponseHeader("Content-Encoding"))&&header==="gzip";var chunkSize=1024*1024;if(!hasByteServing)chunkSize=datalength;var doXHR=(from,to)=>{if(from>to)throw new Error("invalid range ("+from+", "+to+") or no bytes requested!");if(to>datalength-1)throw new Error("only "+datalength+" bytes available! programmer error!");var xhr=new XMLHttpRequest;xhr.open("GET",url,false);if(datalength!==chunkSize)xhr.setRequestHeader("Range","bytes="+from+"-"+to);xhr.responseType="arraybuffer";if(xhr.overrideMimeType){xhr.overrideMimeType("text/plain; charset=x-user-defined")}xhr.send(null);if(!(xhr.status>=200&&xhr.status<300||xhr.status===304))throw new Error("Couldn't load "+url+". Status: "+xhr.status);if(xhr.response!==undefined){return new Uint8Array(xhr.response||[])}return intArrayFromString(xhr.responseText||"",true)};var lazyArray=this;lazyArray.setDataGetter(chunkNum=>{var start=chunkNum*chunkSize;var end=(chunkNum+1)*chunkSize-1;end=Math.min(end,datalength-1);if(typeof lazyArray.chunks[chunkNum]=="undefined"){lazyArray.chunks[chunkNum]=doXHR(start,end)}if(typeof lazyArray.chunks[chunkNum]=="undefined")throw new Error("doXHR failed!");return lazyArray.chunks[chunkNum]});if(usesGzip||!datalength){chunkSize=datalength=1;datalength=this.getter(0).length;chunkSize=datalength;out("LazyFiles on gzip forces download of the whole file when length is accessed")}this._length=datalength;this._chunkSize=chunkSize;this.lengthKnown=true}get length(){if(!this.lengthKnown){this.cacheLength()}return this._length}get chunkSize(){if(!this.lengthKnown){this.cacheLength()}return this._chunkSize}}if(typeof XMLHttpRequest!="undefined"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var lazyArray=new LazyUint8Array;var properties={isDevice:false,contents:lazyArray}}else{var properties={isDevice:false,url}}var node=FS.createFile(parent,name,properties,canRead,canWrite);if(properties.contents){node.contents=properties.contents}else if(properties.url){node.contents=null;node.url=properties.url}Object.defineProperties(node,{usedBytes:{get:function(){return this.contents.length}}});var stream_ops={};var keys=Object.keys(node.stream_ops);keys.forEach(key=>{var fn=node.stream_ops[key];stream_ops[key]=(...args)=>{FS.forceLoadFile(node);return fn(...args)}});function writeChunks(stream,buffer,offset,length,position){var contents=stream.node.contents;if(position>=contents.length)return 0;var size=Math.min(contents.length-position,length);if(contents.slice){for(var i=0;i{FS.forceLoadFile(node);return writeChunks(stream,buffer,offset,length,position)};stream_ops.mmap=(stream,length,position,prot,flags)=>{FS.forceLoadFile(node);var ptr=mmapAlloc(length);if(!ptr){throw new FS.ErrnoError(48)}writeChunks(stream,HEAP8,ptr,length,position);return{ptr,allocated:true}};node.stream_ops=stream_ops;return node}};var UTF8ToString=(ptr,maxBytesToRead)=>{ptr>>>=0;return ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):""};var SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(dirfd,path,allowEmpty){if(PATH.isAbs(path)){return path}var dir;if(dirfd===-100){dir=FS.cwd()}else{var dirstream=SYSCALLS.getStreamFromFD(dirfd);dir=dirstream.path}if(path.length==0){if(!allowEmpty){throw new FS.ErrnoError(44)}return dir}return dir+"/"+path},doStat(func,path,buf){var stat=func(path);HEAP32[buf>>>2>>>0]=stat.dev;HEAP32[buf+4>>>2>>>0]=stat.mode;HEAPU32[buf+8>>>2>>>0]=stat.nlink;HEAP32[buf+12>>>2>>>0]=stat.uid;HEAP32[buf+16>>>2>>>0]=stat.gid;HEAP32[buf+20>>>2>>>0]=stat.rdev;tempI64=[stat.size>>>0,(tempDouble=stat.size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+24>>>2>>>0]=tempI64[0],HEAP32[buf+28>>>2>>>0]=tempI64[1];HEAP32[buf+32>>>2>>>0]=4096;HEAP32[buf+36>>>2>>>0]=stat.blocks;var atime=stat.atime.getTime();var mtime=stat.mtime.getTime();var ctime=stat.ctime.getTime();tempI64=[Math.floor(atime/1e3)>>>0,(tempDouble=Math.floor(atime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+40>>>2>>>0]=tempI64[0],HEAP32[buf+44>>>2>>>0]=tempI64[1];HEAPU32[buf+48>>>2>>>0]=atime%1e3*1e3*1e3;tempI64=[Math.floor(mtime/1e3)>>>0,(tempDouble=Math.floor(mtime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+56>>>2>>>0]=tempI64[0],HEAP32[buf+60>>>2>>>0]=tempI64[1];HEAPU32[buf+64>>>2>>>0]=mtime%1e3*1e3*1e3;tempI64=[Math.floor(ctime/1e3)>>>0,(tempDouble=Math.floor(ctime/1e3),+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+72>>>2>>>0]=tempI64[0],HEAP32[buf+76>>>2>>>0]=tempI64[1];HEAPU32[buf+80>>>2>>>0]=ctime%1e3*1e3*1e3;tempI64=[stat.ino>>>0,(tempDouble=stat.ino,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[buf+88>>>2>>>0]=tempI64[0],HEAP32[buf+92>>>2>>>0]=tempI64[1];return 0},doMsync(addr,stream,len,flags,offset){if(!FS.isFile(stream.node.mode)){throw new FS.ErrnoError(43)}if(flags&2){return 0}var buffer=HEAPU8.slice(addr,addr+len);FS.msync(stream,buffer,offset,len,flags)},getStreamFromFD(fd){var stream=FS.getStreamChecked(fd);return stream},varargs:undefined,getStr(ptr){var ret=UTF8ToString(ptr);return ret}};function ___syscall_faccessat(dirfd,path,amode,flags){path>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(amode&~7){return-28}var lookup=FS.lookupPath(path,{follow:true});var node=lookup.node;if(!node){return-44}var perms="";if(amode&4)perms+="r";if(amode&2)perms+="w";if(amode&1)perms+="x";if(perms&&FS.nodePermissions(node,perms)){return-2}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var syscallGetVarargI=()=>{var ret=HEAP32[+SYSCALLS.varargs>>>2>>>0];SYSCALLS.varargs+=4;return ret};var syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(fd,cmd,varargs){varargs>>>=0;SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(cmd){case 0:{var arg=syscallGetVarargI();if(arg<0){return-28}while(FS.streams[arg]){arg++}var newStream;newStream=FS.dupStream(stream,arg);return newStream.fd}case 1:case 2:return 0;case 3:return stream.flags;case 4:{var arg=syscallGetVarargI();stream.flags|=arg;return 0}case 12:{var arg=syscallGetVarargP();var offset=0;HEAP16[arg+offset>>>1>>>0]=2;return 0}case 13:case 14:return 0}return-28}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_fstat64(fd,buf){buf>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);return SYSCALLS.doStat(FS.stat,stream.path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ftruncate64(fd,length_low,length_high){var length=convertI32PairToI53Checked(length_low,length_high);try{if(isNaN(length))return 61;FS.ftruncate(fd,length);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);function ___syscall_getcwd(buf,size){buf>>>=0;size>>>=0;try{if(size===0)return-28;var cwd=FS.cwd();var cwdLengthInBytes=lengthBytesUTF8(cwd)+1;if(size>>=0;count>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);stream.getdents||=FS.readdir(stream.path);var struct_size=280;var pos=0;var off=FS.llseek(stream,0,1);var startIdx=Math.floor(off/struct_size);var endIdx=Math.min(stream.getdents.length,startIdx+Math.floor(count/struct_size));for(var idx=startIdx;idx>>0,(tempDouble=id,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos>>>2>>>0]=tempI64[0],HEAP32[dirp+pos+4>>>2>>>0]=tempI64[1];tempI64=[(idx+1)*struct_size>>>0,(tempDouble=(idx+1)*struct_size,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[dirp+pos+8>>>2>>>0]=tempI64[0],HEAP32[dirp+pos+12>>>2>>>0]=tempI64[1];HEAP16[dirp+pos+16>>>1>>>0]=280;HEAP8[dirp+pos+18>>>0]=type;stringToUTF8(name,dirp+pos+19,256);pos+=struct_size}FS.llseek(stream,idx*struct_size,0);return pos}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_ioctl(fd,op,varargs){varargs>>>=0;SYSCALLS.varargs=varargs;try{var stream=SYSCALLS.getStreamFromFD(fd);switch(op){case 21509:{if(!stream.tty)return-59;return 0}case 21505:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcgets){var termios=stream.tty.ops.ioctl_tcgets(stream);var argp=syscallGetVarargP();HEAP32[argp>>>2>>>0]=termios.c_iflag||0;HEAP32[argp+4>>>2>>>0]=termios.c_oflag||0;HEAP32[argp+8>>>2>>>0]=termios.c_cflag||0;HEAP32[argp+12>>>2>>>0]=termios.c_lflag||0;for(var i=0;i<32;i++){HEAP8[argp+i+17>>>0]=termios.c_cc[i]||0}return 0}return 0}case 21510:case 21511:case 21512:{if(!stream.tty)return-59;return 0}case 21506:case 21507:case 21508:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tcsets){var argp=syscallGetVarargP();var c_iflag=HEAP32[argp>>>2>>>0];var c_oflag=HEAP32[argp+4>>>2>>>0];var c_cflag=HEAP32[argp+8>>>2>>>0];var c_lflag=HEAP32[argp+12>>>2>>>0];var c_cc=[];for(var i=0;i<32;i++){c_cc.push(HEAP8[argp+i+17>>>0])}return stream.tty.ops.ioctl_tcsets(stream.tty,op,{c_iflag,c_oflag,c_cflag,c_lflag,c_cc})}return 0}case 21519:{if(!stream.tty)return-59;var argp=syscallGetVarargP();HEAP32[argp>>>2>>>0]=0;return 0}case 21520:{if(!stream.tty)return-59;return-28}case 21531:{var argp=syscallGetVarargP();return FS.ioctl(stream,op,argp)}case 21523:{if(!stream.tty)return-59;if(stream.tty.ops.ioctl_tiocgwinsz){var winsize=stream.tty.ops.ioctl_tiocgwinsz(stream.tty);var argp=syscallGetVarargP();HEAP16[argp>>>1>>>0]=winsize[0];HEAP16[argp+2>>>1>>>0]=winsize[1]}return 0}case 21524:{if(!stream.tty)return-59;return 0}case 21515:{if(!stream.tty)return-59;return 0}default:return-28}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_lstat64(path,buf){path>>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.lstat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_mkdirat(dirfd,path,mode){path>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);FS.mkdir(path,mode,0);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_newfstatat(dirfd,path,buf,flags){path>>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);var nofollow=flags&256;var allowEmpty=flags&4096;flags=flags&~6400;path=SYSCALLS.calculateAt(dirfd,path,allowEmpty);return SYSCALLS.doStat(nofollow?FS.lstat:FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_openat(dirfd,path,flags,varargs){path>>>=0;varargs>>>=0;SYSCALLS.varargs=varargs;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);var mode=varargs?syscallGetVarargI():0;return FS.open(path,flags,mode).fd}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_readlinkat(dirfd,path,buf,bufsize){path>>>=0;buf>>>=0;bufsize>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(bufsize<=0)return-28;var ret=FS.readlink(path);var len=Math.min(bufsize,lengthBytesUTF8(ret));var endChar=HEAP8[buf+len>>>0];stringToUTF8(ret,buf,bufsize+1);HEAP8[buf+len>>>0]=endChar;return len}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_rmdir(path){path>>>=0;try{path=SYSCALLS.getStr(path);FS.rmdir(path);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var SOCKFS={websocketArgs:{},callbacks:{},on(event,callback){SOCKFS.callbacks[event]=callback},emit(event,param){SOCKFS.callbacks[event]?.(param)},mount(mount){SOCKFS.websocketArgs=Module["websocket"]||{};(Module["websocket"]??={})["on"]=SOCKFS.on;return FS.createNode(null,"/",16895,0)},createSocket(family,type,protocol){type&=~526336;var streaming=type==1;if(streaming&&protocol&&protocol!=6){throw new FS.ErrnoError(66)}var sock={family,type,protocol,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops};var name=SOCKFS.nextname();var node=FS.createNode(SOCKFS.root,name,49152,0);node.sock=sock;var stream=FS.createStream({path:name,node,flags:2,seekable:false,stream_ops:SOCKFS.stream_ops});sock.stream=stream;return sock},getSocket(fd){var stream=FS.getStream(fd);if(!stream||!FS.isSocket(stream.node.mode)){return null}return stream.node.sock},stream_ops:{poll(stream){var sock=stream.node.sock;return sock.sock_ops.poll(sock)},ioctl(stream,request,varargs){var sock=stream.node.sock;return sock.sock_ops.ioctl(sock,request,varargs)},read(stream,buffer,offset,length,position){var sock=stream.node.sock;var msg=sock.sock_ops.recvmsg(sock,length);if(!msg){return 0}buffer.set(msg.buffer,offset);return msg.buffer.length},write(stream,buffer,offset,length,position){var sock=stream.node.sock;return sock.sock_ops.sendmsg(sock,buffer,offset,length)},close(stream){var sock=stream.node.sock;sock.sock_ops.close(sock)}},nextname(){if(!SOCKFS.nextname.current){SOCKFS.nextname.current=0}return`socket[${SOCKFS.nextname.current++}]`},websocket_sock_ops:{createPeer(sock,addr,port){var ws;if(typeof addr=="object"){ws=addr;addr=null;port=null}if(ws){if(ws._socket){addr=ws._socket.remoteAddress;port=ws._socket.remotePort}else{var result=/ws[s]?:\/\/([^:]+):(\d+)/.exec(ws.url);if(!result){throw new Error("WebSocket URL must be in the format ws(s)://address:port")}addr=result[1];port=parseInt(result[2],10)}}else{try{var url="ws:#".replace("#","//");var subProtocols="binary";var opts=undefined;if(SOCKFS.websocketArgs["url"]){url=SOCKFS.websocketArgs["url"]}if(SOCKFS.websocketArgs["subprotocol"]){subProtocols=SOCKFS.websocketArgs["subprotocol"]}else if(SOCKFS.websocketArgs["subprotocol"]===null){subProtocols="null"}if(url==="ws://"||url==="wss://"){var parts=addr.split("/");url=url+parts[0]+":"+port+"/"+parts.slice(1).join("/")}if(subProtocols!=="null"){subProtocols=subProtocols.replace(/^ +| +$/g,"").split(/ *, */);opts=subProtocols}var WebSocketConstructor;if(ENVIRONMENT_IS_NODE){WebSocketConstructor=require("ws")}else{WebSocketConstructor=WebSocket}ws=new WebSocketConstructor(url,opts);ws.binaryType="arraybuffer"}catch(e){throw new FS.ErrnoError(23)}}var peer={addr,port,socket:ws,msg_send_queue:[]};SOCKFS.websocket_sock_ops.addPeer(sock,peer);SOCKFS.websocket_sock_ops.handlePeerEvents(sock,peer);if(sock.type===2&&typeof sock.sport!="undefined"){peer.msg_send_queue.push(new Uint8Array([255,255,255,255,"p".charCodeAt(0),"o".charCodeAt(0),"r".charCodeAt(0),"t".charCodeAt(0),(sock.sport&65280)>>8,sock.sport&255]))}return peer},getPeer(sock,addr,port){return sock.peers[addr+":"+port]},addPeer(sock,peer){sock.peers[peer.addr+":"+peer.port]=peer},removePeer(sock,peer){delete sock.peers[peer.addr+":"+peer.port]},handlePeerEvents(sock,peer){var first=true;var handleOpen=function(){sock.connecting=false;SOCKFS.emit("open",sock.stream.fd);try{var queued=peer.msg_send_queue.shift();while(queued){peer.socket.send(queued);queued=peer.msg_send_queue.shift()}}catch(e){peer.socket.close()}};function handleMessage(data){if(typeof data=="string"){var encoder=new TextEncoder;data=encoder.encode(data)}else{assert(data.byteLength!==undefined);if(data.byteLength==0){return}data=new Uint8Array(data)}var wasfirst=first;first=false;if(wasfirst&&data.length===10&&data[0]===255&&data[1]===255&&data[2]===255&&data[3]===255&&data[4]==="p".charCodeAt(0)&&data[5]==="o".charCodeAt(0)&&data[6]==="r".charCodeAt(0)&&data[7]==="t".charCodeAt(0)){var newport=data[8]<<8|data[9];SOCKFS.websocket_sock_ops.removePeer(sock,peer);peer.port=newport;SOCKFS.websocket_sock_ops.addPeer(sock,peer);return}sock.recv_queue.push({addr:peer.addr,port:peer.port,data});SOCKFS.emit("message",sock.stream.fd)}if(ENVIRONMENT_IS_NODE){peer.socket.on("open",handleOpen);peer.socket.on("message",function(data,isBinary){if(!isBinary){return}handleMessage(new Uint8Array(data).buffer)});peer.socket.on("close",function(){SOCKFS.emit("close",sock.stream.fd)});peer.socket.on("error",function(error){sock.error=14;SOCKFS.emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])})}else{peer.socket.onopen=handleOpen;peer.socket.onclose=function(){SOCKFS.emit("close",sock.stream.fd)};peer.socket.onmessage=function peer_socket_onmessage(event){handleMessage(event.data)};peer.socket.onerror=function(error){sock.error=14;SOCKFS.emit("error",[sock.stream.fd,sock.error,"ECONNREFUSED: Connection refused"])}}},poll(sock){if(sock.type===1&&sock.server){return sock.pending.length?64|1:0}var mask=0;var dest=sock.type===1?SOCKFS.websocket_sock_ops.getPeer(sock,sock.daddr,sock.dport):null;if(sock.recv_queue.length||!dest||dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){mask|=64|1}if(!dest||dest&&dest.socket.readyState===dest.socket.OPEN){mask|=4}if(dest&&dest.socket.readyState===dest.socket.CLOSING||dest&&dest.socket.readyState===dest.socket.CLOSED){if(sock.connecting){mask|=4}else{mask|=16}}return mask},ioctl(sock,request,arg){switch(request){case 21531:var bytes=0;if(sock.recv_queue.length){bytes=sock.recv_queue[0].data.length}HEAP32[arg>>>2>>>0]=bytes;return 0;default:return 28}},close(sock){if(sock.server){try{sock.server.close()}catch(e){}sock.server=null}var peers=Object.keys(sock.peers);for(var i=0;i>>=0;buf>>>=0;try{path=SYSCALLS.getStr(path);return SYSCALLS.doStat(FS.stat,path,buf)}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function ___syscall_unlinkat(dirfd,path,flags){path>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path);if(flags===0){FS.unlink(path)}else if(flags===512){FS.rmdir(path)}else{abort("Invalid flags passed to unlinkat")}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var readI53FromI64=ptr=>HEAPU32[ptr>>>2>>>0]+HEAP32[ptr+4>>>2>>>0]*4294967296;function ___syscall_utimensat(dirfd,path,times,flags){path>>>=0;times>>>=0;try{path=SYSCALLS.getStr(path);path=SYSCALLS.calculateAt(dirfd,path,true);var now=Date.now(),atime,mtime;if(!times){atime=now;mtime=now}else{var seconds=readI53FromI64(times);var nanoseconds=HEAP32[times+8>>>2>>>0];if(nanoseconds==1073741823){atime=now}else if(nanoseconds==1073741822){atime=null}else{atime=seconds*1e3+nanoseconds/(1e3*1e3)}times+=16;seconds=readI53FromI64(times);nanoseconds=HEAP32[times+8>>>2>>>0];if(nanoseconds==1073741823){mtime=now}else if(nanoseconds==1073741822){mtime=null}else{mtime=seconds*1e3+nanoseconds/(1e3*1e3)}}if((mtime??atime)!==null){FS.utime(path,atime,mtime)}return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var __abort_js=()=>abort("");function __emscripten_memcpy_js(dest,src,num){dest>>>=0;src>>>=0;num>>>=0;return HEAPU8.copyWithin(dest>>>0,src>>>0,src+num>>>0)}var runtimeKeepaliveCounter=0;var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=false;runtimeKeepaliveCounter=0};var __emscripten_throw_longjmp=()=>{throw Infinity};function __gmtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);tmPtr>>>=0;var date=new Date(time*1e3);HEAP32[tmPtr>>>2>>>0]=date.getUTCSeconds();HEAP32[tmPtr+4>>>2>>>0]=date.getUTCMinutes();HEAP32[tmPtr+8>>>2>>>0]=date.getUTCHours();HEAP32[tmPtr+12>>>2>>>0]=date.getUTCDate();HEAP32[tmPtr+16>>>2>>>0]=date.getUTCMonth();HEAP32[tmPtr+20>>>2>>>0]=date.getUTCFullYear()-1900;HEAP32[tmPtr+24>>>2>>>0]=date.getUTCDay();var start=Date.UTC(date.getUTCFullYear(),0,1,0,0,0,0);var yday=(date.getTime()-start)/(1e3*60*60*24)|0;HEAP32[tmPtr+28>>>2>>>0]=yday}var isLeapYear=year=>year%4===0&&(year%100!==0||year%400===0);var MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335];var MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334];var ydayFromDate=date=>{var leap=isLeapYear(date.getFullYear());var monthDaysCumulative=leap?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE;var yday=monthDaysCumulative[date.getMonth()]+date.getDate()-1;return yday};function __localtime_js(time_low,time_high,tmPtr){var time=convertI32PairToI53Checked(time_low,time_high);tmPtr>>>=0;var date=new Date(time*1e3);HEAP32[tmPtr>>>2>>>0]=date.getSeconds();HEAP32[tmPtr+4>>>2>>>0]=date.getMinutes();HEAP32[tmPtr+8>>>2>>>0]=date.getHours();HEAP32[tmPtr+12>>>2>>>0]=date.getDate();HEAP32[tmPtr+16>>>2>>>0]=date.getMonth();HEAP32[tmPtr+20>>>2>>>0]=date.getFullYear()-1900;HEAP32[tmPtr+24>>>2>>>0]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>>2>>>0]=yday;HEAP32[tmPtr+36>>>2>>>0]=-(date.getTimezoneOffset()*60);var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dst=(summerOffset!=winterOffset&&date.getTimezoneOffset()==Math.min(winterOffset,summerOffset))|0;HEAP32[tmPtr+32>>>2>>>0]=dst}var setTempRet0=val=>__emscripten_tempret_set(val);var __mktime_js=function(tmPtr){tmPtr>>>=0;var ret=(()=>{var date=new Date(HEAP32[tmPtr+20>>>2>>>0]+1900,HEAP32[tmPtr+16>>>2>>>0],HEAP32[tmPtr+12>>>2>>>0],HEAP32[tmPtr+8>>>2>>>0],HEAP32[tmPtr+4>>>2>>>0],HEAP32[tmPtr>>>2>>>0],0);var dst=HEAP32[tmPtr+32>>>2>>>0];var guessedOffset=date.getTimezoneOffset();var start=new Date(date.getFullYear(),0,1);var summerOffset=new Date(date.getFullYear(),6,1).getTimezoneOffset();var winterOffset=start.getTimezoneOffset();var dstOffset=Math.min(winterOffset,summerOffset);if(dst<0){HEAP32[tmPtr+32>>>2>>>0]=Number(summerOffset!=winterOffset&&dstOffset==guessedOffset)}else if(dst>0!=(dstOffset==guessedOffset)){var nonDstOffset=Math.max(winterOffset,summerOffset);var trueOffset=dst>0?dstOffset:nonDstOffset;date.setTime(date.getTime()+(trueOffset-guessedOffset)*6e4)}HEAP32[tmPtr+24>>>2>>>0]=date.getDay();var yday=ydayFromDate(date)|0;HEAP32[tmPtr+28>>>2>>>0]=yday;HEAP32[tmPtr>>>2>>>0]=date.getSeconds();HEAP32[tmPtr+4>>>2>>>0]=date.getMinutes();HEAP32[tmPtr+8>>>2>>>0]=date.getHours();HEAP32[tmPtr+12>>>2>>>0]=date.getDate();HEAP32[tmPtr+16>>>2>>>0]=date.getMonth();HEAP32[tmPtr+20>>>2>>>0]=date.getYear();var timeMs=date.getTime();if(isNaN(timeMs)){return-1}return timeMs/1e3})();return setTempRet0((tempDouble=ret,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)),ret>>>0};function __mmap_js(len,prot,flags,fd,offset_low,offset_high,allocated,addr){len>>>=0;var offset=convertI32PairToI53Checked(offset_low,offset_high);allocated>>>=0;addr>>>=0;try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);var res=FS.mmap(stream,len,offset,prot,flags);var ptr=res.ptr;HEAP32[allocated>>>2>>>0]=res.allocated;HEAPU32[addr>>>2>>>0]=ptr;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}function __munmap_js(addr,len,prot,flags,fd,offset_low,offset_high){addr>>>=0;len>>>=0;var offset=convertI32PairToI53Checked(offset_low,offset_high);try{var stream=SYSCALLS.getStreamFromFD(fd);if(prot&2){SYSCALLS.doMsync(addr,stream,len,flags,offset)}}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return-e.errno}}var timers={};var handleException=e=>{if(e instanceof ExitStatus||e=="unwind"){return EXITSTATUS}quit_(1,e)};var keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0;var _proc_exit=code=>{EXITSTATUS=code;if(!keepRuntimeAlive()){Module["onExit"]?.(code);ABORT=true}quit_(code,new ExitStatus(code))};var exitJS=(status,implicit)=>{EXITSTATUS=status;_proc_exit(status)};var _exit=exitJS;var maybeExit=()=>{if(!keepRuntimeAlive()){try{_exit(EXITSTATUS)}catch(e){handleException(e)}}};var callUserCallback=func=>{if(ABORT){return}try{func();maybeExit()}catch(e){handleException(e)}};var _emscripten_get_now=()=>performance.now();var __setitimer_js=(which,timeout_ms)=>{if(timers[which]){clearTimeout(timers[which].id);delete timers[which]}if(!timeout_ms)return 0;var id=setTimeout(()=>{delete timers[which];callUserCallback(()=>__emscripten_timeout(which,_emscripten_get_now()))},timeout_ms);timers[which]={id,timeout_ms};return 0};var __tzset_js=function(timezone,daylight,std_name,dst_name){timezone>>>=0;daylight>>>=0;std_name>>>=0;dst_name>>>=0;var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>>2>>>0]=stdTimezoneOffset*60;HEAP32[daylight>>>2>>>0]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffsetDate.now();var nowIsMonotonic=1;var checkWasiClock=clock_id=>clock_id>=0&&clock_id<=3;function _clock_time_get(clk_id,ignored_precision_low,ignored_precision_high,ptime){var ignored_precision=convertI32PairToI53Checked(ignored_precision_low,ignored_precision_high);ptime>>>=0;if(!checkWasiClock(clk_id)){return 28}var now;if(clk_id===0){now=_emscripten_date_now()}else if(nowIsMonotonic){now=_emscripten_get_now()}else{return 52}var nsec=Math.round(now*1e3*1e3);tempI64=[nsec>>>0,(tempDouble=nsec,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[ptime>>>2>>>0]=tempI64[0],HEAP32[ptime+4>>>2>>>0]=tempI64[1];return 0}var getHeapMax=()=>4294901760;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};function _emscripten_resize_heap(requestedSize){requestedSize>>>=0;var oldSize=HEAPU8.length;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false}var ENV={};var getExecutableName=()=>thisProgram||"./this.program";var getEnvStrings=()=>{if(!getEnvStrings.strings){var lang=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8";var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:lang,_:getExecutableName()};for(var x in ENV){if(ENV[x]===undefined)delete env[x];else env[x]=ENV[x]}var strings=[];for(var x in env){strings.push(`${x}=${env[x]}`)}getEnvStrings.strings=strings}return getEnvStrings.strings};var stringToAscii=(str,buffer)=>{for(var i=0;i>>0]=str.charCodeAt(i)}HEAP8[buffer>>>0]=0};var _environ_get=function(__environ,environ_buf){__environ>>>=0;environ_buf>>>=0;var bufSize=0;getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;HEAPU32[__environ+i*4>>>2>>>0]=ptr;stringToAscii(string,ptr);bufSize+=string.length+1});return 0};var _environ_sizes_get=function(penviron_count,penviron_buf_size){penviron_count>>>=0;penviron_buf_size>>>=0;var strings=getEnvStrings();HEAPU32[penviron_count>>>2>>>0]=strings.length;var bufSize=0;strings.forEach(string=>bufSize+=string.length+1);HEAPU32[penviron_buf_size>>>2>>>0]=bufSize;return 0};function _fd_close(fd){try{var stream=SYSCALLS.getStreamFromFD(fd);FS.close(stream);return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doReadv=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>>2>>>0];var len=HEAPU32[iov+4>>>2>>>0];iov+=8;var curr=FS.read(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>>=0;iovcnt>>>=0;pnum>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doReadv(stream,iov,iovcnt);HEAPU32[pnum>>>2>>>0]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}function _fd_seek(fd,offset_low,offset_high,whence,newOffset){var offset=convertI32PairToI53Checked(offset_low,offset_high);newOffset>>>=0;try{if(isNaN(offset))return 61;var stream=SYSCALLS.getStreamFromFD(fd);FS.llseek(stream,offset,whence);tempI64=[stream.position>>>0,(tempDouble=stream.position,+Math.abs(tempDouble)>=1?tempDouble>0?+Math.floor(tempDouble/4294967296)>>>0:~~+Math.ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[newOffset>>>2>>>0]=tempI64[0],HEAP32[newOffset+4>>>2>>>0]=tempI64[1];if(stream.getdents&&offset===0&&whence===0)stream.getdents=null;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var doWritev=(stream,iov,iovcnt,offset)=>{var ret=0;for(var i=0;i>>2>>>0];var len=HEAPU32[iov+4>>>2>>>0];iov+=8;var curr=FS.write(stream,HEAP8,ptr,len,offset);if(curr<0)return-1;ret+=curr;if(curr>>=0;iovcnt>>>=0;pnum>>>=0;try{var stream=SYSCALLS.getStreamFromFD(fd);var num=doWritev(stream,iov,iovcnt);HEAPU32[pnum>>>2>>>0]=num;return 0}catch(e){if(typeof FS=="undefined"||!(e.name==="ErrnoError"))throw e;return e.errno}}var stackAlloc=sz=>__emscripten_stack_alloc(sz);var stringToUTF8OnStack=str=>{var size=lengthBytesUTF8(str)+1;var ret=stackAlloc(size);stringToUTF8(str,ret,size);return ret};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var getCFunc=ident=>{var func=Module["_"+ident];return func};var writeArrayToMemory=(array,buffer)=>{HEAP8.set(array,buffer>>>0)};var ccall=(ident,returnType,argTypes,args,opts)=>{var toC={string:str=>{var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=stringToUTF8OnStack(str)}return ret},array:arr=>{var ret=stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}};function convertReturnValue(ret){if(returnType==="string"){return UTF8ToString(ret)}if(returnType==="boolean")return Boolean(ret);return ret}var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i{var numericArgs=!argTypes||argTypes.every(type=>type==="number"||type==="boolean");var numericRet=returnType!=="string";if(numericRet&&numericArgs&&!opts){return getCFunc(ident)}return(...args)=>ccall(ident,returnType,argTypes,args,opts)};var FS_createPath=FS.createPath;var FS_unlink=path=>FS.unlink(path);var FS_createLazyFile=FS.createLazyFile;var FS_createDevice=FS.createDevice;FS.createPreloadedFile=FS_createPreloadedFile;FS.staticInit();Module["FS_createPath"]=FS.createPath;Module["FS_createDataFile"]=FS.createDataFile;Module["FS_createPreloadedFile"]=FS.createPreloadedFile;Module["FS_unlink"]=FS.unlink;Module["FS_createLazyFile"]=FS.createLazyFile;Module["FS_createDevice"]=FS.createDevice;MEMFS.doesNotExistError=new FS.ErrnoError(44);MEMFS.doesNotExistError.stack="";if(ENVIRONMENT_IS_NODE){NODEFS.staticInit()}var wasmImports={a:___cxa_throw,B:___syscall_faccessat,m:___syscall_fcntl64,ca:___syscall_fstat64,K:___syscall_ftruncate64,_:___syscall_getcwd,W:___syscall_getdents64,r:___syscall_ioctl,aa:___syscall_lstat64,X:___syscall_mkdirat,$:___syscall_newfstatat,z:___syscall_openat,V:___syscall_readlinkat,U:___syscall_rmdir,R:___syscall_socket,ba:___syscall_stat64,y:___syscall_unlinkat,T:___syscall_utimensat,C:__abort_js,da:__emscripten_memcpy_js,P:__emscripten_runtime_keepalive_clear,N:__emscripten_throw_longjmp,G:__gmtime_js,H:__localtime_js,I:__mktime_js,E:__mmap_js,F:__munmap_js,Q:__setitimer_js,D:__tzset_js,L:_clock_time_get,A:_emscripten_date_now,s:_emscripten_get_now,S:_emscripten_resize_heap,Y:_environ_get,Z:_environ_sizes_get,k:_exit,o:_fd_close,u:_fd_read,J:_fd_seek,t:_fd_write,x:invoke_di,l:invoke_i,f:invoke_ii,c:invoke_iii,d:invoke_iiii,j:invoke_iiiii,i:invoke_iiiiii,p:invoke_iiiiiii,n:invoke_v,b:invoke_vi,e:invoke_vii,w:invoke_viid,g:invoke_viii,h:invoke_viiii,M:invoke_viiiii,v:invoke_viiiiii,q:invoke_viiiiiiii,O:_proc_exit};var wasmExports;createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["fa"])();var _unpack_error_what=Module["_unpack_error_what"]=a0=>(_unpack_error_what=Module["_unpack_error_what"]=wasmExports["ga"])(a0);var _main=Module["_main"]=(a0,a1)=>(_main=Module["_main"]=wasmExports["ha"])(a0,a1);var _itkPNGWriteErrorFunction=Module["_itkPNGWriteErrorFunction"]=(a0,a1)=>(_itkPNGWriteErrorFunction=Module["_itkPNGWriteErrorFunction"]=wasmExports["ia"])(a0,a1);var _itkPNGWriteWarningFunction=Module["_itkPNGWriteWarningFunction"]=(a0,a1)=>(_itkPNGWriteWarningFunction=Module["_itkPNGWriteWarningFunction"]=wasmExports["ja"])(a0,a1);var _itk_wasm_input_array_alloc=Module["_itk_wasm_input_array_alloc"]=(a0,a1,a2,a3)=>(_itk_wasm_input_array_alloc=Module["_itk_wasm_input_array_alloc"]=wasmExports["ka"])(a0,a1,a2,a3);var _itk_wasm_input_json_alloc=Module["_itk_wasm_input_json_alloc"]=(a0,a1,a2)=>(_itk_wasm_input_json_alloc=Module["_itk_wasm_input_json_alloc"]=wasmExports["la"])(a0,a1,a2);var _itk_wasm_output_json_address=Module["_itk_wasm_output_json_address"]=(a0,a1)=>(_itk_wasm_output_json_address=Module["_itk_wasm_output_json_address"]=wasmExports["ma"])(a0,a1);var _itk_wasm_output_json_size=Module["_itk_wasm_output_json_size"]=(a0,a1)=>(_itk_wasm_output_json_size=Module["_itk_wasm_output_json_size"]=wasmExports["na"])(a0,a1);var _itk_wasm_output_array_address=Module["_itk_wasm_output_array_address"]=(a0,a1,a2)=>(_itk_wasm_output_array_address=Module["_itk_wasm_output_array_address"]=wasmExports["oa"])(a0,a1,a2);var _itk_wasm_output_array_size=Module["_itk_wasm_output_array_size"]=(a0,a1,a2)=>(_itk_wasm_output_array_size=Module["_itk_wasm_output_array_size"]=wasmExports["pa"])(a0,a1,a2);var _itk_wasm_free_all=Module["_itk_wasm_free_all"]=()=>(_itk_wasm_free_all=Module["_itk_wasm_free_all"]=wasmExports["qa"])();var _emscripten_builtin_memalign=(a0,a1)=>(_emscripten_builtin_memalign=wasmExports["sa"])(a0,a1);var __emscripten_timeout=(a0,a1)=>(__emscripten_timeout=wasmExports["ta"])(a0,a1);var _setThrew=(a0,a1)=>(_setThrew=wasmExports["ua"])(a0,a1);var __emscripten_tempret_set=a0=>(__emscripten_tempret_set=wasmExports["va"])(a0);var __emscripten_stack_restore=a0=>(__emscripten_stack_restore=wasmExports["wa"])(a0);var __emscripten_stack_alloc=a0=>(__emscripten_stack_alloc=wasmExports["xa"])(a0);var _emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports["ya"])();function invoke_ii(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_v(index){var sp=stackSave();try{getWasmTableEntry(index)()}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_i(index){var sp=stackSave();try{return getWasmTableEntry(index)()}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_di(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viid(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(e!==e+0)throw e;_setThrew(1,0)}}function applySignatureConversions(wasmExports){wasmExports=Object.assign({},wasmExports);var makeWrapper_ppp=f=>(a0,a1)=>f(a0,a1)>>>0;var makeWrapper_pp=f=>a0=>f(a0)>>>0;var makeWrapper_p=f=>()=>f()>>>0;wasmExports["sa"]=makeWrapper_ppp(wasmExports["sa"]);wasmExports["xa"]=makeWrapper_pp(wasmExports["xa"]);wasmExports["ya"]=makeWrapper_p(wasmExports["ya"]);return wasmExports}Module["addRunDependency"]=addRunDependency;Module["removeRunDependency"]=removeRunDependency;Module["callMain"]=callMain;Module["stackSave"]=stackSave;Module["stackRestore"]=stackRestore;Module["ccall"]=ccall;Module["cwrap"]=cwrap;Module["UTF8ToString"]=UTF8ToString;Module["stringToUTF8"]=stringToUTF8;Module["lengthBytesUTF8"]=lengthBytesUTF8;Module["writeArrayToMemory"]=writeArrayToMemory;Module["FS_createPreloadedFile"]=FS_createPreloadedFile;Module["FS_unlink"]=FS_unlink;Module["FS_createPath"]=FS_createPath;Module["FS_createDevice"]=FS_createDevice;Module["FS_createDataFile"]=FS_createDataFile;Module["FS_createLazyFile"]=FS_createLazyFile;var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function callMain(args=[]){var entryFunction=_main;args.unshift(thisProgram);var argc=args.length;var argv=stackAlloc((argc+1)*4);var argv_ptr=argv;args.forEach(arg=>{HEAPU32[argv_ptr>>>2>>>0]=stringToUTF8OnStack(arg);argv_ptr+=4});HEAPU32[argv_ptr>>>2>>>0]=0;try{var ret=entryFunction(argc,argv);exitJS(ret,true);return ret}catch(e){return handleException(e)}}function run(args=arguments_){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();preMain();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();if(shouldRunNow)callMain(args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(()=>{setTimeout(()=>Module["setStatus"](""),1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=false;if(Module["noInitialRun"])shouldRunNow=false;run();Module.mountContainingDir=function(filePath){if(!ENVIRONMENT_IS_NODE){return}var path=require("path");var containingDir=path.dirname(filePath);if(containingDir==="/"){throw new Error("Cannot mount root directory")}var currentDir="/";var splitContainingDir=containingDir.split(path.sep);for(var ii=1;ii - Array.from({ length: size }, (_, i) => (value >>> (8 * i)) & 0xff); - -/** - * One data element, in explicit VR little endian. A string of odd length is - * padded with a NUL, as a UID is. - */ -function dicomElement( - group: number, - element: number, - vr: string, - value: string | number[] -) { - const bytes = - typeof value === 'string' - ? new TextEncoder().encode(value.length % 2 ? `${value}\0` : value) - : new Uint8Array(value); - const longLength = vr === 'OB' || vr === 'OW'; - const header = new DataView(new ArrayBuffer(longLength ? 12 : 8)); - header.setUint16(0, group, true); - header.setUint16(2, element, true); - header.setUint8(4, vr.charCodeAt(0)); - header.setUint8(5, vr.charCodeAt(1)); - if (longLength) header.setUint32(8, bytes.length, true); - else header.setUint16(6, bytes.length, true); - return [new Uint8Array(header.buffer), bytes]; -} - -/** - * A DICOM image of one pixel: the smallest file the DICOM readers accept. - * Reading an empty file loads their WebAssembly modules too, but the tag - * reader then prints "Could not read the input DICOM file" to the console. - */ -function makePreloadDicom() { - const meta = [ - dicomElement(0x0002, 0x0002, 'UI', SECONDARY_CAPTURE_IMAGE_STORAGE), - dicomElement(0x0002, 0x0010, 'UI', EXPLICIT_VR_LITTLE_ENDIAN), - ].flat(); - const metaLength = meta.reduce((length, part) => length + part.length, 0); - const dataSet = [ - dicomElement(0x0008, 0x0016, 'UI', SECONDARY_CAPTURE_IMAGE_STORAGE), - dicomElement(0x0028, 0x0002, 'US', littleEndian(1, 2)), // samples per pixel - dicomElement(0x0028, 0x0004, 'CS', 'MONOCHROME2 '), - dicomElement(0x0028, 0x0010, 'US', littleEndian(1, 2)), // rows - dicomElement(0x0028, 0x0011, 'US', littleEndian(1, 2)), // columns - dicomElement(0x0028, 0x0100, 'US', littleEndian(16, 2)), // bits allocated - dicomElement(0x0028, 0x0101, 'US', littleEndian(16, 2)), // bits stored - dicomElement(0x0028, 0x0102, 'US', littleEndian(15, 2)), // high bit - dicomElement(0x0028, 0x0103, 'US', littleEndian(0, 2)), // unsigned - dicomElement(0x7fe0, 0x0010, 'OW', [0, 0]), // pixel data - ].flat(); - return new File( - [ - new Uint8Array(128), // preamble - 'DICM', - ...dicomElement(0x0002, 0x0000, 'UL', littleEndian(metaLength, 4)), - ...meta, - ...dataSet, - ], - 'preload.dcm' - ); -} - -export async function initItkWorker() { - await Promise.all([ensureWorker(), ensureDicomSeriesWorkerPool()]); - - // Loads the WebAssembly modules now, rather than on the first file. - const preloadFile = makePreloadDicom(); - try { - await readDicomTags(preloadFile); - } catch { - // ignore - } - try { - await readImage(preloadFile); - } catch { - // ignore - } -} diff --git a/src/io/magic.ts b/src/io/magic.ts index 0e5a91de7..6f61539c7 100644 --- a/src/io/magic.ts +++ b/src/io/magic.ts @@ -1,4 +1,4 @@ -import StreamingByteReader from '@/src/core/streaming/streamingByteReader'; +import StreamingByteReader from '@/src/dicom/core/header/streamingByteReader'; import { Maybe } from '../types'; interface MagicDatabase { diff --git a/src/io/zip.ts b/src/io/zip.ts index 25c85cea9..d710ab0f4 100644 --- a/src/io/zip.ts +++ b/src/io/zip.ts @@ -30,18 +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); - - 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/processing/engine/__tests__/mintInput.spec.ts b/src/processing/engine/__tests__/mintInput.spec.ts index 425c61bea..4a0ffbfef 100644 --- a/src/processing/engine/__tests__/mintInput.spec.ts +++ b/src/processing/engine/__tests__/mintInput.spec.ts @@ -1,7 +1,6 @@ import { describe, it, expect } from 'vitest'; import type { DataSource } from '@/src/io/import/dataSource'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { collectProvenanceUris, deriveFormat, @@ -21,31 +20,29 @@ const uriSource = (uri: string): DataSource => ({ name: uri.split('/').pop() ?? uri, }); -// `chunk` is never read by the mint, so a placeholder is cast in. -const dicomChunk = (uri: string): DataSource => +// `instance` is never read by the mint, so a placeholder is cast in. +const dicomInstance = (uri: string): DataSource => ({ - type: 'chunk', - chunk: undefined, - mime: FILE_EXT_TO_MIME.dcm, + type: 'dicom', + instance: undefined, parent: uriSource(uri), }) as unknown as DataSource; const dicomVolume = (uris: string[]): DataSource => ({ type: 'collection', - sources: uris.map(dicomChunk), + sources: uris.map(dicomInstance), }); -const localChunk = (): DataSource => +const localInstance = (): DataSource => ({ - type: 'chunk', - chunk: undefined, - mime: FILE_EXT_TO_MIME.dcm, + type: 'dicom', + instance: undefined, parent: { type: 'file', file: new File([], 'local.dcm'), fileType: '' }, }) as unknown as DataSource; const mixedProvenanceVolume = (uris: string[]): DataSource => ({ type: 'collection', - sources: [...uris.map(dicomChunk), localChunk()], + sources: [...uris.map(dicomInstance), localInstance()], }); const remoteFile = (uri: string, filename: string): DataSource => ({ diff --git a/src/processing/engine/mintInput.ts b/src/processing/engine/mintInput.ts index 858b76f1f..97e99d2a8 100644 --- a/src/processing/engine/mintInput.ts +++ b/src/processing/engine/mintInput.ts @@ -1,6 +1,5 @@ import type { DataSource } from '@/src/io/import/dataSource'; import { getDataSourceName } from '@/src/io/import/dataSource'; -import { FILE_EXT_TO_MIME } from '@/src/io/mimeTypes'; import { basename } from '@/src/utils/path'; import type { InputValue } from '@/backend-contract'; import { TYPE_TAG_IMAGE } from '@/backend-contract'; @@ -34,9 +33,7 @@ const lastExtension = (name: string | undefined): string | undefined => { export const deriveFormat = (ds: DataSource): string | undefined => { if (ds.type === 'collection') { - const isDicom = ds.sources.some( - (s) => s.type === 'chunk' && s.mime === FILE_EXT_TO_MIME.dcm - ); + const isDicom = ds.sources.some((s) => s.type === 'dicom'); return isDicom ? 'dicom-series' : undefined; } return ( diff --git a/src/segmentation/__tests__/artifactParentRestore.spec.ts b/src/segmentation/__tests__/artifactParentRestore.spec.ts index 5b509588d..891541883 100644 --- a/src/segmentation/__tests__/artifactParentRestore.spec.ts +++ b/src/segmentation/__tests__/artifactParentRestore.spec.ts @@ -1,3 +1,4 @@ +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; import { nextTick } from 'vue'; @@ -5,10 +6,13 @@ 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 { Chunk } from '@/src/core/streaming/chunk'; +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 DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; -import { Tags } from '@/src/core/dicomTags'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { useImageCacheStore } from '@/src/store/image-cache'; import { type LabelmapIO } from '@/src/segmentation/store'; import { useToolStore } from '@/src/store/tools'; @@ -84,7 +88,7 @@ const expectPartialRestore = ( expect(store().imageMasks('healthy')).toHaveLength(1); }; -// Real chunk loading and terminal status transitions, with only pixel decoding +// Real volume loading and terminal status transitions, with only pixel decoding // held at the IO seam so deletion/completion can occur during the restore. const pendingImage = async (id = 'parent') => { const decoded = defer(); @@ -100,34 +104,25 @@ const pendingImage = async (id = 'parent') => { [Tags.PixelRepresentation, '0'], [Tags.SamplesPerPixel, '1'], ] as Array<[string, string]>; - const chunk = new Chunk({ - metaLoader: { - meta, - metaBlob: new Blob(['meta']), - load: () => {}, - stop: () => {}, - }, - dataLoader: { data: new Blob(['pixels']), load: () => {}, stop: () => {} }, - }); - await chunk.loadMeta(); - await chunk.loadData(); - const image = new DicomChunkImage({ - splitAndSort: async (chunks) => ({ volume: chunks }), - readDicomImage: async () => { + const instance = instanceFor( + datasetFromTags(meta), + fromBlob(new Blob(['pixels'])) + ); + const runtime = createDicomRuntime( + decodingWith(async () => { started.resolve(); await decoded.promise; return { - image: { - size: [4, 4, 1], - data: Uint16Array.from({ length: 16 }, (_, index) => - index === 5 ? 1 : 0 - ), - imageType: { components: 1 }, - }, + size: [4, 4, 1], + data: Uint16Array.from({ length: 16 }, (_, index) => + index === 5 ? 1 : 0 + ), + components: 1, }; - }, - }); - await image.addChunks([chunk]); + }) + ); + const image = new DicomVolumeImage({ runtime }); + image.setVolume(allocateVolume(plannedUpdate([instance]))); cache().addProgressiveImage(image, { id }); await started.promise; expect(image.loading.value).toBe(true); diff --git a/src/segmentation/io/import.ts b/src/segmentation/io/import.ts index f2e71be12..c185c1ffd 100644 --- a/src/segmentation/io/import.ts +++ b/src/segmentation/io/import.ts @@ -4,7 +4,7 @@ import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; import type { RGBAColor, TypedArray } from '@kitware/vtk.js/types'; import { untilLoaded } from '@/src/composables/untilLoaded'; -import DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { ensureSameSpace } from '@/src/io/resample/resample'; import { overlaySegmentMetadata, @@ -186,18 +186,20 @@ async function segBuildDescriptors( if (useDICOMStore().volumeInfo[imageId]?.kind === 'cine') return undefined; await untilLoaded(imageId); - const chunkImage = useImageCacheStore().imageById[imageId] as DicomChunkImage; - if (chunkImage.getModality() !== 'SEG' || !chunkImage.segBuildInfo) + const image = useImageCacheStore().imageById[imageId]; + if ( + !(image instanceof DicomVolumeImage) || + image.getModality() !== 'SEG' || + !image.segBuildInfo + ) return undefined; - return chunkImage.segBuildInfo.segmentAttributes[component].map( - (segment) => ({ - value: segment.labelID, - name: segment.SegmentLabel, - color: [...segment.recommendedDisplayRGBValue, 255] as RGBAColor, - visible: true, - }) - ); + return image.segBuildInfo.segmentAttributes[component].map((segment) => ({ + value: segment.labelID, + name: segment.SegmentLabel, + color: [...segment.recommendedDisplayRGBValue, 255] as RGBAColor, + visible: true, + })); } export const distinctLabelValues = (image: vtkLabelMap) => diff --git a/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts new file mode 100644 index 000000000..8dfe8c29c --- /dev/null +++ b/src/store/__tests__/datasets-dicom-acquisition-split.spec.ts @@ -0,0 +1,217 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; + +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { useImageCacheStore } from '@/src/store/image-cache'; +import { useMessageStore } from '@/src/store/messages'; +import { + getDisplayName, + useDICOMStore, + type ImportInstancesResult, +} from '@/src/store/datasets-dicom'; +import { + acquisition, + imageFactory, + OTHER_SERIES_UID, + SERIES_UID, + sliceFor, +} from '@/src/store/__tests__/dicomImportFixtures'; + +// 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]); + +const volumeIds = (result: ImportInstancesResult) => + Object.keys(result.volumes).sort(); + +const labelsOf = (store: ReturnType) => + Object.values(store.volumeInfo) + .map((info) => info.splitLabel) + .sort(); + +describe('DICOM store acquisition split across imports', () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + it('loads one series holding two overlapping passes as two labelled volumes', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + + const result = store.importInstances( + [...acquisitionOne(), ...acquisitionTwo()], + { createImage } + ); + + expect(volumeIds(result)).toHaveLength(2); + expect(labelsOf(store)).toEqual(['acquisition 1', 'acquisition 2']); + Object.values(store.volumeInfo).forEach((info) => { + expect(info.NumberOfSlices).toBe(3); + expect(info.SeriesDescription).toBe('Imported series'); + expect(getDisplayName(info)).toBe(`Imported series (${info.splitLabel})`); + }); + expect(useMessageStore().messages).toEqual([]); + }); + + 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 = store.importInstances(first, { createImage }); + const [firstId] = volumeIds(initial); + expect(store.volumeInfo[firstId].splitLabel).toBeUndefined(); + + const second = store.importInstances(acquisitionTwo(), { + createImage, + }); + + // The pass already on screen keeps its id and gains its label; the new + // pass gets a fresh id. Nothing dissolves. + expect(volumeIds(second)).toContain(firstId); + expect(volumeIds(second)).toHaveLength(2); + expect(store.volumeInfo[firstId].splitLabel).toBe('acquisition 1'); + expect(labelsOf(store)).toEqual(['acquisition 1', 'acquisition 2']); + expect(Object.keys(useImageCacheStore().imageById).sort()).toEqual( + volumeIds(second) + ); + // The first image was not rebuilt, only left holding its own pass. + expect(created).toHaveLength(2); + expect(created[0].getInstances()).toEqual(first); + }); + + it('keeps an established split when a later slice lacks the discriminator', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + + store.importInstances([...acquisitionOne(), ...acquisitionTwo()], { + createImage, + }); + const untagged = sliceFor({ sop: 'untagged', z: 1.5 }); + store.importInstances([untagged], { createImage }); + + // The slice no axis can place forms its own volume; the two passes stay. + expect(labelsOf(store)).toEqual([ + 'acquisition 1', + 'acquisition 2', + 'acquisition unknown', + ]); + }); + + 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 = () => + [0, 2.5, 2.5, 5].map((z, i) => + sliceFor({ + sop: `dup-${i}`, + z, + tags: { [Tags.AcquisitionNumber]: '1' }, + }) + ); + + store.importInstances(doubled(), { createImage }); + // Dropping the same folder again changes nothing worth repeating. + store.importInstances(doubled(), { createImage }); + + const { messages } = useMessageStore(); + expect(messages).toHaveLength(1); + expect(messages[0].title).toMatch(/did not load as one sound volume/); + expect(messages[0].options.details).toMatch( + /^Imported series holds repeated/ + ); + }); + + 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('names a positionless volume once a later import of its series places others', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + const unplaced = sliceFor({ + sop: 'unplaced', + tags: { [Tags.ImagePositionPatient]: '' }, + }); + + store.importInstances([unplaced], { createImage }); + expect(labelsOf(store)).toEqual([undefined]); + + store.importInstances(acquisitionOne(), { createImage }); + + 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(); + const tagged = (sop: string, z: number, number: string) => + sliceFor({ sop, z, tags: { [Tags.AcquisitionNumber]: number } }); + // Two slices of two passes load as one volume; the second batch completes + // both passes and splits the pair so evenly that neither keeps the id. + const first = [tagged('a', 0, '1'), tagged('b', 2, '2')]; + const second = [tagged('c', 2, '1'), tagged('d', 0, '2')]; + + const [id] = volumeIds(store.importInstances(first, { createImage })); + store.importInstances(second, { createImage }); + + expect(store.volumeInfo[id]).toBeUndefined(); + const regrouped = useMessageStore().messages.filter((message) => + /regrouped/.test(message.title) + ); + expect(regrouped).toHaveLength(1); + expect(regrouped[0].options.details).toMatch( + /^Imported series was regrouped/ + ); + }); +}); diff --git a/src/store/__tests__/datasets-dicom-cine.spec.ts b/src/store/__tests__/datasets-dicom-cine.spec.ts index 2f1c4fc97..0c5071050 100644 --- a/src/store/__tests__/datasets-dicom-cine.spec.ts +++ b/src/store/__tests__/datasets-dicom-cine.spec.ts @@ -1,288 +1,121 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import type { Chunk } from '@/src/core/streaming/chunk'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { - SOP_CLASS_ULTRASOUND_MULTIFRAME, - SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, - Tags, -} from '@/src/core/dicomTags'; -import type { - CineHeader, - CineParseResult, -} from '@/src/core/cine/parseCineDicom'; + 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 { isCineChunkGroup, useDICOMStore } from '@/src/store/datasets-dicom'; - -const mocks = vi.hoisted(() => { - const chunkImages: MockDicomChunkImage[] = []; - - class MockDicomChunkImage { - chunks: Chunk[] = []; - name = ''; - - constructor() { - chunkImages.push(this); - } - - async addChunks(chunks: Chunk[]) { - this.chunks = chunks; - } - - getDicomMetadata() { - return this.chunks[0].metadata; - } - - getChunks() { - return this.chunks.slice(); - } - - setName(name: string) { - this.name = name; - } - - getStatus() { - return 'complete'; - } - - isLoading() { - return false; - } - - addEventListener() {} - - removeEventListener() {} - - startLoad() {} - - dispose() {} - } - - return { - splitAndSort: vi.fn(), - parseCineDicom: vi.fn(), - chunkImages, - MockDicomChunkImage, - }; -}); - -// eslint-disable-next-line no-restricted-syntax -- DICOM splitting runs in wasm; unavailable in the node test environment -vi.mock('@/src/io/dicom', () => ({ - splitAndSort: mocks.splitAndSort, -})); - -// eslint-disable-next-line no-restricted-syntax -- reads real DICOM bytes through wasm -vi.mock('@/src/core/cine/parseCineDicom', async (importOriginal) => { - const actual = - await importOriginal(); - return { - ...actual, - parseCineDicom: mocks.parseCineDicom, - }; -}); - -// eslint-disable-next-line no-restricted-syntax -- needs a streaming chunk source the node environment cannot provide -vi.mock('@/src/core/streaming/dicomChunkImage', () => ({ - default: mocks.MockDicomChunkImage, -})); - -function metadata(overrides: Record = {}) { - return instanceTags({ - sopClassUid: SOP_CLASS_ULTRASOUND_MULTIFRAME, - numberOfFrames: '2', - sopInstanceUid: 'sop-uid', - modality: 'US', - seriesDescription: 'Unsupported native cine', - }).map(([tag, value]) => [tag, overrides[tag] ?? value]) as [ - string, - string, - ][]; -} - -function cineHeader(overrides: Partial = {}): CineHeader { - return { - transferSyntaxUID: '1.2.840.10008.1.2.1', - rows: 2, - cols: 2, - numberOfFrames: 2, - samplesPerPixel: 1, - bitsAllocated: 8, - planarConfiguration: 0, - photometricInterpretation: 'MONOCHROME1', - 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: '7', - SeriesDescription: 'Unsupported native cine', - Modality: 'US', - }, - regions: [], - ...overrides, - }; -} - -function parseResult(header: CineHeader): CineParseResult { - return { - header, - frames: [new Uint8Array([1, 2, 3, 4]), new Uint8Array([5, 6, 7, 8])], - encapsulated: false, - }; -} - -function chunk(meta = metadata()) { - return { - metadata: meta, - metaBlob: new Blob([new Uint8Array([1])]), - dataBlob: new Blob([new Uint8Array([2])]), - loadData: vi.fn().mockResolvedValue(undefined), - } as unknown as Chunk; -} - -describe('isCineChunkGroup', () => { - it('accepts a single current ultrasound multi-frame image with more than one frame', () => { - expect(isCineChunkGroup([chunk()])).toBe(true); - }); - - it('accepts the retired ultrasound multi-frame SOP class UID', () => { - expect( - isCineChunkGroup([ - chunk( - metadata({ - [Tags.SOPClassUID]: SOP_CLASS_ULTRASOUND_MULTIFRAME_RETIRED, - }) - ), - ]) - ).toBe(true); - }); - - it('rejects multi-chunk groups', () => { - expect(isCineChunkGroup([chunk(), chunk()])).toBe(false); +import { + imageFactory, + onlyId, + sliceFor, + STUDY_UID, +} from '@/src/store/__tests__/dicomImportFixtures'; +import { useDICOMStore } from '@/src/store/datasets-dicom'; + +const SERIES = { + [Tags.SeriesNumber]: '7', + [Tags.SeriesDescription]: 'Unsupported native cine', +}; + +// MONOCHROME1 native pixels are a clip the cine player does not support. +const unsupported = () => + cineInstance({ + ...SERIES, + [Tags.PhotometricInterpretation]: 'MONOCHROME1', }); - it('rejects non-ultrasound SOP classes', () => { - expect( - isCineChunkGroup([ - chunk( - metadata({ - [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2', - }) - ), - ]) - ).toBe(false); - }); - - it('rejects single-frame images', () => { - expect( - isCineChunkGroup([ - chunk( - metadata({ - [Tags.NumberOfFrames]: '1', - }) - ), - ]) - ).toBe(false); - }); -}); +beforeEach(() => setActivePinia(createPinia())); describe('DICOM store cine routing', () => { - beforeEach(() => { - setActivePinia(createPinia()); - mocks.splitAndSort.mockReset(); - mocks.parseCineDicom.mockReset(); - mocks.chunkImages.length = 0; - }); - - it('falls back to chunk import for unsupported parsed cine headers', async () => { - const unsupportedCineChunk = chunk(); - const chunksByVolume = { 'volume-1': [unsupportedCineChunk] }; - mocks.splitAndSort.mockResolvedValue(chunksByVolume); - mocks.parseCineDicom.mockReturnValue(parseResult(cineHeader())); + it('imports a clip the cine player does not support as a volume', () => { + const { created, createImage } = imageFactory(); + const clip = unsupported(); const store = useDICOMStore(); - await expect(store.importChunks([unsupportedCineChunk])).resolves.toBe( - chunksByVolume - ); + const result = store.importInstances([clip], { createImage }); - expect(unsupportedCineChunk.loadData).toHaveBeenCalledOnce(); - expect(mocks.parseCineDicom).toHaveBeenCalledOnce(); - expect(mocks.chunkImages).toHaveLength(1); - expect(mocks.chunkImages[0].chunks).toEqual([unsupportedCineChunk]); + expect(created).toHaveLength(1); + expect(created[0].getInstances()).toEqual([clip]); - const imageCacheStore = useImageCacheStore(); - expect(imageCacheStore.imageById['volume-1']).toBe(mocks.chunkImages[0]); - expect(store.volumeInfo['volume-1']).toMatchObject({ - NumberOfSlices: 1, - VolumeID: 'volume-1', + const id = onlyId(result); + expect(result.volumes[id]).toEqual([clip]); + expect(useImageCacheStore().imageById[id]).toBe(created[0]); + expect(store.volumeInfo[id]).toMatchObject({ + NumberOfSlices: 2, + VolumeID: id, Modality: 'US', SeriesInstanceUID: 'series-uid', SeriesNumber: '7', SeriesDescription: 'Unsupported native cine', + kind: 'volume', }); - expect(store.volumeInfo['volume-1'].kind).toBe('volume'); }); - it('falls back to chunk import when cine parsing throws', async () => { - const malformedCineChunk = chunk(); - const chunksByVolume = { 'volume-1': [malformedCineChunk] }; - mocks.splitAndSort.mockResolvedValue(chunksByVolume); - mocks.parseCineDicom.mockImplementation(() => { - throw new Error('unsupported encapsulated frame layout'); - }); + it('plays a clip as cine from its header alone, whatever its pixels hold', () => { + const { created, createImage } = imageFactory(); + const malformed = cineInstance( + {}, + { transferSyntaxUid: TS_JPEG_BASELINE, pixels: new Uint8Array(8) } + ); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - try { - const store = useDICOMStore(); - await expect(store.importChunks([malformedCineChunk])).resolves.toBe( - chunksByVolume - ); - } finally { - warn.mockRestore(); - } + const store = useDICOMStore(); + const id = onlyId(store.importInstances([malformed], { createImage })); - expect(malformedCineChunk.loadData).toHaveBeenCalledOnce(); - expect(mocks.parseCineDicom).toHaveBeenCalledOnce(); - expect(mocks.chunkImages).toHaveLength(1); - expect(mocks.chunkImages[0].chunks).toEqual([malformedCineChunk]); + expect(created).toHaveLength(0); + expect(store.volumeInfo[id].kind).toBe('cine'); + expect(useImageCacheStore().imageById[id]).toBeInstanceOf(DicomCineImage); + }); - const imageCacheStore = useImageCacheStore(); - expect(imageCacheStore.imageById['volume-1']).toBe(mocks.chunkImages[0]); - expect(useDICOMStore().volumeInfo['volume-1'].kind).toBe('volume'); + it('reuses an unsupported cine clip that already loaded as a volume', () => { + const { created, createImage } = imageFactory(); + const store = useDICOMStore(); + 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('rejects cached non-chunk images before chunk-volume reuse', async () => { - const normalChunk = chunk( - metadata({ - [Tags.SOPClassUID]: '1.2.840.10008.5.1.4.1.1.2', - [Tags.NumberOfFrames]: '1', - }) - ); - const chunksByVolume = { 'volume-1': [normalChunk] }; - mocks.splitAndSort.mockResolvedValue(chunksByVolume); +it('imports two same-shaped ultrasound clips as separate playable cine volumes', () => { + const clips = ['clip-1', 'clip-2'].map((sop) => + cineInstance({ [Tags.SOPInstanceUID]: sop }) + ); + const { created, createImage } = imageFactory(); + const store = useDICOMStore(); + const result = store.importInstances(clips, { createImage }); + expect( + Object.values(result.volumes).map((members) => members.length) + ).toEqual([1, 1]); + expect(Object.values(store.volumeInfo).map((info) => info.kind)).toEqual([ + 'cine', + 'cine', + ]); + expect( + Object.keys(result.volumes).map( + (id) => useImageCacheStore().imageById[id] instanceof DicomCineImage + ) + ).toEqual([true, true]); + expect(created).toHaveLength(0); +}); - const imageCacheStore = useImageCacheStore(); - imageCacheStore.imageById['volume-1'] = - {} as (typeof imageCacheStore.imageById)[string]; +it('files a clip and a volume of one study under one patient', () => { + 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, + }; - const store = useDICOMStore(); - await expect(store.importChunks([normalChunk])).rejects.toThrow( - /non-chunk progressive image/ - ); - expect(mocks.chunkImages).toHaveLength(0); + 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 new file mode 100644 index 000000000..c744c089f --- /dev/null +++ b/src/store/__tests__/datasets-dicom-geometry.spec.ts @@ -0,0 +1,95 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { useDICOMStore } from '@/src/store/datasets-dicom'; +import { useMessageStore } from '@/src/store/messages'; +import { + ALLOCATION_FAILURE, + imageFactory, + onlyFailure, + sliceFor, + unallocatableFor, +} from './dicomImportFixtures'; + +const AXIAL = [1, 0, 0, 0, 1, 0]; +const leaning = (theta: number) => [ + Math.cos(theta), + 0, + Math.sin(theta), + 0, + 1, + 0, +]; +const TILTED = leaning(0.0002); + +// Slice 0 is the stray one, and is not the first its series walks. +const slice = (index: number, { stray = TILTED, pixelSpacing = '1\\1' } = {}) => + sliceFor({ + sop: index === 1 ? '1' : `2.${index}`, + z: index * 5, + orientation: (index === 0 ? stray : AXIAL).join('\\'), + tags: { [Tags.BitsStored]: '8', [Tags.PixelSpacing]: pixelSpacing }, + }); + +const slices = (count: number, options?: Parameters[1]) => + Array.from({ length: count }, (_, i) => slice(i, options)); + +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', () => { + const { created, createImage } = imageFactory(); + const result = useDICOMStore().importInstances(slices(121), { + createImage, + }); + const [image] = created; + + expect(Object.keys(result.volumes)).toHaveLength(1); + expect(useMessageStore().messages).toHaveLength(0); + expect(image.getVtkImageData().getSpacing()).toEqual([1, 1, 5]); + expect(image.getVtkImageData().getDirection()).toEqual([...AXIAL, 0, 0, 1]); + expect(image.getVtkImageData().indexToWorld([0, 0, 120])[2]).toBe(600); + image.dispose(); + }); + + 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(); + useDICOMStore().importInstances(slices(5, wide), { createImage }); + const [image] = created; + + expect(image.getVtkImageData().getDirection()).toEqual([...AXIAL, 0, 0, 1]); + expect( + useMessageStore().messages.map((message) => message.options.details) + ).toEqual([expect.stringContaining('not parallel to one another')]); + image.dispose(); + }); + + 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); + 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. + expect( + onlyFailure( + store.importInstances([...rest, unallocatableFor({ sop: 'scout' })], { + createImage, + }) + ) + ).toMatch(ALLOCATION_FAILURE); + expect(image.getInstances()).toEqual([first]); + expect(direction()).toEqual(TILTED); + + 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 new file mode 100644 index 000000000..98f82903a --- /dev/null +++ b/src/store/__tests__/datasets-dicom-lifetime.spec.ts @@ -0,0 +1,29 @@ +import { beforeEach, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +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'; +import { + imageFactory, + sliceFor, +} from '@/src/store/__tests__/dicomImportFixtures'; + +beforeEach(() => setActivePinia(createPinia())); + +it('cancels a pending pixel read when its dataset is removed', async () => { + const hanging = hangingSource(); + const store = useDICOMStore(); + const { volumes } = store.importInstances( + [sliceFor({ sop: '1.2.3.5', source: hanging.source })], + { createImage: imageFactory().createImage } + ); + const [id] = Object.keys(volumes); + await hanging.pulled; + + useDatasetStore().remove(id); + + expect(await hanging.cancelled).toMatchObject({ name: 'AbortError' }); + expect(store.volumeInfo).toEqual({}); + expect(useImageCacheStore().imageById[id]).toBeUndefined(); +}); diff --git a/src/store/__tests__/datasets-dicom-reimport.spec.ts b/src/store/__tests__/datasets-dicom-reimport.spec.ts index b60cffc94..8f3647ea2 100644 --- a/src/store/__tests__/datasets-dicom-reimport.spec.ts +++ b/src/store/__tests__/datasets-dicom-reimport.spec.ts @@ -1,109 +1,238 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it } from 'vitest'; import { createPinia, setActivePinia } from 'pinia'; -import type { Chunk } from '@/src/core/streaming/chunk'; +import type DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { useImageCacheStore } from '@/src/store/image-cache'; -import { instanceTags } from '@/src/store/__tests__/dicomTagFixtures'; 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, + STUDY_UID, + unallocatableFor, +} from '@/src/store/__tests__/dicomImportFixtures'; + +const sliceValues = (image: DicomVolumeImage) => { + const data = image.getVtkImageData(); + const [columns, rows, slices] = data.getDimensions(); + const scalars = data.getPointData().getScalars().getData(); + return Array.from( + { length: slices }, + (_, slice) => scalars[slice * columns * rows] + ); +}; -const mocks = vi.hoisted(() => { - const chunkImages: MockDicomChunkImage[] = []; +describe('DICOM store incremental import', () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); - class MockDicomChunkImage { - additions: Chunk[][] = []; - startLoadCount = 0; - name = ''; + it('grows the image a re-import adds to and loads the new slice', async () => { + const { created, createImage } = imageFactory(); + const first = sliceFor({ sop: 'a', z: 0 }); + const second = sliceFor({ sop: 'b', z: 1 }); - constructor() { - chunkImages.push(this); - } + const store = useDICOMStore(); + const firstResult = store.importInstances([first], { createImage }); + const id = onlyId(firstResult); + await untilLoaded(id); + const secondResult = store.importInstances([second], { + createImage, + }); + await untilLoaded(id); + + expect(created).toHaveLength(1); + const [image] = created; + expect(membersOf(image)).toEqual(['a', 'b']); + expect(sliceValues(image)).toEqual([1, 2]); + expect(onlyId(secondResult)).toBe(id); + expect(useImageCacheStore().imageById[id]).toBe(image); + // Every member reports back, so the dataset's provenance stays complete. + expect(secondResult.volumes[id]).toEqual([first, second]); + }); - async addChunks(chunks: Chunk[]) { - this.additions.push(chunks); - } + it('builds the volume in planned order, not arrival order', async () => { + const { created, createImage } = imageFactory(); + const store = useDICOMStore(); + store.importInstances([sliceFor({ sop: 'b', z: 1 })], { + createImage, + }); + const id = onlyId( + store.importInstances([sliceFor({ sop: 'a', z: 0 })], { + createImage, + }) + ); + await untilLoaded(id); + + expect(membersOf(created[0])).toEqual(['a', 'b']); + expect(sliceValues(created[0])).toEqual([1, 2]); + }); - getDicomMetadata() { - return this.additions.at(-1)![0].metadata; - } + 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( + (_, batch) => + onlyId( + store.importInstances( + batch.map((sop) => sliceFor({ sop, z: sop.charCodeAt(0) })), + { createImage } + ) + ), + '' + ); + }; + + const oneBatch = load([['a', 'b', 'c']]); + expect(load([['a'], ['b', 'c']])).toBe(oneBatch); + expect(load([['b', 'c'], ['a']])).toBe(oneBatch); + expect( + load([ + ['a', 'b', 'c'], + ['a', 'b', 'c'], + ]) + ).toBe(oneBatch); + }); - getChunks() { - return this.additions.at(-1)!.slice(); - } + 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 }); - setName(name: string) { - this.name = name; - } + const store = useDICOMStore(); + const first = store.importInstances([original], { createImage }); + const second = store.importInstances([resupplied], { createImage }); - getStatus() { - return 'incomplete'; - } + expect(created).toHaveLength(1); + expect(created[0].getInstances()).toEqual([original]); + expect(second.volumes[onlyId(first)]).toEqual([resupplied]); + expect(store.volumeInfo[onlyId(first)].NumberOfSlices).toBe(1); + }); - isLoading() { - return false; - } + it('counts every member of the volume after a re-import', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); - addEventListener() {} + const first = store.importInstances([sliceFor({ sop: 'a', z: 0 })], { + createImage, + }); + store.importInstances([sliceFor({ sop: 'b', z: 1 })], { + createImage, + }); - removeEventListener() {} + expect(store.volumeInfo[onlyId(first)].NumberOfSlices).toBe(2); + }); - startLoad() { - this.startLoadCount += 1; - } + 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 })]; - dispose() {} - } + const store = useDICOMStore(); + const result = store.importInstances([scout, ...slices], { + createImage, + }); + + expect(created).toHaveLength(2); + const ids = Object.keys(result.volumes); + expect(ids).toHaveLength(2); + expect(Object.values(result.volumes)).toContainEqual([scout]); + expect(Object.values(result.volumes)).toContainEqual(slices); + + const imageCacheStore = useImageCacheStore(); + ids.forEach((id) => expect(imageCacheStore.imageById[id]).toBeDefined()); + expect(ids.map((id) => store.volumeInfo[id].NumberOfSlices).sort()).toEqual( + [1, 2] + ); + expect(store.studyVolumes[STUDY_UID].sort()).toEqual([...ids].sort()); + }); - return { splitAndSort: vi.fn(), chunkImages, MockDicomChunkImage }; -}); + 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(store.importInstances([original], { createImage })); + useImageCacheStore().removeImage(id); + store.deleteVolume(id); + + const resupplied = sliceFor({ sop: 'a', z: 0 }); + const reimported = onlyId( + store.importInstances([resupplied], { createImage }) + ); + + expect(reimported).toBe(id); + expect(created).toHaveLength(2); + // Identity, not shape: the forgotten instance is an equal but stale object. + expect(created[1].getInstances()).toHaveLength(1); + expect(created[1].getInstances()[0]).toBe(resupplied); + }); -// eslint-disable-next-line no-restricted-syntax -- DICOM splitting runs in wasm; unavailable in the node test environment -vi.mock('@/src/io/dicom', () => ({ - splitAndSort: mocks.splitAndSort, -})); - -// eslint-disable-next-line no-restricted-syntax -- needs a streaming chunk source the node environment cannot provide -vi.mock('@/src/core/streaming/dicomChunkImage', () => ({ - default: mocks.MockDicomChunkImage, -})); - -function chunk(sopInstanceUid: string) { - const metadata = instanceTags({ - sopClassUid: '1.2.840.10008.5.1.4.1.1.2', - numberOfFrames: '1', - sopInstanceUid, - modality: 'CT', - seriesDescription: 'Incremental series', + it('drops the volume a replan dissolved', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + const imageCacheStore = useImageCacheStore(); + const { between, straight, tilted } = mergingInstances(sliceFor); + + const first = store.importInstances([straight, tilted], { + createImage, + }); + const ids = Object.keys(first.volumes); + expect(ids).toHaveLength(2); + + const merged = store.importInstances([between], { createImage }); + const survivor = onlyId(merged); + const dissolved = ids.find((id) => id !== survivor)!; + + expect(store.volumeInfo[dissolved]).toBeUndefined(); + expect(imageCacheStore.imageById[dissolved]).toBeUndefined(); + expect(store.studyVolumes[STUDY_UID]).toEqual([survivor]); + expect(store.volumeInfo[survivor].NumberOfSlices).toBe(3); + // The survivor carries the provenance of the member it inherited. + expect(merged.volumes[survivor]).toEqual([straight, tilted, between]); }); - return { - metadata, - metaBlob: new Blob([new Uint8Array([1])]), - dataBlob: new Blob([new Uint8Array([2])]), - loadData: vi.fn().mockResolvedValue(undefined), - } as unknown as Chunk; -} -describe('DICOM store incremental import', () => { - beforeEach(() => { - setActivePinia(createPinia()); - mocks.splitAndSort.mockReset(); - mocks.chunkImages.length = 0; + it('lets a corrected re-import replace the instance a failed import brought', () => { + const { created, createImage } = imageFactory(); + const store = useDICOMStore(); + expect( + onlyFailure( + store.importInstances([unallocatableFor({ sop: 'a' })], { createImage }) + ) + ).toMatch(ALLOCATION_FAILURE); + + const corrected = sliceFor({ sop: 'a', rows: '8' }); + store.importInstances([corrected], { createImage }); + + // Identity, not shape: the failed import must not pin its instance. + expect(created).toHaveLength(1); + expect(created[0].getInstances()).toEqual([corrected]); + expect(created[0].getInstances()[0]).toBe(corrected); }); - it('asks an already-registered image to load the chunks a re-import adds', async () => { - const first = chunk('sop-1'); - const second = chunk('sop-2'); - mocks.splitAndSort - .mockResolvedValueOnce({ 'volume-1': [first] }) - .mockResolvedValueOnce({ 'volume-1': [first, second] }); + 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(); - await store.importChunks([first]); - await store.importChunks([second]); - - expect(mocks.chunkImages).toHaveLength(1); - const [image] = mocks.chunkImages; - expect(image.additions).toEqual([[first], [first, second]]); - expect(image.startLoadCount).toBe(2); - expect(useImageCacheStore().imageById['volume-1']).toBe(image); + const result = store.importInstances([first, second], { + createImage, + }); + + const ids = Object.keys(result.volumes); + expect(ids).toHaveLength(2); + expect( + ids.map((id) => store.volumeInfo[id].SeriesInstanceUID).sort() + ).toEqual([SERIES_UID, OTHER_SERIES_UID].sort()); }); }); diff --git a/src/store/__tests__/datasets-dicom-transaction.spec.ts b/src/store/__tests__/datasets-dicom-transaction.spec.ts new file mode 100644 index 000000000..7fe8a8e9e --- /dev/null +++ b/src/store/__tests__/datasets-dicom-transaction.spec.ts @@ -0,0 +1,219 @@ +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; + +import { useImageCacheStore } from '@/src/store/image-cache'; +import { untilLoaded } from '@/src/composables/untilLoaded'; +import { useDICOMStore, getDisplayName } from '@/src/store/datasets-dicom'; +import { + ALLOCATION_FAILURE, + cineFor, + imageFactory, + membersOf, + onlyFailure, + onlyId, + SERIES_UID, + sliceFor, + splitting, + STUDY_UID, + unallocatableFor, +} from '@/src/store/__tests__/dicomImportFixtures'; + +const cachedIds = () => Object.keys(useImageCacheStore().imageById); + +/** Loads the pair a later batch splits into two fresh collections. */ +const loadSplittablePair = () => { + const instances = splitting(); + const loaded = imageFactory(); + const store = useDICOMStore(); + const id = onlyId( + store.importInstances([instances.one, instances.three], { + createImage: loaded.createImage, + }) + ); + return { ...instances, store, loaded, id }; +}; + +/** Loads and decodes one slice, then fails a batch that grows it and adds a scout. */ +const growAndFail = async () => { + const { created, createImage } = imageFactory(); + const store = useDICOMStore(); + const first = sliceFor({ sop: 'a', z: 0 }); + const id = onlyId(store.importInstances([first], { createImage })); + await untilLoaded(id); + const shown = created[0].getVtkImageData(); + + expect( + onlyFailure( + store.importInstances( + [sliceFor({ sop: 'b', z: 1 }), unallocatableFor({ sop: 'scout' })], + { createImage } + ) + ) + ).toMatch(ALLOCATION_FAILURE); + + return { store, id, first, created, shown }; +}; + +describe('DICOM store atomic series commit', () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + it('commits nothing for a series when one of its collections fails to allocate', () => { + const { created, createImage } = imageFactory(); + const store = useDICOMStore(); + + 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([]); + expect(store.volumeInfo).toEqual({}); + expect(store.volumeStudy).toEqual({}); + expect(store.studyVolumes).toEqual({}); + expect(store.studyInfo).toEqual({}); + expect(store.patientInfo).toEqual({}); + expect(store.patientStudies).toEqual({}); + }); + + it('leaves a displayed volume and its pixels unchanged when its growth fails', async () => { + const { store, id, first, created, shown } = await growAndFail(); + + expect(created).toHaveLength(1); + expect(created[0].getInstances()).toEqual([first]); + expect(created[0].getVtkImageData()).toBe(shown); + expect(shown.isDeleted()).toBe(false); + expect(Array.from(shown.getPointData().getScalars().getData())).toEqual( + Array(16).fill(1) + ); + expect(cachedIds()).toEqual([id]); + expect(store.volumeInfo[id].NumberOfSlices).toBe(1); + expect(store.studyVolumes[STUDY_UID]).toEqual([id]); + }); + + it('lets the next import of the series commit after a failed batch', async () => { + const { store, id, first, created } = await growAndFail(); + + const retry = imageFactory(); + const corrected = sliceFor({ sop: 'b', z: 1 }); + const scout = sliceFor({ sop: 'scout', rows: '8' }); + const result = store.importInstances([corrected, scout], { + createImage: retry.createImage, + }); + + // The unchanged key keeps its ID, and only the scout needs a new image. + const ids = Object.keys(result.volumes); + expect(ids).toHaveLength(2); + expect(ids).toContain(id); + expect(retry.created).toHaveLength(1); + + const scoutId = ids.find((other) => other !== id)!; + // Identity, not shape: the failed batch must not pin the instance it brought. + expect(result.volumes[id]).toEqual([first, corrected]); + expect(result.volumes[id][1]).toBe(corrected); + expect(result.volumes[scoutId]).toEqual([scout]); + expect(created[0].getInstances()[1]).toBe(corrected); + expect(store.volumeInfo[id].NumberOfSlices).toBe(2); + expect(store.volumeInfo[scoutId].NumberOfSlices).toBe(1); + }); + + it('keeps a dissolved volume when the split that dissolves it fails', () => { + const { store, id, zero, two, loaded } = loadSplittablePair(); + + const failing = imageFactory(); + 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); + expect(store.studyVolumes[STUDY_UID]).toEqual([id]); + expect(membersOf(loaded.created[0])).toEqual(['sop-1', 'sop-3']); + expect(failing.created).toEqual([]); + }); + + it('hands a dissolved volume to the given removal', () => { + const { store, id, zero, two } = loadSplittablePair(); + const removed: string[] = []; + + store.importInstances([zero, two], { + createImage: imageFactory().createImage, + removeDissolved: (dissolved) => removed.push(dissolved), + }); + + expect(removed).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', () => { + const { store, id, zero, one, two, three } = loadSplittablePair(); + + const result = store.importInstances([zero, two], { + createImage: imageFactory().createImage, + }); + + const ids = Object.keys(result.volumes); + expect(ids).toHaveLength(2); + expect(ids).not.toContain(id); + expect(store.volumeInfo[id]).toBeUndefined(); + expect(cachedIds().sort()).toEqual([...ids].sort()); + expect(store.studyVolumes[STUDY_UID].sort()).toEqual([...ids].sort()); + expect(ids.map((each) => store.volumeInfo[each].NumberOfSlices)).toEqual([ + 2, 2, + ]); + // Each half carries the provenance of the member it inherited. + expect(Object.values(result.volumes)).toContainEqual([zero, one]); + expect(Object.values(result.volumes)).toContainEqual([two, three]); + }); + + it('registers no cine image when a sibling collection fails', () => { + const { createImage } = imageFactory(); + const store = useDICOMStore(); + + expect( + onlyFailure( + store.importInstances( + [cineFor('cine'), unallocatableFor({ sop: 'scout' })], + { createImage } + ) + ) + ).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({}); + }); +}); + +describe('DICOM record naming', () => { + beforeEach(() => setActivePinia(createPinia())); + + 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 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__/dicom-viewed-slice.spec.ts b/src/store/__tests__/dicom-viewed-slice.spec.ts new file mode 100644 index 000000000..a33073d48 --- /dev/null +++ b/src/store/__tests__/dicom-viewed-slice.spec.ts @@ -0,0 +1,67 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { createPinia, setActivePinia } from 'pinia'; +import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; +import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; +import type { LPSAxis } from '@/src/types/lps'; +import { useImageCacheStore } from '@/src/store/image-cache'; +import { useViewStore } from '@/src/store/views'; +import { useViewSliceStore } from '@/src/store/view-configs/slicing'; +import { viewedSlice } from '@/src/store/dicom-viewed-slice'; + +function cacheStack(slices: number) { + const data = vtkImageData.newInstance(); + data.setDimensions([2, 2, slices]); + data + .getPointData() + .setScalars( + vtkDataArray.newInstance({ values: new Uint8Array(4 * slices) }) + ); + return useImageCacheStore().addVTKImageData(data, 'stack'); +} + +function show(dataID: string, orientation: LPSAxis, slot = 0) { + const views = useViewStore(); + views.replaceView(views.layoutViews[slot].id, { + name: orientation, + type: '2D', + dataID, + options: { orientation }, + }); + return views.layoutViews[slot].id; +} + +describe('viewedSlice', () => { + beforeEach(() => setActivePinia(createPinia())); + + it('follows the slice a view along the acquisition axis shows', () => { + const id = cacheStack(9); + const viewID = show(id, 'Axial'); + useViewStore().setActiveView(viewID); + + useViewSliceStore().updateConfig(viewID, id, { min: 0, max: 8, slice: 6 }); + expect(viewedSlice(id)).toBe(6); + + useViewSliceStore().updateConfig(viewID, id, { slice: 2 }); + expect(viewedSlice(id)).toBe(2); + }); + + it('ignores views that cut across the acquisition axis', () => { + const id = cacheStack(9); + const viewID = show(id, 'Sagittal'); + useViewSliceStore().updateConfig(viewID, id, { min: 0, max: 1, slice: 1 }); + + expect(viewedSlice(id)).toBeUndefined(); + }); + + it('prefers the active view when two views show different slices', () => { + const id = cacheStack(9); + const [first, second] = [show(id, 'Axial', 0), show(id, 'Axial', 1)]; + const slices = useViewSliceStore(); + slices.updateConfig(first, id, { min: 0, max: 8, slice: 1 }); + slices.updateConfig(second, id, { min: 0, max: 8, slice: 7 }); + + useViewStore().setActiveView(second); + + expect(viewedSlice(id)).toBe(7); + }); +}); diff --git a/src/store/__tests__/dicom-web-store.spec.ts b/src/store/__tests__/dicom-web-store.spec.ts new file mode 100644 index 000000000..609bd7679 --- /dev/null +++ b/src/store/__tests__/dicom-web-store.spec.ts @@ -0,0 +1,159 @@ +import { useDicomMetaStore } from '@/src/store/dicom-web/dicom-meta-store'; +import { useViewStore } from '@/src/store/views'; +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'; + +import { + type PatientInfo, + type StudyInfo, + type VolumeInfo, + useDICOMStore, +} from '@/src/store/datasets-dicom'; +import { useDicomWebStore } from '@/src/store/dicom-web/dicom-web-store'; + +const patient: PatientInfo = { + PatientID: 'patient-1', + PatientName: 'Test Patient', + PatientBirthDate: '', + PatientSex: '', +}; + +const study: StudyInfo = { + StudyID: 'study-1', + StudyInstanceUID: 'study-uid', + StudyDate: '', + StudyTime: '', + AccessionNumber: '', + StudyDescription: '', +}; + +function volume(VolumeID: string, SeriesInstanceUID: string): VolumeInfo { + return { + NumberOfSlices: 1, + VolumeID, + Modality: 'CT', + SeriesInstanceUID, + SeriesNumber: '1', + SeriesDescription: '', + WindowLevel: '', + WindowWidth: '', + kind: 'volume', + }; +} + +describe('DICOMweb loaded-series tracking', () => { + beforeEach(() => { + setActivePinia(createPinia()); + }); + + it('does not treat a different series with a shared UID prefix as loaded', () => { + const dicomStore = useDICOMStore(); + const dicomWebStore = useDicomWebStore(); + + dicomStore._updateDatabase( + patient, + study, + volume('1.2.3.orientation', '1.2.3') + ); + dicomStore._updateDatabase( + patient, + study, + volume('1.2.30.orientation', '1.2.30') + ); + dicomWebStore.volumes['1.2.3'] = { + state: 'Done', + loaded: 1, + total: 1, + }; + + dicomStore.deleteVolume('1.2.3.orientation'); + + expect(dicomWebStore.volumes['1.2.3']).toEqual({ + state: 'Remote', + loaded: 0, + total: 1, + }); + }); + + it('allows downloading a padded series UID after its final volume is deleted', () => { + const store = useDICOMStore(); + const remote = useDicomWebStore(); + store._updateDatabase(patient, study, volume('first', '1.2.3 ')); + store._updateDatabase(patient, study, volume('second', '1.2.3\0')); + remote.volumes['1.2.3'] = { state: 'Done', loaded: 2, total: 2 }; + store.deleteVolume('first'); + expect(remote.volumes['1.2.3'].state).toBe('Done'); + store.deleteVolume('second'); + expect(remote.volumes['1.2.3'].state).toBe('Remote'); + }); +}); + +/** 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 { select, store } = remoteSeries(); + const retrieve = vi.fn(async () => [new File([], 'rt.dcm')]); + const importSources = async ( + sources: Parameters[0][] + ) => sources.map(asOkayResult); + await store.downloadVolume('series-uid', retrieve, importSources); + expect(store.volumes['series-uid'].state).toBe('Error'); + expect(select).not.toHaveBeenCalled(); + await store.downloadVolume('series-uid', retrieve, importSources); + expect(retrieve).toHaveBeenCalledTimes(2); + }); +}); + +describe('partly failed DICOMweb downloads', () => { + beforeEach(() => setActivePinia(createPinia())); + 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, 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); + + expect(store.volumes['series-uid'].state).toBe('Done'); + expect(select).toHaveBeenCalledWith('volume-1'); + expect(useMessageStore().messages).toEqual([ + expect.objectContaining({ + title: expect.stringMatching(/^2 of .* may be incomplete/), + options: expect.objectContaining({ + details: 'bad.dcm is not DICOM\nworse.dcm is not DICOM', + }), + }), + ]); + }); +}); diff --git a/src/store/__tests__/dicomImportFixtures.ts b/src/store/__tests__/dicomImportFixtures.ts new file mode 100644 index 000000000..4f6e73ce9 --- /dev/null +++ b/src/store/__tests__/dicomImportFixtures.ts @@ -0,0 +1,213 @@ +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; +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'; +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'; +export const STUDY_UID = '1.2.826.0.1.3680043.9.1'; + +type SliceOptions = { + sop: string; + series?: string; + z?: number; + rows?: string; + orientation?: string; + // Extra tags, keyed 'gggg|eeee'; a fixed tag given here is replaced. + tags?: Record; + source?: ByteSource; +}; + +/** One planned slice header, as `readInstance` hands it back. */ +export function sliceFor({ + sop, + series = SERIES_UID, + z = 0, + rows = '4', + orientation = '1\\0\\0\\0\\1\\0', + tags = {}, + source = fromBlob(new Blob([sop])), +}: SliceOptions) { + const metadata = [ + [Tags.SOPClassUID, '1.2.840.10008.5.1.4.1.1.4'], + [Tags.NumberOfFrames, '1'], + [Tags.SOPInstanceUID, sop], + [Tags.PatientID, 'patient-1'], + [Tags.PatientName, 'Test Patient'], + [Tags.PatientBirthDate, ''], + [Tags.PatientSex, ''], + [Tags.StudyID, 'study-1'], + [Tags.StudyInstanceUID, STUDY_UID], + [Tags.StudyDate, ''], + [Tags.StudyTime, ''], + [Tags.AccessionNumber, ''], + [Tags.StudyDescription, ''], + [Tags.Modality, 'MR'], + [Tags.SeriesInstanceUID, series], + [Tags.SeriesNumber, '7'], + [Tags.SeriesDescription, 'Imported series'], + [Tags.WindowLevel, ''], + [Tags.WindowWidth, ''], + [Tags.Rows, rows], + [Tags.Columns, '4'], + [Tags.SamplesPerPixel, '1'], + [Tags.BitsStored, '16'], + [Tags.PixelRepresentation, '0'], + [Tags.ImageOrientationPatient, orientation], + [Tags.ImagePositionPatient, `0\\0\\${z}`], + [Tags.InstanceNumber, String(z + 1)], + ] as Array<[string, string]>; + const merged = new Map([...metadata, ...Object.entries(tags)]); + 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 + * 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]: '' } }); + +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`; + return { + type: 'dicom', + instance, + parent: uriToDataSource( + `https://example.test/${name}`, + name, + FILE_EXT_TO_MIME.dcm + ), + } satisfies 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)); + +/** Fills each slice with its InstanceNumber, without a decoder worker. */ +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) + ), + components: 1, + }; +}; + +// Module scope, so a live image does not pin the factory's record of images. +const noThumbnail = () => ''; + +/** Records every DICOM image the store creates, decoding without workers. */ +export function imageFactory( + decoder: WholeInstanceDecode = instanceNumberDecoder +) { + const runtime = createDicomRuntime({ + ...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({ + runtime, + encodeThumbnail: noThumbnail, + }); + created.push(image); + return image; + }; + return { created, createImage, runtime }; +} + +/** The SOP Instance UIDs an image is built from, in planned order. */ +export const membersOf = (image: DicomVolumeImage) => + image.getInstances().map(sopOf); + +/** A single ultrasound multi-frame instance, which the store routes to cine. */ +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 fabacdaa7..ee158cb73 100644 --- a/src/store/__tests__/dicomTagFixtures.ts +++ b/src/store/__tests__/dicomTagFixtures.ts @@ -1,4 +1,4 @@ -import { Tags } from '@/src/core/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 5f87cf353..f87e5207d 100644 --- a/src/store/__tests__/duplicateDatasetSave.spec.ts +++ b/src/store/__tests__/duplicateDatasetSave.spec.ts @@ -1,21 +1,42 @@ +import { datasetFromTags, instanceFor } from '@/tests/dicomDataset'; 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 type { Chunk } from '@/src/core/streaming/chunk'; -import { Tags } from '@/src/core/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. */ +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,85 +55,76 @@ 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(); }); - const dicomBatch = (instances: string[]): DataSource => ({ + const dicomCollection = ( + instances: string[], + parent: (instance: string) => DataSource + ): DataSource => ({ type: 'collection', sources: instances.map((instance) => ({ - type: 'chunk', - chunk: { - metadata: [[Tags.SOPInstanceUID, instance]], - } as Chunk, - mime: FILE_EXT_TO_MIME.dcm, - parent: uriToDataSource( + type: 'dicom', + instance: instanceFor(datasetFromTags([[Tags.SOPInstanceUID, instance]])), + parent: parent(instance), + })), + }); + + const dicomBatch = (instances: string[]) => + dicomCollection(instances, (instance) => + uriToDataSource( `https://ex/series/${instance}.dcm`, `${instance}.dcm`, FILE_EXT_TO_MIME.dcm - ), - })), - }); + ) + ); - const localDicomBatch = (instances: string[]): DataSource => ({ - type: 'collection', - sources: instances.map((instance) => ({ - type: 'chunk', - chunk: { - metadata: [[Tags.SOPInstanceUID, instance]], - } as Chunk, - mime: FILE_EXT_TO_MIME.dcm, - parent: { - type: 'file', - file: new File([instance], `${instance}.dcm`, { - type: FILE_EXT_TO_MIME.dcm, - lastModified: 1, - }), - fileType: FILE_EXT_TO_MIME.dcm, - }, - })), + const localDicomBatch = (instances: string[]) => + dicomCollection(instances, (instance) => ({ + type: 'file', + file: new File([instance], `${instance}.dcm`, { + type: FILE_EXT_TO_MIME.dcm, + lastModified: 1, + }), + fileType: FILE_EXT_TO_MIME.dcm, + })); + + it('retains the original local file when a duplicate SOP supplies other pixels', async () => { + const store = useDatasetStore(); + const original = localDicomBatch(['sop-1']); + const duplicate = dicomCollection(['sop-1'], () => ({ + type: 'file', + file: new File(['different pixels'], 'sop-1.dcm'), + fileType: FILE_EXT_TO_MIME.dcm, + })); + store.addDataSources([{ dataID: 'series-1', dataSource: original }]); + store.addDataSources([{ dataID: 'series-1', dataSource: duplicate }]); + const { zip, manifest } = await save(); + const [filePath] = Object.values(manifest.datasetFilePath!); + expect(await zip.file(filePath)!.async('string')).toBe('sop-1'); }); - it('merges complementary DICOM batches into one complete saved dataset', async () => { + // A re-import reports every member the volume now holds, so the later + // collection is the complete one. + it('saves the membership the latest import reports for a dataset', async () => { const store = useDatasetStore(); store.addDataSources([ { dataID: 'series-1', dataSource: dicomBatch(['sop-1', 'sop-2']) }, ]); store.addDataSources([ - { dataID: 'series-1', dataSource: dicomBatch(['sop-3', 'sop-4']) }, + { + dataID: 'series-1', + dataSource: dicomBatch(['sop-1', 'sop-2', 'sop-3', 'sop-4']), + }, ]); - 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(); }); @@ -125,23 +137,35 @@ 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', () => { + const store = useDatasetStore(); + store.addDataSources([ + { dataID: 'series-1', dataSource: dicomBatch(['sop-1', 'sop-2']) }, + ]); + store.addDataSources([ + { dataID: 'series-1', dataSource: dicomBatch(['sop-1']) }, + ]); + + const source = store.getDataSource('series-1'); + if (source?.type !== 'collection') throw new Error('Expected collection'); + expect(source.sources).toHaveLength(1); + }); + + it('keeps remote provenance for a member the re-import supplies locally', () => { + const store = useDatasetStore(); + store.addDataSources([ + { dataID: 'series-1', dataSource: dicomBatch(['sop-1', 'sop-2']) }, + ]); + store.addDataSources([ + { dataID: 'series-1', dataSource: localDicomBatch(['sop-1', 'sop-2']) }, + ]); + + expect(isRemoteDataSource(store.getDataSource('series-1'))).toBe(true); }); it('replaces local provenance when the same instances are re-imported remotely', () => { @@ -156,3 +180,28 @@ describe('dataset provenance dedup on re-import', () => { expect(isRemoteDataSource(store.getDataSource('series-1'))).toBe(true); }); }); + +it('saves one shared archive File used by distinct restored dataset leaves', async () => { + setActivePinia(createPinia()); + const file = new File(['zip bytes'], 'series.zip', { + type: 'application/zip', + }); + const store = useDatasetStore(); + store.addDataSources( + ['a', 'b'].map((name) => ({ + dataID: name, + dataSource: { + type: 'archive' as const, + path: name + '/slice.dcm', + parent: { type: 'file' as const, file, fileType: 'application/zip' }, + }, + })) + ); + const { zip, manifest } = await save(); + expect(manifest.datasets).toHaveLength(2); + expect( + manifest.dataSources.filter((source) => source.type === 'file') + ).toHaveLength(1); + expect(Object.keys(manifest.datasetFilePath!)).toHaveLength(1); + expect(() => normalizeManifest(manifest, zip)).not.toThrow(); +}); diff --git a/src/store/__tests__/image-cache.spec.ts b/src/store/__tests__/image-cache.spec.ts index f4f002d0d..f5a183655 100644 --- a/src/store/__tests__/image-cache.spec.ts +++ b/src/store/__tests__/image-cache.spec.ts @@ -4,6 +4,14 @@ 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, + type ProgressiveImageEvents, +} from '@/src/core/progressiveImage'; +import { getEnFaceUnavailableReason } from '@/src/enface/availability'; +import mitt from 'mitt'; const seatImage = () => { const data = vtkImageData.newInstance(); @@ -42,4 +50,51 @@ describe('image cache lifecycle', () => { expect(store.getVtkImageData('img-1')).toBeNull(); }); + + // 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'); + const events = mitt(); + 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.' + ); + events.emit('status', 'complete'); + expect(getEnFaceUnavailableReason('retry')).toBe( + 'The volume failed to load completely.' + ); + events.emit('loading', true); + events.emit('loading', false); + events.emit('status', 'complete'); + expect(getEnFaceUnavailableReason('retry')).toBeNull(); + }); }); 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/datasets-dicom.ts b/src/store/datasets-dicom.ts index 504a7b529..2bd63a47b 100644 --- a/src/store/datasets-dicom.ts +++ b/src/store/datasets-dicom.ts @@ -1,21 +1,37 @@ import { defineStore } from 'pinia'; -import { Image } from 'itk-wasm'; -import * as DICOM from '@/src/io/dicom'; -import { Chunk } from '@/src/core/streaming/chunk'; +import { + allocateVolume, + type Volume, +} from '@/src/dicom/core/volume/allocateVolume'; +import { + emptyRegistry, + forgetCollection, + registerInstances, + type InstanceCollectionUpdate, + type RegistryState, +} from '@/src/dicom/core/collections/instanceRegistry'; +import { + getDatasetModality, + getDatasetTag, +} 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 DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; +import type { ProgressiveImage } from '@/src/core/progressiveImage'; import DicomCineImage from '@/src/core/cine/DicomCineImage'; -import { parseCineDicom } from '@/src/core/cine/parseCineDicom'; -import { isUltrasoundMultiframeSopClass, Tags } from '@/src/core/dicomTags'; -import { removeFromArray } from '../utils'; +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 '@/src/dicom/core/collections/groupBy'; export const ANONYMOUS_PATIENT = 'Anonymous'; export const ANONYMOUS_PATIENT_ID = 'ANONYMOUS'; -export function imageCacheMultiKey(offset: number, asThumbnail: boolean) { - return `${offset}!!${asThumbnail}`; -} - export type VolumeKeys = { patientKey: string; studyKey: string; @@ -47,18 +63,15 @@ export type VolumeInfo = { SeriesDescription: string; WindowLevel: string; WindowWidth: string; + // Names the scan a split volume was separated out as ('acquisition 2', + // 'phase 3, echo 1'). Absent on volumes that were not split. + splitLabel?: string; // For 'cine', NumberOfSlices is the frame count. Optional for back-compat // with saved state that predates the field. kind?: 'volume' | 'cine'; }; type State = { - // volumeKey -> imageCacheMultiKey -> ITKImage - sliceData: Record>; - - // volume invalidation information - needsRebuild: Record; - // patientKey -> patient info patientInfo: Record; // patientKey -> array of studyKeys @@ -84,30 +97,18 @@ type State = { * @param name * @returns string */ -const cleanupName = (name: string) => { - return name.trim().replace(/\s+/g, ' '); +const cleanupName = (name: string | undefined) => { + return (name ?? '').trim().replace(/\s+/g, ' '); }; export const getDisplayName = (info: VolumeInfo) => { - return ( + const name = cleanupName(info.SeriesDescription || info.SeriesNumber) || - info.SeriesInstanceUID - ); + info.SeriesInstanceUID || + 'Unnamed series'; + return info.splitLabel ? `${name} (${info.splitLabel})` : name; }; -export function isCineChunkGroup(chunks: Chunk[]): boolean { - if (chunks.length !== 1) return false; - const meta = chunks[0].metadata; - if (!meta) return false; - const lookup = Object.fromEntries(meta); - const sopClass = lookup[Tags.SOPClassUID] ?? ''; - const numberOfFrames = parseInt( - (lookup[Tags.NumberOfFrames] ?? '0').trim(), - 10 - ); - return isUltrasoundMultiframeSopClass(sopClass) && numberOfFrames > 1; -} - export const getWindowLevels = (info: VolumeInfo) => { const { WindowWidth, WindowLevel } = info; if ( @@ -135,9 +136,278 @@ export const getWindowLevels = (info: VolumeInfo) => { return widths.map((width, i) => ({ width, level: levels[i] })); }; +export type ImportInstancesDeps = { + createImage?: (id: string) => DicomVolumeImage; + /** + * Removes a volume a replan dissolved from everything that names it, before + * its replacements are reported. This store and the image cache alone by + * default; the app hands in the dataset store's removal so layers, view + * configuration and statistics let go of the image before it is evicted. + */ + removeDissolved?: (id: string) => void; +}; + +export type ImportInstancesResult = { + // Collection ID to every instance whose provenance the collection now + // covers, not just the ones this batch brought. + volumes: Record; + // Each series commits on its own; these are the ones that did not. + failures: { error: Error; instances: Instance[] }[]; +}; + +type DatabaseRecord = { + patient: PatientInfo; + study: StudyInfo; + volume: VolumeInfo; + // What the planner wants the user told about this collection. + warnings: string[]; +}; + +/** + * One collection's next value, computed before any store is touched. `keep` + * is a collection already shown as it is planned; `fill` gives a DICOM image + * its new volume or SEG object. + */ +type Candidate = { id: string; record: DatabaseRecord } & ( + | { kind: 'keep' } + | { kind: 'cine'; image: DicomCineImage } + | { + kind: 'dicom'; + shown: DicomVolumeImage | undefined; + fill: (image: DicomVolumeImage) => void; + } +); + +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 = ({ + id, + members, + collection, +}: InstanceCollectionUpdate): DatabaseRecord => { + const { dataset } = members[0]; + 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, + ...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, + clip: Instance, + numberOfFrames: number +): DatabaseRecord => { + const { patient, study, series } = describeSeries(clip.dataset); + return { + patient, + study, + volume: { + NumberOfSlices: numberOfFrames, + VolumeID: id, + ...series, + WindowLevel: '', + WindowWidth: '', + kind: 'cine', + }, + warnings: [], + }; +}; + +// 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( + id: string, + clip: Instance, + cached: ProgressiveImage | undefined +): Candidate { + const header = readCineHeader(clip); + const record = cineRecord(id, clip, header.numberOfFrames); + return cached + ? { kind: 'keep', id, record } + : { kind: 'cine', id, record, image: new DicomCineImage(clip, header) }; +} + +function fillFor(update: InstanceCollectionUpdate, previous?: Volume) { + if (isSegmentation(update)) + 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 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.unchanged) return { kind: 'keep', id, record }; + const shown = cached instanceof DicomVolumeImage ? cached : undefined; + return { + kind: 'dicom', + id, + record, + shown, + fill: fillFor(update, shown?.getVolume() ?? undefined), + }; +} + +type CommitTarget = { + _updateDatabase: ( + patient: PatientInfo, + study: StudyInfo, + volume: VolumeInfo + ) => void; + volumeInfo: Record; +}; + +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( + candidate: Exclude, + createImage: (id: string) => DicomVolumeImage +) { + const cache = useImageCacheStore(); + const { id } = candidate; + if (candidate.kind === 'cine') { + cache.addProgressiveImage(candidate.image, { id }); + return candidate.image; + } + const image = candidate.shown ?? createImage(id); + candidate.fill(image); + if (candidate.shown) image.startLoad(); + else cache.addProgressiveImage(image, { id }); + return image; +} + +function commitCandidate( + store: CommitTarget, + candidate: Candidate, + createImage: (id: string) => DicomVolumeImage +) { + 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); + image?.startLoad(); + return; + } + showCandidate(candidate, createImage).setName(name); +} + +function reportDissolved( + store: CommitTarget, + dissolved: string[], + removeDissolved: (id: string) => void +) { + dissolved.forEach((id) => { + const previous = store.volumeInfo[id]; + removeDissolved(id); + // Whatever the user attached to the dissolved dataset went with it. + if (previous) + useMessageStore().addWarning( + 'A DICOM volume was regrouped', + `${getDisplayName(previous)} was regrouped into other volumes of its ` + + 'series. Annotations and view settings made on it were removed.' + ); + }); +} + +const reportConflicts = (uids: string[]) => { + if (!uids.length) return; + useMessageStore().addWarning( + 'DICOM instances share an identifier', + 'Files with conflicting metadata reuse SOP Instance UID(s): ' + + uids.join(', ') + + '. Only the first copy was retained. Check the source files before saving the session.' + ); +}; + +// Kept outside reactive state: a fresh pinia plans from nothing. +const registries = new WeakMap(); + +const registryOf = (store: object) => registries.get(store) ?? emptyRegistry; + export const useDICOMStore = defineStore('dicom', { state: (): State => ({ - sliceData: {}, patientInfo: {}, patientStudies: {}, studyInfo: {}, @@ -145,138 +415,60 @@ export const useDICOMStore = defineStore('dicom', { volumeInfo: {}, volumeStudy: {}, studyPatient: {}, - needsRebuild: {}, }), actions: { - async importChunks(chunks: Chunk[]) { - const imageCacheStore = useImageCacheStore(); + /** + * Plans, allocates and publishes each series of the batch in one + * synchronous step. A series that fails to plan or allocate changes + * nothing, because nothing computed for it is assigned. + */ + importInstances( + instances: Instance[], + deps: ImportInstancesDeps = {} + ): ImportInstancesResult { + const createImage = + deps.createImage ?? + ((id: string) => + new DicomVolumeImage({ focus: () => viewedSlice(id) })); + const removeDissolved = + deps.removeDissolved ?? + ((id: string) => { + this.deleteVolume(id); + useImageCacheStore().removeImage(id); + }); + const failures: ImportInstancesResult['failures'] = []; + const committed = [ + ...groupBy(instances, (instance) => seriesKeyOf(instance.dataset)), + ].flatMap(([, batch]) => { + try { + return Object.entries( + this._commitSeries(batch, { createImage, removeDissolved }) + ); + } catch (error) { + failures.push({ error: ensureError(error), instances: batch }); + return []; + } + }); + return { volumes: Object.fromEntries(committed), failures }; + }, - // split into groups - const chunksByVolume = await DICOM.splitAndSort( - chunks, - (chunk) => chunk.metaBlob! + _commitSeries( + batch: Instance[], + context: Required + ): ImportInstancesResult['volumes'] { + const { state, updates, removed, conflictingInstanceUids } = + registerInstances(registryOf(this), batch); + const candidates = updates.map(planCandidate); + + registries.set(this, state); + candidates.forEach((candidate) => + commitCandidate(this, candidate, context.createImage) ); - - await Promise.all( - Object.entries(chunksByVolume).map(async ([id, sortedChunks]) => { - if (isCineChunkGroup(sortedChunks)) { - const importedAsCine = await this._importCineChunk( - id, - sortedChunks[0] - ); - if (importedAsCine) return; - } - - const cachedImage = imageCacheStore.imageById[id]; - if (cachedImage && !(cachedImage instanceof DicomChunkImage)) { - throw new Error( - `Volume ${id} is already loaded as a non-chunk progressive image; cannot re-import as a chunk volume.` - ); - } - const image = cachedImage ?? new DicomChunkImage(); - - await image.addChunks(sortedChunks); - // Registration starts the first load; a re-import starts its own. - if (cachedImage) image.startLoad(); - else imageCacheStore.addProgressiveImage(image, { id }); - - // update database - const metaPairs = image.getDicomMetadata(); - if (!metaPairs) throw new Error('Metdata not ready'); - const metadata = Object.fromEntries(metaPairs); - - const patientInfo: PatientInfo = { - PatientID: metadata[Tags.PatientID], - PatientName: metadata[Tags.PatientName], - PatientBirthDate: metadata[Tags.PatientBirthDate], - PatientSex: metadata[Tags.PatientSex], - }; - - const studyInfo: StudyInfo = { - 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 volumeInfo: VolumeInfo = { - NumberOfSlices: image.getChunks().length, - VolumeID: id, - Modality: metadata[Tags.Modality], - SeriesInstanceUID: metadata[Tags.SeriesInstanceUID], - SeriesNumber: metadata[Tags.SeriesNumber], - SeriesDescription: metadata[Tags.SeriesDescription], - WindowLevel: metadata[Tags.WindowLevel], - WindowWidth: metadata[Tags.WindowWidth], - kind: 'volume', - }; - - this._updateDatabase(patientInfo, studyInfo, volumeInfo); - - // save the image name - image.setName(getDisplayName(volumeInfo)); - }) + reportDissolved(this, removed, context.removeDissolved); + reportConflicts(conflictingInstanceUids); + return Object.fromEntries( + updates.map(({ id, provenance }) => [id, provenance]) ); - - return chunksByVolume; - }, - - async _importCineChunk(id: string, chunk: Chunk): Promise { - const imageCacheStore = useImageCacheStore(); - - // If we already created this cine image (state-file reload), bail. - if (this.volumeInfo[id]?.kind === 'cine') { - return true; - } - - const cachedImage = imageCacheStore.imageById[id]; - if (cachedImage && !(cachedImage instanceof DicomCineImage)) { - throw new Error( - `Volume ${id} is already loaded as a non-cine progressive image; cannot re-import as a cine clip.` - ); - } - - await chunk.loadData(); - const blob = chunk.dataBlob; - if (!blob) throw new Error('Cine DICOM chunk has no data'); - const buffer = await blob.arrayBuffer(); - let parsed: ReturnType; - try { - parsed = parseCineDicom(buffer); - } catch (err) { - console.warn( - 'Failed to parse cine DICOM; falling back to volume import', - err - ); - return false; - } - - if (!DicomCineImage.isSupported(parsed.header)) { - return false; - } - - const image = new DicomCineImage(parsed); - imageCacheStore.addProgressiveImage(image, { id }); - - const { patient, study, series } = parsed.header; - const volumeInfo: VolumeInfo = { - NumberOfSlices: parsed.header.numberOfFrames, - VolumeID: id, - Modality: series.Modality, - SeriesInstanceUID: series.SeriesInstanceUID, - SeriesNumber: series.SeriesNumber, - SeriesDescription: series.SeriesDescription, - WindowLevel: '', - WindowWidth: '', - kind: 'cine', - }; - - this._updateDatabase(patient, study, volumeInfo); - - image.setName(getDisplayName(volumeInfo)); - return true; }, _updateDatabase( @@ -301,20 +493,22 @@ export const useDICOMStore = defineStore('dicom', { } if (!(volumeKey in this.volumeInfo)) { - this.volumeInfo[volumeKey] = volume; this.volumeStudy[volumeKey] = studyKey; - this.sliceData[volumeKey] = {}; this.studyVolumes[studyKey].push(volumeKey); } + // A re-import grows the membership, so the record is rewritten. + this.volumeInfo[volumeKey] = volume; }, // You should probably call datasetStore.remove instead as this does not // 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]; delete this.volumeInfo[volumeKey]; - delete this.sliceData[volumeKey]; delete this.volumeStudy[volumeKey]; removeFromArray(this.studyVolumes[studyKey], 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/datasets.ts b/src/store/datasets.ts index 11472710f..d4039966e 100644 --- a/src/store/datasets.ts +++ b/src/store/datasets.ts @@ -9,7 +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 { Tags } from '@/src/core/dicomTags'; +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', @@ -21,12 +24,17 @@ interface LoadedData { dataSource: DataSource; } +function dicomInstanceIdentity(instance: Instance): string | undefined { + const sopInstanceUID = trimDicomPadding( + getDatasetTag(instance.dataset, Tags.SOPInstanceUID) ?? '' + ); + return sopInstanceUID ? `dicom:${sopInstanceUID}` : undefined; +} + function sourceIdentity(dataSource: DataSource): string | undefined { - if (dataSource.type === 'chunk') { - const sopInstanceUID = dataSource.chunk.metadata - ?.find(([tag]) => tag === Tags.SOPInstanceUID)?.[1] - ?.trim(); - if (sopInstanceUID) return `dicom:${sopInstanceUID}`; + if (dataSource.type === 'dicom') { + const identity = dicomInstanceIdentity(dataSource.instance); + if (identity) return identity; } if (dataSource.type === 'uri') return `uri:${dataSource.uri}`; @@ -50,21 +58,37 @@ function sourceIdentity(dataSource: DataSource): string | undefined { return undefined; } +// Remote provenance survives a merge: it is the copy that can be re-fetched +// when the session is restored. +const preferRemote = (incoming: DataSource, kept: DataSource) => + isRemoteDataSource(incoming) && !isRemoteDataSource(kept); + +/** + * The incoming collection names every member the dataset now covers, so it + * decides membership: a member the dataset no longer holds (moved to a sibling + * volume by a replan) is dropped. The existing collection only contributes a + * retained copy of a member unless the incoming source adds remote provenance. + */ function mergeCollectionSources( existing: DataSource, incoming: DataSource ): DataSource { if (existing.type !== 'collection' || incoming.type !== 'collection') { - return isRemoteDataSource(incoming) && !isRemoteDataSource(existing) - ? incoming - : existing; + return preferRemote(incoming, existing) ? incoming : existing; } + const priorByIdentity = new Map(); + existing.sources.forEach((source) => { + const identity = sourceIdentity(source); + if (identity !== undefined && !priorByIdentity.has(identity)) + priorByIdentity.set(identity, source); + }); + const merged: DataSource[] = []; const indexByIdentity = new Map(); const seenByReference = new Set(); - [...existing.sources, ...incoming.sources].forEach((source) => { + incoming.sources.forEach((source) => { const identity = sourceIdentity(source); if (identity === undefined) { if (!seenByReference.has(source)) { @@ -75,16 +99,15 @@ function mergeCollectionSources( } const existingIndex = indexByIdentity.get(identity); - if (existingIndex === undefined) { - indexByIdentity.set(identity, merged.length); - merged.push(source); + if (existingIndex !== undefined) { + if (preferRemote(source, merged[existingIndex])) + merged[existingIndex] = source; return; } - const kept = merged[existingIndex]; - if (isRemoteDataSource(source) && !isRemoteDataSource(kept)) { - merged[existingIndex] = source; - } + const prior = priorByIdentity.get(identity); + indexByIdentity.set(identity, merged.length); + merged.push(prior && !preferRemote(source, prior) ? prior : source); }); return { type: 'collection', sources: merged }; @@ -102,6 +125,7 @@ function serializeLoadedData(loadedDataSources: Array) { const serializedDependencies: Array = []; const dataIDToDataSourceID: Record = {}; const files: Record = {}; + const fileToSourceId = new Map(); function serializeDataSource(ds: DataSource): number { if (dataSourceToId.has(ds)) { @@ -116,8 +140,11 @@ function serializeLoadedData(loadedDataSources: Array) { return serializeDataSource(ds.parent); } + const existingFile = fileToSourceId.get(ds.file); + if (existingFile !== undefined) return existingFile; const id = nextId(); dataSourceToId.set(ds, id); + fileToSourceId.set(ds.file, id); const fileId = nextId(); files[fileId] = ds.file; @@ -170,12 +197,12 @@ function serializeLoadedData(loadedDataSources: Array) { return id; } - if (type === 'chunk') { - // chunk derives from the parent. Just return the serialized parent. + if (type === 'dicom') { + // An instance derives from the parent. Just return the serialized parent. if (ds.parent) { return serializeDataSource(ds.parent); } - throw new Error('Chunk does not have a parent'); + throw new Error('DICOM instance does not have a parent'); } throw new Error(`Invalid data source type: ${type as string}`); @@ -279,10 +306,10 @@ export const useDatasetStore = defineStore('dataset', () => { function addDataSources(sources: Array) { // Re-importing the same data yields the same dataID (e.g. the same DICOM - // series dragged in twice). Keep one dataset entry while merging distinct - // collection members so incremental imports retain every slice. Duplicate - // DICOM instances are keyed by SOP Instance UID, preferring remote - // provenance when both local and remote forms are available. + // series dragged in twice). Keep one dataset entry and let the incoming + // collection, which names every member the volume now holds, decide its + // provenance. Duplicate DICOM instances are keyed by SOP Instance UID, + // preferring remote provenance when both local and remote forms exist. const byId = new Map(loadedData.value.map((d) => [d.dataID, d])); sources.forEach((d) => { const existing = byId.get(d.dataID); diff --git a/src/store/dicom-runtime.ts b/src/store/dicom-runtime.ts new file mode 100644 index 000000000..338125499 --- /dev/null +++ b/src/store/dicom-runtime.ts @@ -0,0 +1,20 @@ +import { defineStore } from 'pinia'; +import { markRaw, onScopeDispose } from 'vue'; +import { createDicomRuntime } from '@/src/dicom/core/runtime/createDicomRuntime'; +import { $fetch } from '@/src/utils/fetch'; +import itkConfig from '@/src/io/itk/itkConfig'; + +/** Each application instance owns its metadata workers, decoders and requests. */ +export const useDicomRuntimeStore = defineStore('dicom-runtime', () => { + const runtime = markRaw( + createDicomRuntime({ + fetch: $fetch, + assets: { + pipelineWorkerUrl: itkConfig.pipelineWorkerUrl, + imageIOUrl: itkConfig.imageIOUrl, + }, + }) + ); + onScopeDispose(() => runtime.dispose()); + return { runtime }; +}); diff --git a/src/store/dicom-viewed-slice.ts b/src/store/dicom-viewed-slice.ts new file mode 100644 index 000000000..c1eed8c46 --- /dev/null +++ b/src/store/dicom-viewed-slice.ts @@ -0,0 +1,28 @@ +import { useImageCacheStore } from '@/src/store/image-cache'; +import { useViewStore } from '@/src/store/views'; +import { useViewSliceStore } from '@/src/store/view-configs/slicing'; +import type { ViewInfo, ViewInfo2D } from '@/src/types/views'; + +// A DICOM volume's third index axis is its acquisition axis. +const SLICE_AXIS = 2; + +/** + * The slice of `dataID` a 2D view looking along its acquisition axis shows, + * preferring the active view; undefined when no view shows one yet. + */ +export function viewedSlice(dataID: string) { + const views = useViewStore(); + const metadata = useImageCacheStore().getImageMetadata(dataID); + if (!metadata) return undefined; + const alongSlices = views.visibleViews.filter( + (view: ViewInfo): view is ViewInfo2D => + view.type === '2D' && + view.dataID === dataID && + metadata.lpsOrientation[view.options.orientation] === SLICE_AXIS + ); + const view = + alongSlices.find(({ id }) => id === views.activeView) ?? alongSlices[0]; + return view + ? useViewSliceStore().configs[view.id]?.[dataID]?.slice + : undefined; +} diff --git a/src/store/dicom-web/dicom-web-store.ts b/src/store/dicom-web/dicom-web-store.ts index 019af0d58..300ff77f1 100644 --- a/src/store/dicom-web/dicom-web-store.ts +++ b/src/store/dicom-web/dicom-web-store.ts @@ -22,6 +22,11 @@ import { Instance, } from '@/src/core/dicom-web-api'; import { useViewStore } from '@/src/store/views'; +import { + isVolumeResult, + type ImportDataSourcesResult, +} from '@/src/io/import/common'; +import { trimDicomPadding } from '@/src/dicom/core/utils'; const DICOM_WEB_URL_PARAM = 'dicomweb'; @@ -72,6 +77,38 @@ 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') + ); + // One notice for the series, however many of its files failed. + if (failures.length > 0) + useMessageStore().addError( + `${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. + 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 */ @@ -164,7 +201,11 @@ export const useDicomWebStore = defineStore('dicom-web', () => { const volumes = ref({} as Progress); - const downloadVolume = async (volumeKey: string) => { + const downloadVolume = async ( + volumeKey: string, + retrieve = fetchSeries, + importSources = importDataSources + ) => { const dicoms = useDicomMetaStore(); if (!isDownloadable(volumes.value[volumeKey])) return; @@ -194,7 +235,7 @@ export const useDicomWebStore = defineStore('dicom-web', () => { studyInstanceUID: studyInfo.StudyInstanceUID, seriesInstanceUID: volumeInfo.SeriesInstanceUID, }; - const files = await fetchSeries( + const files = await retrieve( cleanHost.value, seriesInfo, progressCallback @@ -204,15 +245,12 @@ export const useDicomWebStore = defineStore('dicom-web', () => { throw new Error('Could not fetch series'); } - const [loadResult] = await importDataSources(files.map(fileToDataSource)); - if (!loadResult) { + const results = await importSources(files.map(fileToDataSource)); + if (results.length === 0) { throw new Error('Did not receive a load result'); } - if (loadResult.type === 'error') { - throw loadResult.error; - } - - const selection = convertSuccessResultToDataSelection(loadResult); + const primaryResult = primaryVolumeResult(results); + const selection = convertSuccessResultToDataSelection(primaryResult); useViewStore().setDataForAllViews(selection); volumes.value[volumeKey] = { ...volumes.value[volumeKey], @@ -305,17 +343,24 @@ export const useDicomWebStore = defineStore('dicom-web', () => { loadedDicoms.$onAction(({ name, args, after }) => { if (name !== 'deleteVolume') return; + const [loadedVolumeKey] = args; + const seriesInstanceUID = trimDicomPadding( + loadedDicoms.volumeInfo[loadedVolumeKey]?.SeriesInstanceUID ?? '' + ); + after(() => { - const [loadedVolumeKey] = args; - const volumeKey = Object.keys(volumes.value).find((key) => - loadedVolumeKey.startsWith(key) + if (!seriesInstanceUID || !(seriesInstanceUID in volumes.value)) return; + // A split series loads as several volumes with one Series Instance UID; + // only mark the series remote when the last of them is deleted. + const stillLoaded = Object.values(loadedDicoms.volumeInfo).some( + (info) => trimDicomPadding(info.SeriesInstanceUID) === seriesInstanceUID ); - if (volumeKey) - volumes.value[volumeKey] = { - ...volumes.value[volumeKey], - state: 'Remote', - loaded: 0, - }; + if (stillLoaded) return; + volumes.value[seriesInstanceUID] = { + ...volumes.value[seriesInstanceUID], + state: 'Remote', + loaded: 0, + }; }); }); diff --git a/src/store/image-cache.ts b/src/store/image-cache.ts index 3e33722f8..6d6dff169 100644 --- a/src/store/image-cache.ts +++ b/src/store/image-cache.ts @@ -55,14 +55,17 @@ export const useImageCacheStore = defineStore('image-cache', () => { imageStatus[id] = status; }; const onLoading = (loading: boolean) => { + 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/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); } }); diff --git a/src/store/view-configs/layers.ts b/src/store/view-configs/layers.ts index f9c0393b4..28f1df153 100644 --- a/src/store/view-configs/layers.ts +++ b/src/store/view-configs/layers.ts @@ -1,3 +1,4 @@ +import { getWindowMetadata } from '@/src/utils/dicom/windowMetadata'; import vtkPiecewiseFunctionProxy from '@kitware/vtk.js/Proxy/Core/PiecewiseFunctionProxy'; import { defineStore } from 'pinia'; import { reactive } from 'vue'; @@ -10,7 +11,7 @@ import { import { Maybe } from '@/src/types'; import { resolveLayerColorPreset } from '@/src/vtk/LayerColorPresets'; import { useImageCacheStore } from '@/src/store/image-cache'; -import DicomChunkImage from '@/src/core/streaming/dicomChunkImage'; +import DicomVolumeImage from '@/src/core/streaming/dicomVolumeImage'; import { getConsistentDicomWindowRange } from '@/src/utils/dicomWindowRange'; import { DEFAULT_PRESET_BY_MODALITY } from '@/src/config'; import { @@ -116,15 +117,15 @@ export const useLayerColoringStore = defineStore('layerColoring', () => { const source = layer && imageCacheStore.imageById[layer.selection]; if (!scalarImage) { const modality = - source instanceof DicomChunkImage ? source.getModality() : undefined; + source instanceof DicomVolumeImage ? source.getModality() : undefined; return defaultMulticomponentConfig(imageDataRange, modality); } const isPET = - source instanceof DicomChunkImage && source.getModality() === 'PT'; + source instanceof DicomVolumeImage && source.getModality() === 'PT'; const dicomRange = isPET ? getConsistentDicomWindowRange( - source.getChunks().map((chunk) => chunk.metadata) + source.getInstances().map(({ dataset }) => getWindowMetadata(dataset)) ) : undefined; return { diff --git a/src/types/image.ts b/src/types/image.ts index d33d4602b..32275068b 100644 --- a/src/types/image.ts +++ b/src/types/image.ts @@ -2,7 +2,7 @@ import { mat3, mat4, vec3 } from 'gl-matrix'; import type { Bounds } from '@kitware/vtk.js/types'; import { LPSDirections } from './lps'; -export interface ImageMetadata { +export type ImageMetadata = { name: string; orientation: mat3; lpsOrientation: LPSDirections; @@ -12,4 +12,4 @@ export interface ImageMetadata { worldBounds: Bounds; worldToIndex: mat4; indexToWorld: mat4; -} +}; diff --git a/src/utils/__tests__/allocateImageFromChunks.spec.ts b/src/utils/__tests__/allocateImageFromChunks.spec.ts deleted file mode 100644 index 3ecb3b4e0..000000000 --- a/src/utils/__tests__/allocateImageFromChunks.spec.ts +++ /dev/null @@ -1,417 +0,0 @@ -import type { Chunk } from '@/src/core/streaming/chunk'; -import { Tags } from '@/src/core/dicomTags'; -import { - allocateImageFromChunks, - getPixelFormat, - getRescaledValueRange, - getBufferValueRange, - getTypedArrayForDataRange, - getTypedArrayValueRange, - getVolumeBufferType, - samplesAreIntegral, - valuesFitBuffer, -} from '@/src/utils/allocateImageFromChunks'; -import { describe, it, expect } from 'vitest'; - -function chunk(overrides: Record = {}) { - const metadata = { - [Tags.SOPInstanceUID]: '1.2.3', - [Tags.ImagePositionPatient]: '0\\0\\0', - [Tags.ImageOrientationPatient]: '1\\0\\0\\0\\1\\0', - [Tags.Rows]: '3', - [Tags.Columns]: '4', - [Tags.BitsStored]: '16', - [Tags.PixelRepresentation]: '0', - [Tags.SamplesPerPixel]: '1', - ...overrides, - }; - return { - metadata: Object.entries(metadata), - } as unknown as Chunk; -} - -function positionedChunk(z: number, overrides: Record = {}) { - return chunk({ - [Tags.ImagePositionPatient]: `0\\0\\${z}`, - ...overrides, - }); -} - -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(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(Int32Array); - }); - - 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('uses Float64 when fractional rescale has integral endpoints', () => { - expect( - getVolumeBufferType([ - format({ - [Tags.BitsStored]: '12', - [Tags.RescaleSlope]: '0.2', - [Tags.RescaleIntercept]: '0', - }), - ]) - ).toBe(Float64Array); - }); - - 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(Float64Array); - }); -}); - -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); - }); - - it('accepts anything bound for a float buffer', () => { - expect( - samplesAreIntegral(new Float64Array([0.5, 1e30]), new Float64Array(1)) - ).toBe(true); - }); -}); - -describe('allocateImageFromChunks', () => { - 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]], - ['NaN', [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 }), - ]); - 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('matches ITK spacing order for single-slice images with SpacingBetweenSlices', () => { - const image = allocateImageFromChunks([ - chunk({ - [Tags.PixelSpacing]: '2.5\\0.75', - [Tags.SpacingBetweenSlices]: '7.25', - }), - ]); - - 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', - }), - ]); - 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), - ]); - - expect(Array.from(image.getSpacing())).toEqual([0.75, 2.5, 9]); - }); -}); diff --git a/src/utils/__tests__/dicomWindowRange.spec.ts b/src/utils/__tests__/dicomWindowRange.spec.ts index 4481cbcd4..bb383476d 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 '@/src/core/dicomTags'; +import { Tags } from '@/src/dicom/core/metadata/dicomTags'; import { getConsistentDicomWindowRange } from '@/src/utils/dicomWindowRange'; function windowTags(center: string, width: string, voiFunction?: string) { @@ -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)( @@ -27,7 +28,7 @@ describe('DICOM window display range', () => { } ); - it('compares parsed values across chunks and defaults an absent function to LINEAR', () => { + it('compares parsed values across instances and defaults an absent function to LINEAR', () => { expect( getConsistentDicomWindowRange([ windowTags('1000', '2000'), @@ -47,7 +48,7 @@ describe('DICOM window display range', () => { }); it.each([ - ['no chunks', []], + ['no instances', []], ['missing first metadata', [undefined, windowTags('50', '100')]], ['missing later metadata', [windowTags('50', '100'), null]], ['missing center', [[[Tags.WindowWidth, '100']]]], diff --git a/src/utils/__tests__/fetch.spec.ts b/src/utils/__tests__/fetch.spec.ts index 0537edd0a..6e9a10edd 100644 --- a/src/utils/__tests__/fetch.spec.ts +++ b/src/utils/__tests__/fetch.spec.ts @@ -1,7 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { $fetch, setGlobalHeader, deleteGlobalHeader } from '@/src/utils/fetch'; -import { RequestPool } from '@/src/core/streaming/requestPool'; +import { createPinia, disposePinia, setActivePinia } from 'pinia'; +import { useDicomRuntimeStore } from '@/src/store/dicom-runtime'; describe('$fetch global-header merging', () => { let fetchStub: ReturnType; @@ -52,7 +53,7 @@ describe('$fetch global-header merging', () => { }); }); -describe('RequestPool default fetch is the authenticated $fetch', () => { +describe('the application DICOM loader uses authenticated $fetch', () => { let fetchStub: ReturnType; beforeEach(() => { @@ -66,11 +67,13 @@ describe('RequestPool default fetch is the authenticated $fetch', () => { vi.unstubAllGlobals(); }); - it('routes a default-pool request through $fetch so the bearer is attached', async () => { - // No custom fetchFn: the singleton/default path the streaming importers use. - const pool = new RequestPool(); - await pool.fetch(`${window.location.origin}/api/stream`); + it('attaches the bearer to requests through the application runtime', async () => { + const pinia = createPinia(); + setActivePinia(pinia); + const { runtime } = useDicomRuntimeStore(); + await runtime.fetch(`${window.location.origin}/api/stream`); const init = fetchStub.mock.calls[0][1] as RequestInit; expect(new Headers(init.headers).get('Authorization')).toBe('Bearer pool'); + disposePinia(pinia); }); }); diff --git a/src/utils/__tests__/parseContentRangeHeader.spec.ts b/src/utils/__tests__/parseContentRangeHeader.spec.ts deleted file mode 100644 index fe397107e..000000000 --- a/src/utils/__tests__/parseContentRangeHeader.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { parseContentRangeHeader } from '@/src/utils/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('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'); - }); - }); -}); diff --git a/src/utils/allocateImageFromChunks.ts b/src/utils/allocateImageFromChunks.ts deleted file mode 100644 index 8d6e2ab60..000000000 --- a/src/utils/allocateImageFromChunks.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { Chunk } from '@/src/core/streaming/chunk'; -import { Maybe } from '@/src/types'; -import { NAME_TO_TAG } from '@/src/core/dicomTags'; -import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; -import { Vector3 } from '@kitware/vtk.js/types'; -import { mat3, vec3 } from 'gl-matrix'; -import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray'; - -const ImagePositionPatientTag = NAME_TO_TAG.get('ImagePositionPatient')!; -const ImageOrientationPatientTag = NAME_TO_TAG.get('ImageOrientationPatient')!; -const PixelSpacingTag = NAME_TO_TAG.get('PixelSpacing')!; -const SpacingBetweenSlicesTag = NAME_TO_TAG.get('SpacingBetweenSlices')!; -const RowsTag = NAME_TO_TAG.get('Rows')!; -const ColumnsTag = NAME_TO_TAG.get('Columns')!; -const BitsStoredTag = NAME_TO_TAG.get('BitsStored')!; -const PixelRepresentationTag = NAME_TO_TAG.get('PixelRepresentation')!; -const SamplesPerPixelTag = NAME_TO_TAG.get('SamplesPerPixel')!; -const RescaleIntercept = NAME_TO_TAG.get('RescaleIntercept')!; -const RescaleSlope = NAME_TO_TAG.get('RescaleSlope')!; -const NumberOfFrames = NAME_TO_TAG.get('NumberOfFrames')!; - -function toVec(s: Maybe): number[] | null { - if (!s?.length) return null; - return s.split('\\').map((a) => Number(a)) as number[]; -} - -function isPositiveFiniteNumber(value: number) { - return Number.isFinite(value) && value > 0; -} - -function getInPlaneSpacing(value: Maybe): [number, number] { - const [row = 1, column = row] = toVec(value) ?? []; - return [ - isPositiveFiniteNumber(column) ? column : 1, - isPositiveFiniteNumber(row) ? row : 1, - ]; -} - -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 TypedArrayConstructor = - | typeof Int8Array - | typeof Uint8Array - | typeof Int16Array - | typeof Uint16Array - | typeof Int32Array - | typeof Uint32Array; - -const TYPED_ARRAY_VALUE_RANGES = new Map< - TypedArrayConstructor, - { 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 TypedArrayConstructor); -} - -/** - * 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`); -} - -function numberOr(value: Maybe, fallback: number) { - const text = value?.trim(); - if (!text) return fallback; - const num = Number(text); - return Number.isFinite(num) ? num : fallback; -} - -/** - * 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: Maybe>) { - const meta = new Map(metadata ?? []); - return { - bitsStored: numberOr(meta.get(BitsStoredTag), 0), - pixelRepresentation: numberOr(meta.get(PixelRepresentationTag), 0), - rescaleSlope: numberOr(meta.get(RescaleSlope), 1), - rescaleIntercept: numberOr(meta.get(RescaleIntercept), 0), - }; -} - -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) }; -} - -/** - * 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[]) { - 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'); - - const needsFloat64 = usable.some( - ({ format, range }) => - !Number.isInteger(format.rescaleSlope) || - !Number.isInteger(format.rescaleIntercept) || - !Number.isSafeInteger(range.min) || - !Number.isSafeInteger(range.max) - ); - if (needsFloat64) 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; - - // NOTE(fli): might be better to assume (u)int16 and re-allocate to (u)int32 - // if needed, since the data range might actually fit in a smaller datatype. - return getTypedArrayForDataRange(min, max); -} - -export function allocateImageFromChunks(sortedChunks: Chunk[]) { - if (sortedChunks.length === 0) { - throw new Error('Cannot allocate an image from zero chunks'); - } - - // use the first chunk as the source of metadata - const meta = new Map(sortedChunks[0].metadata!); - const imagePositionPatient = toVec(meta.get(ImagePositionPatientTag)); - const imageOrientationPatient = toVec(meta.get(ImageOrientationPatientTag)); - const pixelSpacing = getInPlaneSpacing(meta.get(PixelSpacingTag)); - const spacingBetweenSlices = Number(meta.get(SpacingBetweenSlicesTag)); - const rows = Number(meta.get(RowsTag) ?? 0); - const columns = Number(meta.get(ColumnsTag) ?? 0); - const volumeFormats = sortedChunks.map((chunk) => - getPixelFormat(chunk.metadata) - ); - const samplesPerPixel = Number(meta.get(SamplesPerPixelTag) ?? 1); - const numberOfFrames = meta.has(NumberOfFrames) - ? Number(meta.get(NumberOfFrames)) - : null; - - if ( - numberOfFrames !== null && - numberOfFrames > 1 && - sortedChunks.length > 1 - ) { - throw new Error( - 'First chunk in a group of chunks (size > 1) is a multi-frame chunk' - ); - } - - // We don't support volumes with multiple chunks/files with multi-frame data at the moment. - // Some CT modality series have NumberOfFrames === 1, so use the number of chunks if more than 1 chunk. - const slices = - sortedChunks.length > 1 ? sortedChunks.length : (numberOfFrames ?? 1); - const TypedArrayCtor = getVolumeBufferType(volumeFormats); - const pixelData = new TypedArrayCtor( - rows * columns * slices * samplesPerPixel - ); - - const image = vtkImageData.newInstance(); - image.setExtent([0, columns - 1, 0, rows - 1, 0, slices - 1]); - - if (imagePositionPatient) { - image.setOrigin(imagePositionPatient as Vector3); - } - - const spacing: Vector3 = [...pixelSpacing, 1]; - - if (imagePositionPatient && sortedChunks.length > 1) { - const lastMeta = new Map(sortedChunks[sortedChunks.length - 1].metadata); - const lastIPP = toVec(lastMeta.get(ImagePositionPatientTag)); - if (lastIPP) { - // assumption: uniform Z spacing - const zVec = vec3.create(); - vec3.sub(zVec, lastIPP as vec3, imagePositionPatient as vec3); - spacing[2] = vec3.len(zVec) / (slices - 1) || 1; - } - } else if (isPositiveFiniteNumber(spacingBetweenSlices)) { - spacing[2] = spacingBetweenSlices; - } - image.setSpacing(spacing); - - if (imageOrientationPatient) { - const zDir = vec3.create() as Vector3; - vec3.cross( - zDir, - imageOrientationPatient.slice(0, 3) as vec3, - imageOrientationPatient.slice(3, 6) as vec3 - ); - image.setDirection([...imageOrientationPatient, ...zDir] as mat3); - } - - const dataArray = vtkDataArray.newInstance({ - numberOfComponents: samplesPerPixel, - values: pixelData, - }); - image.getPointData().setScalars(dataArray); - - // Needed for volume rendering to work at start - // TODO(fli) sane defaults? - dataArray.setRange({ min: 0, max: 255 }, 0); - - return image; -} diff --git a/src/utils/dicom/windowMetadata.ts b/src/utils/dicom/windowMetadata.ts new file mode 100644 index 000000000..c128e0d04 --- /dev/null +++ b/src/utils/dicom/windowMetadata.ts @@ -0,0 +1,10 @@ +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) => + [Tags.WindowLevel, Tags.WindowWidth, Tags.VOILUTFunction].flatMap((tag) => { + const value = getDatasetTag(dataset, tag); + return value === undefined ? [] : [[tag, value] as const]; + }); diff --git a/src/utils/dicomWindowRange.ts b/src/utils/dicomWindowRange.ts index 8dd7455aa..a61a6b052 100644 --- a/src/utils/dicomWindowRange.ts +++ b/src/utils/dicomWindowRange.ts @@ -1,4 +1,5 @@ -import { Tags } from '@/src/core/dicomTags'; +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; diff --git a/src/utils/index.ts b/src/utils/index.ts index e0782ad9e..c1010e739 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -313,35 +313,3 @@ export function addEventListenerOnce( }; target.addEventListener(event, handler); } - -/** - * Converts a byte sequence to ASCII. - * @param bytes - * @param param1 - * @returns - */ -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); -} diff --git a/tests/byteSourceFixtures.ts b/tests/byteSourceFixtures.ts new file mode 100644 index 000000000..b147cf2a1 --- /dev/null +++ b/tests/byteSourceFixtures.ts @@ -0,0 +1,45 @@ +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) => { + const stats = { reads: 0, delivered: 0, cancelled: 0 }; + const source: ByteSource = { + 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 = Promise.withResolvers(); + const cancelled = Promise.withResolvers(); + 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 }; +}; diff --git a/tests/datasets.ts b/tests/datasets.ts index 3865ce2b3..f044a7749 100644 --- a/tests/datasets.ts +++ b/tests/datasets.ts @@ -1,8 +1,12 @@ // 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' }; +import compositionCorpus from './dicomCompositionCorpus.json' with { type: 'json' }; + const DATASET_RELEASE = 'https://github.com/Kitware/VolView/releases/download/test-data-1'; @@ -125,113 +129,15 @@ export const { CT_ELECTRODES, } = DATASETS; -export const PET_CT_DICOM_DATASETS = [ - { - name: 'PET-CT-PT-01.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.125971577518855152164687925479', - sha256: '082cc2a92409d26dcd465ca37dcb55182f526fa94f0d66299c93196f0dd2b130', - }, - { - name: 'PET-CT-PT-02.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.164470072637482892742730606415', - sha256: '7fc5a40cc7645c64c91df14008e27c8f20f6b613af8f888125d72c6ae6f153d6', - }, - { - name: 'PET-CT-PT-03.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.645656839545863315258382059304', - sha256: 'b4922f66ed2d02e1783c32d23e3bd8aa73cc30f648784de91316890c1a8faaf6', - }, - { - name: 'PET-CT-PT-04.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.171033599854331402388163035916', - sha256: 'ae96aa74535276c86e9e6f06be540b446f349d58e376cd6812832bbb183fed0b', - }, - { - name: 'PET-CT-PT-05.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.757229251338810950547930294076', - sha256: '71d7ea70e1527dcaac130ec4794748710961d0d18b11dc8a0dda3d96c7e1ddea', - }, - { - name: 'PET-CT-PT-06.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.290313076131916328810257384513', - sha256: '4c9f3fac5d2710d72c46ed63f97aed8052245380967efa3f1f4ce72aeb488fa7', - }, - { - name: 'PET-CT-PT-07.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.167034157012705076112347098246', - sha256: 'c5398c842bb35f7c7b7d77398d2246003b4565474961c622820545ab1a42d7dc', - }, - { - name: 'PET-CT-PT-08.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.305525101475115108798705213666', - sha256: '65115e0a3335074976e2178e52e5036bfe4201d3b315a79f733cb470729c220d', - }, - { - name: 'PET-CT-PT-09.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.180547818912813778100247492512', - sha256: '8e0316240d5e8cc3c7e0913b4abb892be1be5879b5cc3f0379a205fd286ca17b', - }, - { - name: 'PET-CT-PT-10.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.190211187176681563808826571096', - sha256: 'fb424c9c3670d0f0374361ecb16bf342e27cdfcf8be0aead1e4629ea7a2e7928', - }, - { - name: 'PET-CT-CT-01.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.330442471593744252750634668562', - sha256: '262fc85a0a05c57ec96451baf8a1b64f3287d5d6efdf5e4d9e67983e20e59fe2', - }, - { - name: 'PET-CT-CT-02.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.787146087385319992976365569088', - sha256: 'c348f6f8d899ce9e02a4b2fc3f93743491df1a04c99f65c1c77ab1c8baec8cb7', - }, - { - name: 'PET-CT-CT-03.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.754367593034585495537680981967', - sha256: '4935a37d77059028d175a38c515e52beb2e90d0971c9b495ab956433c8e7fa18', - }, - { - name: 'PET-CT-CT-04.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.268694914226381205284654198517', - sha256: '27cff9c1bd6d1fc6543bb8d2a009e232c4f39b6aa333b9d3ce39d7cdeddf0cc3', - }, - { - name: 'PET-CT-CT-05.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.273002091516249828143197374115', - sha256: '038be9136459b5d9d5dbd44b7d35394012a0415f5ed09b2ba46ca34aef1c1f96', - }, - { - name: 'PET-CT-CT-06.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.251520880093056497198942071424', - sha256: 'feceb609cda89e382459a1c6884e5737e5f00b378de19c33e3f9838474f418bd', - }, - { - name: 'PET-CT-CT-07.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.254151550624375545322457061626', - sha256: 'a416fb025436c0d0bcdedb9e36b51a4ac744ac332b83ce8c94da7b459188e39b', - }, - { - name: 'PET-CT-CT-08.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.477776731601464757864806040291', - sha256: '6b8db167b9ddbf9194d9935b94092668d2b7eb6c576dce5cc3f96046046fb6fc', - }, - { - name: 'PET-CT-CT-09.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.831869199671510110705249657284', - sha256: '31df0464f111f0cccd1cba25f2e014f88375de44bc0ba7ead844a015508f5f43', - }, - { - name: 'PET-CT-CT-10.dcm', - url: 'https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.243468898389109491372438016818', - sha256: 'c2470a67fd601d7e36130bebd51e8e71b9f6fad9832ea6b79f504309f2fee984', - }, -]; +export const PET_CT_DICOM_DATASETS = compositionCorpus.datasets.filter( + ({ name }) => name.startsWith('PET-CT-') +); // Everything declared above is downloaded. export const TEST_DATASETS = [ ...Object.values(DATASETS), - ...PET_CT_DICOM_DATASETS, + ...compositionCorpus.datasets, + ...dicomVolumeCorpus.datasets, ]; export type TestDataset = (typeof TEST_DATASETS)[number]; diff --git a/tests/dicomCompositionCorpus.json b/tests/dicomCompositionCorpus.json new file mode 100644 index 000000000..afb8e95d9 --- /dev/null +++ b/tests/dicomCompositionCorpus.json @@ -0,0 +1,865 @@ +{ + "referenceDecoder": { + "pydicom": "3.0.2", + "numpy": "2.4.6", + "jpegLossless": "pylibjpeg-libjpeg2.5.0" + }, + "pixelHashEncoding": "SHA256 of calibrated samples, rounded to float32 where a fractional rescale fits the Float32 rule, as Float64 little-endian, C order [slice,row,column], planes sorted by ascending patient-space projection", + "geometryToleranceMm": 0.0001, + "datasets": [ + { + "name": "PET-CT-PT-01.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.125971577518855152164687925479", + "sha256": "082cc2a92409d26dcd465ca37dcb55182f526fa94f0d66299c93196f0dd2b130" + }, + { + "name": "PET-CT-PT-02.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.164470072637482892742730606415", + "sha256": "7fc5a40cc7645c64c91df14008e27c8f20f6b613af8f888125d72c6ae6f153d6" + }, + { + "name": "PET-CT-PT-03.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.645656839545863315258382059304", + "sha256": "b4922f66ed2d02e1783c32d23e3bd8aa73cc30f648784de91316890c1a8faaf6" + }, + { + "name": "PET-CT-PT-04.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.171033599854331402388163035916", + "sha256": "ae96aa74535276c86e9e6f06be540b446f349d58e376cd6812832bbb183fed0b" + }, + { + "name": "PET-CT-PT-05.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.757229251338810950547930294076", + "sha256": "71d7ea70e1527dcaac130ec4794748710961d0d18b11dc8a0dda3d96c7e1ddea" + }, + { + "name": "PET-CT-PT-06.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.290313076131916328810257384513", + "sha256": "4c9f3fac5d2710d72c46ed63f97aed8052245380967efa3f1f4ce72aeb488fa7" + }, + { + "name": "PET-CT-PT-07.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.167034157012705076112347098246", + "sha256": "c5398c842bb35f7c7b7d77398d2246003b4565474961c622820545ab1a42d7dc" + }, + { + "name": "PET-CT-PT-08.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.305525101475115108798705213666", + "sha256": "65115e0a3335074976e2178e52e5036bfe4201d3b315a79f733cb470729c220d" + }, + { + "name": "PET-CT-PT-09.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.180547818912813778100247492512", + "sha256": "8e0316240d5e8cc3c7e0913b4abb892be1be5879b5cc3f0379a205fd286ca17b" + }, + { + "name": "PET-CT-PT-10.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.316521143696464534574699049839&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.190211187176681563808826571096", + "sha256": "fb424c9c3670d0f0374361ecb16bf342e27cdfcf8be0aead1e4629ea7a2e7928" + }, + { + "name": "PET-CT-CT-01.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.330442471593744252750634668562", + "sha256": "262fc85a0a05c57ec96451baf8a1b64f3287d5d6efdf5e4d9e67983e20e59fe2" + }, + { + "name": "PET-CT-CT-02.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.787146087385319992976365569088", + "sha256": "c348f6f8d899ce9e02a4b2fc3f93743491df1a04c99f65c1c77ab1c8baec8cb7" + }, + { + "name": "PET-CT-CT-03.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.754367593034585495537680981967", + "sha256": "4935a37d77059028d175a38c515e52beb2e90d0971c9b495ab956433c8e7fa18" + }, + { + "name": "PET-CT-CT-04.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.268694914226381205284654198517", + "sha256": "27cff9c1bd6d1fc6543bb8d2a009e232c4f39b6aa333b9d3ce39d7cdeddf0cc3" + }, + { + "name": "PET-CT-CT-05.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.273002091516249828143197374115", + "sha256": "038be9136459b5d9d5dbd44b7d35394012a0415f5ed09b2ba46ca34aef1c1f96" + }, + { + "name": "PET-CT-CT-06.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.251520880093056497198942071424", + "sha256": "feceb609cda89e382459a1c6884e5737e5f00b378de19c33e3f9838474f418bd" + }, + { + "name": "PET-CT-CT-07.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.254151550624375545322457061626", + "sha256": "a416fb025436c0d0bcdedb9e36b51a4ac744ac332b83ce8c94da7b459188e39b" + }, + { + "name": "PET-CT-CT-08.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.477776731601464757864806040291", + "sha256": "6b8db167b9ddbf9194d9935b94092668d2b7eb6c576dce5cc3f96046046fb6fc" + }, + { + "name": "PET-CT-CT-09.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.831869199671510110705249657284", + "sha256": "31df0464f111f0cccd1cba25f2e014f88375de44bc0ba7ead844a015508f5f43" + }, + { + "name": "PET-CT-CT-10.dcm", + "url": "https://services.cancerimagingarchive.net/nbia-api/services/v1/getSingleImage?SeriesInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.114189455733462211540942355885&SOPInstanceUID=1.3.6.1.4.1.14519.5.2.1.6655.2359.243468898389109491372438016818", + "sha256": "c2470a67fd601d7e36130bebd51e8e71b9f6fad9832ea6b79f504309f2fee984" + }, + { + "name": "dicom-composition-mr-acquisition-01-e154bee1-f613-4c7d-b03b-b1e9e55f63d9.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/e154bee1-f613-4c7d-b03b-b1e9e55f63d9.dcm", + "sha256": "e4c5393292e39cb48f52faf27dda06f3f820500a17f598e3d60a9d1989586492", + "bytes": 17222, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.175422070467069899872257220126620012644", + "acquisitionNumber": 1, + "spatialIndex": 0, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-1d00e686-4959-4caa-82ea-232a9c3a8d01.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/1d00e686-4959-4caa-82ea-232a9c3a8d01.dcm", + "sha256": "37aafc35348c751a5d906d177a1b204954c8433c93fa745a950516f00945c196", + "bytes": 17282, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.74828307994170137574374080356928369364", + "acquisitionNumber": 1, + "spatialIndex": 1, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-71840b5a-927b-48d8-bfc2-80da50789b61.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/71840b5a-927b-48d8-bfc2-80da50789b61.dcm", + "sha256": "d868e37ba73219537aaa7dc063c22faf70cd5eb115542c904e53b42024f06925", + "bytes": 17506, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.18246013024174158390277563280188834034", + "acquisitionNumber": 1, + "spatialIndex": 2, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-f02cdf7f-1ec5-4e3d-9e17-ac03a8238e1a.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/f02cdf7f-1ec5-4e3d-9e17-ac03a8238e1a.dcm", + "sha256": "9300c63434e6fc385f780248eac5e37934b84d4134bb464a2517227ba0166fab", + "bytes": 17520, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.87589025663324541812773758238195829559", + "acquisitionNumber": 1, + "spatialIndex": 3, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-0b58d48d-ad5e-4047-a48e-70fa8df73fcc.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/0b58d48d-ad5e-4047-a48e-70fa8df73fcc.dcm", + "sha256": "2a9f2ef3afc4264ecf8e793de3fdc8cdeda1183065bd6665e589d4d0d3cfcd01", + "bytes": 17642, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.265416146372149318162024061181114373847", + "acquisitionNumber": 1, + "spatialIndex": 4, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-908f1ae9-91d7-4478-8abf-65be08c63fe2.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/908f1ae9-91d7-4478-8abf-65be08c63fe2.dcm", + "sha256": "e4536a8c4b53745c9a2a629822a04b690c01ac4b341d45acda48b4c75ad77624", + "bytes": 17874, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.95895646951134769097166684863822992", + "acquisitionNumber": 1, + "spatialIndex": 5, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-7b3e57c4-3ce8-4320-aff6-bf8a9e3d75c9.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/7b3e57c4-3ce8-4320-aff6-bf8a9e3d75c9.dcm", + "sha256": "5193025b6a2f18e0856ed1387b5880b53fb54d2c8e4c7a6931f5e7025607fa10", + "bytes": 18188, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.216717631237343833964306094926050249278", + "acquisitionNumber": 1, + "spatialIndex": 6, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-35ee5eb7-b1f9-47fe-b77d-72eb8b05d06b.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/35ee5eb7-b1f9-47fe-b77d-72eb8b05d06b.dcm", + "sha256": "2f887dbf48234d42ae8b8f3f21098c55ca7ad3c6900756064bd9bfc6668c45ed", + "bytes": 18536, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.11246558375985292032717579163105937938", + "acquisitionNumber": 1, + "spatialIndex": 7, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-6360529b-0de9-4d56-9785-5bbbc14392e7.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/6360529b-0de9-4d56-9785-5bbbc14392e7.dcm", + "sha256": "0ac6fba5bc3478214b7ee30547392a623fc35ef0b9542b26730476011e031286", + "bytes": 18696, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.284065435769955657314770925744007917501", + "acquisitionNumber": 1, + "spatialIndex": 8, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-3fcd9e8b-e062-49d3-8ed5-cdeced610b11.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/3fcd9e8b-e062-49d3-8ed5-cdeced610b11.dcm", + "sha256": "8ea05e97c52b6969667c5d46570c69686a9e5f20937b1957ca1ec82ac1493b95", + "bytes": 18668, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.136729336478045227230023809227263752689", + "acquisitionNumber": 1, + "spatialIndex": 9, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-52a88286-f3f9-4a9d-b8f8-f7abe8e40d59.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/52a88286-f3f9-4a9d-b8f8-f7abe8e40d59.dcm", + "sha256": "0e2e846a410cc24dcffaeaa04524ca564e010ed8eeacd6cbabfdcc34982af54f", + "bytes": 18600, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.9546374682728595323438495350056808095", + "acquisitionNumber": 1, + "spatialIndex": 10, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-86275346-584e-492b-829c-d197dc477ef0.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/86275346-584e-492b-829c-d197dc477ef0.dcm", + "sha256": "21195015775cafbae8d702c83193cd055d5ed9268814381611ee305c492cb9dc", + "bytes": 18484, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.39011493149661743539155371466940683065", + "acquisitionNumber": 1, + "spatialIndex": 11, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-20d18bba-64aa-4c56-a853-25669575299d.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/20d18bba-64aa-4c56-a853-25669575299d.dcm", + "sha256": "ed6e1d3198cc05fc3400f017a60f34eaf9b974c6a59aea2bc83420800fb3814f", + "bytes": 18436, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.26525129033124267904381337952873368912", + "acquisitionNumber": 1, + "spatialIndex": 12, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-658fcada-2c6f-497c-b5de-6a7298628610.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/658fcada-2c6f-497c-b5de-6a7298628610.dcm", + "sha256": "32510f22a3bf88158f190d65424653eaa01f7c4943126e929a273b47c00bfe89", + "bytes": 18548, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.310251359228770623293767338778806598673", + "acquisitionNumber": 1, + "spatialIndex": 13, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-54021f3b-2b11-4f1a-aa96-3cda348d2962.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/54021f3b-2b11-4f1a-aa96-3cda348d2962.dcm", + "sha256": "b3d46e7ed754a42990aca6cef94e2d8b35e4878f272dce6883f0e759a0640601", + "bytes": 18834, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.55049365537386617744561788609735942581", + "acquisitionNumber": 1, + "spatialIndex": 14, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-f6af8b49-b857-41bb-bfca-847481dc1a6d.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/f6af8b49-b857-41bb-bfca-847481dc1a6d.dcm", + "sha256": "710e527b4c580ff52102cc302efbdd4bfa98149cfd13105cb757e841dcc2cb38", + "bytes": 18782, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.164314255039726640018309666632100103489", + "acquisitionNumber": 1, + "spatialIndex": 15, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-dcfcbbef-3aff-409c-bc4d-17050f57b9b6.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/dcfcbbef-3aff-409c-bc4d-17050f57b9b6.dcm", + "sha256": "863118c03075ff7053d4b4e27339b4a7c6c65d167d0de9766460733ef62bbc8b", + "bytes": 18766, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.89591371192466041605354161692414601123", + "acquisitionNumber": 1, + "spatialIndex": 16, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-0cd1bbba-f64a-4c8b-8c52-41de33567004.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/0cd1bbba-f64a-4c8b-8c52-41de33567004.dcm", + "sha256": "e1dbdb603cb5a162d704f574f9c3246be4fc55254e67b2d89a807d49f68f0109", + "bytes": 18778, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.25551077253562667719265633888997904301", + "acquisitionNumber": 1, + "spatialIndex": 17, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-7fa53a42-375e-46f0-881f-3bed1640d3ae.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/7fa53a42-375e-46f0-881f-3bed1640d3ae.dcm", + "sha256": "07e5f6d6404f7f7321feb791949c2312b6272346746776d42d8a829c92df5935", + "bytes": 18676, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.48243253609306306463136916680254474573", + "acquisitionNumber": 1, + "spatialIndex": 18, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-01-938d0902-0939-491d-98be-8705cd7d0117.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/938d0902-0939-491d-98be-8705cd7d0117.dcm", + "sha256": "fd2c1321e25d1a181a5f333c6143f8271d8b890752f4db0b6a1e2eebce158d54", + "bytes": 18696, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.9823821695062948400149786107754402093", + "acquisitionNumber": 1, + "spatialIndex": 19, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-63499c26-d5d0-4c15-bd13-23baf6b73f67.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/63499c26-d5d0-4c15-bd13-23baf6b73f67.dcm", + "sha256": "8bc52fcde26f5a9282aeb83b2875f316f7547b6626cae8393314f5ef2936a250", + "bytes": 17218, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.95800245628389430547908955664336971166", + "acquisitionNumber": 2, + "spatialIndex": 0, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-06442f32-ba30-401c-b5d8-c322f1a64ca1.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/06442f32-ba30-401c-b5d8-c322f1a64ca1.dcm", + "sha256": "9427c70f70647ffd4bea36cd00474f7813a800193edb22859c88fea0ae5f6457", + "bytes": 17256, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.10324730000090874951730116451541894560", + "acquisitionNumber": 2, + "spatialIndex": 1, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-0294525b-c306-40c1-84b3-bb47f0176218.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/0294525b-c306-40c1-84b3-bb47f0176218.dcm", + "sha256": "44c0902bda70abdd86f1b6db3085ff1202ea7d6e61128c1e4d935cb1ae9236d0", + "bytes": 17562, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.20871289937842133708603344148131563991", + "acquisitionNumber": 2, + "spatialIndex": 2, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-b5500532-a246-4069-a61c-13f732029aa1.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/b5500532-a246-4069-a61c-13f732029aa1.dcm", + "sha256": "3e2dab57310d504e90e8947fc733d9dab4720841292c8d49d026e4396d4fe73c", + "bytes": 17514, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.207601200393842342415867127072398671280", + "acquisitionNumber": 2, + "spatialIndex": 3, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-795beca3-db51-4f61-a173-38a98578396a.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/795beca3-db51-4f61-a173-38a98578396a.dcm", + "sha256": "aa515e195bdcddc50c80a3c3f0d66efbd7999c7999f8711876f693fea3d34e5a", + "bytes": 17618, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.5019695074283757761417608292898492579", + "acquisitionNumber": 2, + "spatialIndex": 4, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-fba460f3-2746-4d34-9a67-2746835b185c.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/fba460f3-2746-4d34-9a67-2746835b185c.dcm", + "sha256": "c7cd0eb175bd35ac6e223a132da1fd4156787ddbb3b3fc77d2d22864072e9cbc", + "bytes": 17892, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.244710395874376369715943521608533083799", + "acquisitionNumber": 2, + "spatialIndex": 5, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-41f827f8-f2c9-4d06-b47d-b55e05fc448b.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/41f827f8-f2c9-4d06-b47d-b55e05fc448b.dcm", + "sha256": "1c4e2fb11cd395b9136b0c24070069aaa76cfa8de10492a28425fcbe39901c68", + "bytes": 18166, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.42613418119216512098730031618859421607", + "acquisitionNumber": 2, + "spatialIndex": 6, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-42e2e428-da0e-411d-ad7d-322685f3d790.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/42e2e428-da0e-411d-ad7d-322685f3d790.dcm", + "sha256": "aa83476067ee5a722f31316b35991d31a070d2797418dfd35c9bfa805c116e99", + "bytes": 18532, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.79378288901235501366512113344307439532", + "acquisitionNumber": 2, + "spatialIndex": 7, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-4c104781-26b3-41ba-bced-c17980117735.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/4c104781-26b3-41ba-bced-c17980117735.dcm", + "sha256": "0e811516f53b3610bb8b92c2f7c5a704525a2a6cc625cb4fff32c101d7e7b191", + "bytes": 18660, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.96214938527447624723367621124186432575", + "acquisitionNumber": 2, + "spatialIndex": 8, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-de87bbbb-0008-4ddb-9b04-0d84c6e495ba.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/de87bbbb-0008-4ddb-9b04-0d84c6e495ba.dcm", + "sha256": "79a7c77d4c36f7656fb9cc9818fc46f0c6a6e038aafc0b2fa58bc66706959042", + "bytes": 18618, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.11477809763946167544868963125148672216", + "acquisitionNumber": 2, + "spatialIndex": 9, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-88e1577a-db1e-461f-b65f-10771719caa8.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/88e1577a-db1e-461f-b65f-10771719caa8.dcm", + "sha256": "00e0319163bc01799d57e3f24437f7f9e4f59a307002eb645027ba242cc7e2c0", + "bytes": 18640, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.116677553804498275761354796089763839564", + "acquisitionNumber": 2, + "spatialIndex": 10, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-20d1aaef-1142-4afc-a489-dcdd6b44023f.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/20d1aaef-1142-4afc-a489-dcdd6b44023f.dcm", + "sha256": "504df2390dd65cc8db0b05c59ec8fb61cb09f5856cf8f737d4a43165da69804f", + "bytes": 18486, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.124215952865600213334872250839850807271", + "acquisitionNumber": 2, + "spatialIndex": 11, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-fc889111-82a7-4975-b3c0-c2697ee4ddfb.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/fc889111-82a7-4975-b3c0-c2697ee4ddfb.dcm", + "sha256": "1c3bd0f01a25ba51f55be4804831172c83da47dbd71a7a0d3a5bcc10b05cdb76", + "bytes": 18476, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.159565847346051610447852872136558610464", + "acquisitionNumber": 2, + "spatialIndex": 12, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-12a9492b-4d4b-4772-8112-2d3603acae0c.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/12a9492b-4d4b-4772-8112-2d3603acae0c.dcm", + "sha256": "e8955849e5f409f8eaa2f7239cbb19f3162445cb2f45718482e85e3f9eeb01d1", + "bytes": 18538, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.105236080028506882585509543614990123305", + "acquisitionNumber": 2, + "spatialIndex": 13, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-bc9c0df3-e75f-4505-9aea-4af6f63bc483.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/bc9c0df3-e75f-4505-9aea-4af6f63bc483.dcm", + "sha256": "47e4eba0ac652738ccc51aaadb255ce7ad918320852eaecb75c97619e4ab59e6", + "bytes": 18790, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.240658961409259338415298464496856630506", + "acquisitionNumber": 2, + "spatialIndex": 14, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-758fc031-17a8-4d75-a53c-112b106fbfb5.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/758fc031-17a8-4d75-a53c-112b106fbfb5.dcm", + "sha256": "4f1d5a2d88ca416eb8ae2d89e53d1ed10a1ac371a85a682e5b723bf7fd0410bc", + "bytes": 18766, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.48057063746393045761305555460588541183", + "acquisitionNumber": 2, + "spatialIndex": 15, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-f2a46e8a-5002-4ed9-a177-95968edee72d.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/f2a46e8a-5002-4ed9-a177-95968edee72d.dcm", + "sha256": "0cdffb90494e1ffee754b3f8a535fb3f5d65a90a386eb9a3972ce3dca7abf7b5", + "bytes": 18770, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.277576526130247578770581544443175766465", + "acquisitionNumber": 2, + "spatialIndex": 16, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-1aa44640-53cc-45c6-8e28-c7fafd94dcef.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/1aa44640-53cc-45c6-8e28-c7fafd94dcef.dcm", + "sha256": "2a8d75467e25056f1ee0fa3451306ed1d5a574d014703335e5a0c7f2259e5bdf", + "bytes": 18708, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.31016158786533738904377172767810945877", + "acquisitionNumber": 2, + "spatialIndex": 17, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-76452ba7-528c-4ef7-b5f1-18044ea9bb25.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/76452ba7-528c-4ef7-b5f1-18044ea9bb25.dcm", + "sha256": "82b40893ff43190abbc7fd1000631909c40264792863fa9175d40df66cc5948e", + "bytes": 18650, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.45552704547405539600621661677355908697", + "acquisitionNumber": 2, + "spatialIndex": 18, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + }, + { + "name": "dicom-composition-mr-acquisition-02-fdd34427-1293-48c3-afae-4c6765bf6779.dcm", + "url": "https://idc-open-data.s3.amazonaws.com/5660fad0-290f-482f-89a9-47411084c038/fdd34427-1293-48c3-afae-4c6765bf6779.dcm", + "sha256": "af9fdbc8a40ba79f89c62cff3e676d6295036a87745e7f8a3fbf1e7779515e5f", + "bytes": 18676, + "sopInstanceUID": "1.3.6.1.4.1.14519.5.2.1.306307086227517891627472362958678830947", + "acquisitionNumber": 2, + "spatialIndex": 19, + "sourceDOI": "10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "collection": "upenn_gbm" + } + ], + "cases": [ + { + "id": "pet-ct", + "volumes": [ + { + "id": "pet-ct-ct-10-slices", + "files": [ + "PET-CT-CT-01.dcm", + "PET-CT-CT-02.dcm", + "PET-CT-CT-03.dcm", + "PET-CT-CT-04.dcm", + "PET-CT-CT-05.dcm", + "PET-CT-CT-06.dcm", + "PET-CT-CT-07.dcm", + "PET-CT-CT-08.dcm", + "PET-CT-CT-09.dcm", + "PET-CT-CT-10.dcm" + ], + "sopInstanceUIDs": [ + "1.3.6.1.4.1.14519.5.2.1.6655.2359.330442471593744252750634668562", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.787146087385319992976365569088", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.754367593034585495537680981967", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.268694914226381205284654198517", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.273002091516249828143197374115", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.251520880093056497198942071424", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.254151550624375545322457061626", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.477776731601464757864806040291", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.831869199671510110705249657284", + "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], + "pixelHash": "2ad22501d69427486583b99b0950b18db4deadccdde5910e5e54214eaed06474", + "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], + "pixelHash": "cba4f6107835fa368f6c260f1ed19dd0168afebac0efe03219f9bcc7342c8a77", + "firstPlanePosition": [-249.51171875, -429.51171875, -373.0], + "lastPlanePosition": [-249.51171875, -429.51171875, -365.0] + }, + "provenance": { + "collection": "lung_pet_ct_dx", + "sourceDOI": "10.7937/tcia.2020.nnc2-0461", + "license": "CC BY 4.0", + "scope": "Ten contiguous original single-slice instances from the existing pinned test dataset manifest" + }, + "acquisitionNumber": 6 + }, + { + "id": "pet-ct-pt-10-slices", + "files": [ + "PET-CT-PT-01.dcm", + "PET-CT-PT-02.dcm", + "PET-CT-PT-03.dcm", + "PET-CT-PT-04.dcm", + "PET-CT-PT-05.dcm", + "PET-CT-PT-06.dcm", + "PET-CT-PT-07.dcm", + "PET-CT-PT-08.dcm", + "PET-CT-PT-09.dcm", + "PET-CT-PT-10.dcm" + ], + "sopInstanceUIDs": [ + "1.3.6.1.4.1.14519.5.2.1.6655.2359.125971577518855152164687925479", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.164470072637482892742730606415", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.645656839545863315258382059304", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.171033599854331402388163035916", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.757229251338810950547930294076", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.290313076131916328810257384513", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.167034157012705076112347098246", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.305525101475115108798705213666", + "1.3.6.1.4.1.14519.5.2.1.6655.2359.180547818912813778100247492512", + "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], + "pixelHash": "5d594a7f8eba4fadb4a6e013f29783bed9595f8577b04fb184772463bf0bc8b0", + "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], + "pixelHash": "cdd3a5fe2695d8baabc9726dd74cef785fb73660ad5cea5550d8613d79776486", + "firstPlanePosition": [-407.316, -586.743, -383.0], + "lastPlanePosition": [-407.316, -586.743, -359.0] + }, + "provenance": { + "collection": "lung_pet_ct_dx", + "sourceDOI": "10.7937/tcia.2020.nnc2-0461", + "license": "CC BY 4.0", + "scope": "Ten contiguous original single-slice instances from the existing pinned test dataset manifest" + }, + "acquisitionNumber": 6001 + } + ] + }, + { + "id": "mr-acquisitions", + "volumes": [ + { + "id": "idc-mr-acquisition-1", + "files": [ + "dicom-composition-mr-acquisition-01-e154bee1-f613-4c7d-b03b-b1e9e55f63d9.dcm", + "dicom-composition-mr-acquisition-01-1d00e686-4959-4caa-82ea-232a9c3a8d01.dcm", + "dicom-composition-mr-acquisition-01-71840b5a-927b-48d8-bfc2-80da50789b61.dcm", + "dicom-composition-mr-acquisition-01-f02cdf7f-1ec5-4e3d-9e17-ac03a8238e1a.dcm", + "dicom-composition-mr-acquisition-01-0b58d48d-ad5e-4047-a48e-70fa8df73fcc.dcm", + "dicom-composition-mr-acquisition-01-908f1ae9-91d7-4478-8abf-65be08c63fe2.dcm", + "dicom-composition-mr-acquisition-01-7b3e57c4-3ce8-4320-aff6-bf8a9e3d75c9.dcm", + "dicom-composition-mr-acquisition-01-35ee5eb7-b1f9-47fe-b77d-72eb8b05d06b.dcm", + "dicom-composition-mr-acquisition-01-6360529b-0de9-4d56-9785-5bbbc14392e7.dcm", + "dicom-composition-mr-acquisition-01-3fcd9e8b-e062-49d3-8ed5-cdeced610b11.dcm", + "dicom-composition-mr-acquisition-01-52a88286-f3f9-4a9d-b8f8-f7abe8e40d59.dcm", + "dicom-composition-mr-acquisition-01-86275346-584e-492b-829c-d197dc477ef0.dcm", + "dicom-composition-mr-acquisition-01-20d18bba-64aa-4c56-a853-25669575299d.dcm", + "dicom-composition-mr-acquisition-01-658fcada-2c6f-497c-b5de-6a7298628610.dcm", + "dicom-composition-mr-acquisition-01-54021f3b-2b11-4f1a-aa96-3cda348d2962.dcm", + "dicom-composition-mr-acquisition-01-f6af8b49-b857-41bb-bfca-847481dc1a6d.dcm", + "dicom-composition-mr-acquisition-01-dcfcbbef-3aff-409c-bc4d-17050f57b9b6.dcm", + "dicom-composition-mr-acquisition-01-0cd1bbba-f64a-4c8b-8c52-41de33567004.dcm", + "dicom-composition-mr-acquisition-01-7fa53a42-375e-46f0-881f-3bed1640d3ae.dcm", + "dicom-composition-mr-acquisition-01-938d0902-0939-491d-98be-8705cd7d0117.dcm" + ], + "sopInstanceUIDs": [ + "1.3.6.1.4.1.14519.5.2.1.175422070467069899872257220126620012644", + "1.3.6.1.4.1.14519.5.2.1.74828307994170137574374080356928369364", + "1.3.6.1.4.1.14519.5.2.1.18246013024174158390277563280188834034", + "1.3.6.1.4.1.14519.5.2.1.87589025663324541812773758238195829559", + "1.3.6.1.4.1.14519.5.2.1.265416146372149318162024061181114373847", + "1.3.6.1.4.1.14519.5.2.1.95895646951134769097166684863822992", + "1.3.6.1.4.1.14519.5.2.1.216717631237343833964306094926050249278", + "1.3.6.1.4.1.14519.5.2.1.11246558375985292032717579163105937938", + "1.3.6.1.4.1.14519.5.2.1.284065435769955657314770925744007917501", + "1.3.6.1.4.1.14519.5.2.1.136729336478045227230023809227263752689", + "1.3.6.1.4.1.14519.5.2.1.9546374682728595323438495350056808095", + "1.3.6.1.4.1.14519.5.2.1.39011493149661743539155371466940683065", + "1.3.6.1.4.1.14519.5.2.1.26525129033124267904381337952873368912", + "1.3.6.1.4.1.14519.5.2.1.310251359228770623293767338778806598673", + "1.3.6.1.4.1.14519.5.2.1.55049365537386617744561788609735942581", + "1.3.6.1.4.1.14519.5.2.1.164314255039726640018309666632100103489", + "1.3.6.1.4.1.14519.5.2.1.89591371192466041605354161692414601123", + "1.3.6.1.4.1.14519.5.2.1.25551077253562667719265633888997904301", + "1.3.6.1.4.1.14519.5.2.1.48243253609306306463136916680254474573", + "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], + "pixelHash": "551354c80e038874f8f5f95eaf3840911836ebd3893b40974650064c3b9e0cdd", + "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], + "pixelHash": "5101bcfd36da0f11b3f07c6d77a6dedb6473130339566112edbab228393ad489", + "firstPlanePosition": [-105.23245681323, -147.49348022462, -33.429649353027], + "lastPlanePosition": [-105.23245681323, -147.49348022462, 20.570348739624] + }, + "provenance": { + "collection": "upenn_gbm", + "sourceDOI": "10.7937/tcia.709x-dn49", + "source": "https://doi.org/10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "crdcSeriesUUID": "5660fad0-290f-482f-89a9-47411084c038", + "objectListingSource": "https://idc-open-data.s3.amazonaws.com/?list-type=2&prefix=5660fad0-290f-482f-89a9-47411084c038/", + "membershipRule": "Group exact DICOM AcquisitionNumber; sort each group by patient-position projection on normalized row cross column; require regular spacing and no in-plane drift" + }, + "acquisitionNumber": 1 + }, + { + "id": "idc-mr-acquisition-2", + "files": [ + "dicom-composition-mr-acquisition-02-63499c26-d5d0-4c15-bd13-23baf6b73f67.dcm", + "dicom-composition-mr-acquisition-02-06442f32-ba30-401c-b5d8-c322f1a64ca1.dcm", + "dicom-composition-mr-acquisition-02-0294525b-c306-40c1-84b3-bb47f0176218.dcm", + "dicom-composition-mr-acquisition-02-b5500532-a246-4069-a61c-13f732029aa1.dcm", + "dicom-composition-mr-acquisition-02-795beca3-db51-4f61-a173-38a98578396a.dcm", + "dicom-composition-mr-acquisition-02-fba460f3-2746-4d34-9a67-2746835b185c.dcm", + "dicom-composition-mr-acquisition-02-41f827f8-f2c9-4d06-b47d-b55e05fc448b.dcm", + "dicom-composition-mr-acquisition-02-42e2e428-da0e-411d-ad7d-322685f3d790.dcm", + "dicom-composition-mr-acquisition-02-4c104781-26b3-41ba-bced-c17980117735.dcm", + "dicom-composition-mr-acquisition-02-de87bbbb-0008-4ddb-9b04-0d84c6e495ba.dcm", + "dicom-composition-mr-acquisition-02-88e1577a-db1e-461f-b65f-10771719caa8.dcm", + "dicom-composition-mr-acquisition-02-20d1aaef-1142-4afc-a489-dcdd6b44023f.dcm", + "dicom-composition-mr-acquisition-02-fc889111-82a7-4975-b3c0-c2697ee4ddfb.dcm", + "dicom-composition-mr-acquisition-02-12a9492b-4d4b-4772-8112-2d3603acae0c.dcm", + "dicom-composition-mr-acquisition-02-bc9c0df3-e75f-4505-9aea-4af6f63bc483.dcm", + "dicom-composition-mr-acquisition-02-758fc031-17a8-4d75-a53c-112b106fbfb5.dcm", + "dicom-composition-mr-acquisition-02-f2a46e8a-5002-4ed9-a177-95968edee72d.dcm", + "dicom-composition-mr-acquisition-02-1aa44640-53cc-45c6-8e28-c7fafd94dcef.dcm", + "dicom-composition-mr-acquisition-02-76452ba7-528c-4ef7-b5f1-18044ea9bb25.dcm", + "dicom-composition-mr-acquisition-02-fdd34427-1293-48c3-afae-4c6765bf6779.dcm" + ], + "sopInstanceUIDs": [ + "1.3.6.1.4.1.14519.5.2.1.95800245628389430547908955664336971166", + "1.3.6.1.4.1.14519.5.2.1.10324730000090874951730116451541894560", + "1.3.6.1.4.1.14519.5.2.1.20871289937842133708603344148131563991", + "1.3.6.1.4.1.14519.5.2.1.207601200393842342415867127072398671280", + "1.3.6.1.4.1.14519.5.2.1.5019695074283757761417608292898492579", + "1.3.6.1.4.1.14519.5.2.1.244710395874376369715943521608533083799", + "1.3.6.1.4.1.14519.5.2.1.42613418119216512098730031618859421607", + "1.3.6.1.4.1.14519.5.2.1.79378288901235501366512113344307439532", + "1.3.6.1.4.1.14519.5.2.1.96214938527447624723367621124186432575", + "1.3.6.1.4.1.14519.5.2.1.11477809763946167544868963125148672216", + "1.3.6.1.4.1.14519.5.2.1.116677553804498275761354796089763839564", + "1.3.6.1.4.1.14519.5.2.1.124215952865600213334872250839850807271", + "1.3.6.1.4.1.14519.5.2.1.159565847346051610447852872136558610464", + "1.3.6.1.4.1.14519.5.2.1.105236080028506882585509543614990123305", + "1.3.6.1.4.1.14519.5.2.1.240658961409259338415298464496856630506", + "1.3.6.1.4.1.14519.5.2.1.48057063746393045761305555460588541183", + "1.3.6.1.4.1.14519.5.2.1.277576526130247578770581544443175766465", + "1.3.6.1.4.1.14519.5.2.1.31016158786533738904377172767810945877", + "1.3.6.1.4.1.14519.5.2.1.45552704547405539600621661677355908697", + "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], + "pixelHash": "3ce6cc25b707b832b0a86832964c58cffea295e99b0fdf56f02b243b7d3de1ad", + "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], + "pixelHash": "ed41b3a8545d61f6598b40efb5d7d090eb12a75f24e561e9eff63c2b914e300b", + "firstPlanePosition": [-105.23245681323, -147.49348022462, -33.429649353027], + "lastPlanePosition": [-105.23245681323, -147.49348022462, 20.570348739624] + }, + "provenance": { + "collection": "upenn_gbm", + "sourceDOI": "10.7937/tcia.709x-dn49", + "source": "https://doi.org/10.7937/tcia.709x-dn49", + "license": "CC BY 4.0", + "crdcSeriesUUID": "5660fad0-290f-482f-89a9-47411084c038", + "objectListingSource": "https://idc-open-data.s3.amazonaws.com/?list-type=2&prefix=5660fad0-290f-482f-89a9-47411084c038/", + "membershipRule": "Group exact DICOM AcquisitionNumber; sort each group by patient-position projection on normalized row cross column; require regular spacing and no in-plane drift" + }, + "acquisitionNumber": 2 + } + ] + } + ] +} diff --git a/tests/dicomDataset.ts b/tests/dicomDataset.ts new file mode 100644 index 000000000..83e99b778 --- /dev/null +++ b/tests/dicomDataset.ts @@ -0,0 +1,35 @@ +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 = ( + tags: Iterable +): DicomDataset => ({ + specificCharacterSet: null, + elements: [...tags].map(([key, value]) => { + const tag = key.replace('|', '').toUpperCase(); + return { + tag, + group: parseInt(tag.slice(0, 4), 16), + element: parseInt(tag.slice(4), 16), + vr: 'LO', + values: { kind: 'text', values: value.split('\\') }, + }; + }), +}); + +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, + transferSyntaxUid: null, + pixelData: null, + }); diff --git a/tests/dicomOrientationFixtures.ts b/tests/dicomOrientationFixtures.ts new file mode 100644 index 000000000..0b1ffe843 --- /dev/null +++ b/tests/dicomOrientationFixtures.ts @@ -0,0 +1,21 @@ +type MergingSlice = { sop: string; z: number; orientation: string }; + +export const tilt = (radians: number) => { + const cos = Math.cos(radians); + const sin = Math.sin(radians); + return [cos, sin, 0, -sin, cos, 0].join('\\'); +}; + +/** + * Orientation agreement is a tolerance, so it is not transitive: the between + * instance sorts first, the greedy walk takes its cosines as the bucket + * reference, and both others agree with it. Planned apart, the pair merges + * into one collection once the between instance arrives. + */ +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/dicomPages.ts b/tests/dicomPages.ts new file mode 100644 index 000000000..890c066cd --- /dev/null +++ b/tests/dicomPages.ts @@ -0,0 +1,26 @@ +import { DOWNLOAD_TIMEOUT } from '../wdio.shared.conf'; + +export async function openDicomPage(url: string, expectedError?: string) { + await browser.url(url); + await waitForDicomPage(expectedError); +} + +export async function waitForDicomPage( + expectedError?: string, + status = 'complete' +) { + await browser.waitUntil( + async () => + (await $('#error').isExisting()) || + ((await $('#status').isExisting()) && + (await $('#status').getText()) === status), + { timeout: DOWNLOAD_TIMEOUT } + ); + if (expectedError) { + await expect($('#error')).toHaveText(expectedError); + return; + } + if (await $('#error').isExisting()) + throw new Error(await $('#error').getText()); + await expect($('#status')).toHaveText(status); +} diff --git a/tests/dicomSourceFixtures.ts b/tests/dicomSourceFixtures.ts new file mode 100644 index 000000000..304220a8d --- /dev/null +++ b/tests/dicomSourceFixtures.ts @@ -0,0 +1,48 @@ +import { + readInstance, + type ReadInstanceOptions, +} from '@/src/dicom/core/instance/readInstance'; +import { trackedSource } from '@/tests/byteSourceFixtures'; +import { + buildSyntheticDicom, + type SyntheticSliceOptions, +} from '@/tests/specs/syntheticDicom'; + +export const syntheticSlice = ( + overrides: Partial = {} +) => + buildSyntheticDicom({ + studyUid: '1.2.826.0.1.3680043.10.998.1', + seriesUid: '1.2.826.0.1.3680043.10.998.2', + sopUid: '1.2.826.0.1.3680043.10.998.3', + instanceNumber: 1, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], + imagePositionPatient: [0, 0, 0], + ...overrides, + }); + +/** Offset of the (7fe0,0010) tag, found without the streaming parser. */ +export const pixelDataStart = (bytes: Uint8Array) => { + const tag = [0xe0, 0x7f, 0x10, 0x00]; + const at = bytes.findIndex( + (_, i) => i > 132 && tag.every((byte, j) => bytes[i + j] === byte) + ); + if (at < 0) throw new Error('fixture has no Pixel Data element'); + return at; +}; + +/** The same file with its Pixel Data element cut off, as an RT object has. */ +export const withoutPixelData = (bytes: Uint8Array) => + bytes.slice(0, pixelDataStart(bytes)); + +/** Reads a header from bytes delivered `chunkSize` at a time. */ +export const readHeader = ( + bytes: Uint8Array, + chunkSize = bytes.length, + options?: ReadInstanceOptions +) => + readInstance( + trackedSource(bytes, chunkSize).source, + new AbortController().signal, + options + ); diff --git a/tests/dicomVolumeCorpus.json b/tests/dicomVolumeCorpus.json new file mode 100644 index 000000000..8d74f75e3 --- /dev/null +++ b/tests/dicomVolumeCorpus.json @@ -0,0 +1,436 @@ +{ + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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" + } + }, + { + "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/dicomVolumeFixtures.ts b/tests/dicomVolumeFixtures.ts new file mode 100644 index 000000000..b9bdae779 --- /dev/null +++ b/tests/dicomVolumeFixtures.ts @@ -0,0 +1,20 @@ +import { + emptyRegistry, + registerInstances, +} from '@/src/dicom/core/collections/instanceRegistry'; +import { singleDecoderTable } from '@/src/dicom/core/pixels/decoderTable'; +import { + wholeInstanceDecoder, + type WholeInstanceDecode, +} 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[]) => + registerInstances(emptyRegistry, members).updates[0]; + +/** 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-pages/composition.html b/tests/fixtures/dicom-pages/composition.html new file mode 100644 index 000000000..df83f8a0e --- /dev/null +++ b/tests/fixtures/dicom-pages/composition.html @@ -0,0 +1,13 @@ + + + + + DICOM collection composition + + +

DICOM collection composition

+ +
+ + + diff --git a/tests/fixtures/dicom-pages/composition.ts b/tests/fixtures/dicom-pages/composition.ts new file mode 100644 index 000000000..30593e33b --- /dev/null +++ b/tests/fixtures/dicom-pages/composition.ts @@ -0,0 +1,114 @@ +import { + emptyRegistry, + registerInstances, +} 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'; +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?.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-pages/compositionReference.py b/tests/fixtures/dicom-pages/compositionReference.py new file mode 100644 index 000000000..7f24a81bf --- /dev/null +++ b/tests/fixtures/dicom-pages/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 page + + + +

DICOM core page

+
+ + + diff --git a/tests/fixtures/dicom-pages/core.ts b/tests/fixtures/dicom-pages/core.ts new file mode 100644 index 000000000..20163d3ad --- /dev/null +++ b/tests/fixtures/dicom-pages/core.ts @@ -0,0 +1,43 @@ +import { fromBlob, readBytes } from '@/src/dicom/core/source/byteSource'; +import { + assetUrls, + createRuntime, + firstUnit, + failed, + gdcmOnly, + never, + report, +} from './shared'; +import { fixtureBytes } from './fixtureData'; + +async function recoverWorker() { + const recovering = createRuntime({ + assets: assetUrls('./recovering-worker.js'), + decodeConcurrency: 1, + ...gdcmOnly, + }); + 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 = 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'), + (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'); +} + +recoverWorker().catch(failed); diff --git a/tests/fixtures/dicom-pages/corpus.html b/tests/fixtures/dicom-pages/corpus.html new file mode 100644 index 000000000..9d26eabf0 --- /dev/null +++ b/tests/fixtures/dicom-pages/corpus.html @@ -0,0 +1,12 @@ + + + + + DICOM volume corpus page + + +

DICOM volume corpus page

+
+ + + diff --git a/tests/fixtures/dicom-pages/corpus.ts b/tests/fixtures/dicom-pages/corpus.ts new file mode 100644 index 000000000..49c0c960d --- /dev/null +++ b/tests/fixtures/dicom-pages/corpus.ts @@ -0,0 +1,23 @@ +import { failed, never, report, runtime, sourceOf } from './shared'; +import { loadInstanceVolume } from './loadVolume'; +import { describeVolume } from './describeVolume'; + +async function run() { + const params = new URL(location.href).searchParams; + const source = params.get('source'); + const url = new URL( + `./${source === 'unranged' ? 'unranged-data' : 'corpus-data'}/${encodeURIComponent(params.get('name')!)}`, + document.baseURI + ); + const input = + source === 'file' + ? new File([await (await fetch(url)).blob()], 'volume.dcm') + : url; + const instance = await runtime.readInstance(sourceOf(input), never); + const { update, image } = await loadInstanceVolume(instance); + await describeVolume(image, report); + report('reconstruction', update.collection.reconstruction.kind); + report('status', 'complete'); +} + +run().catch(failed); diff --git a/tests/fixtures/dicom-pages/describeVolume.ts b/tests/fixtures/dicom-pages/describeVolume.ts new file mode 100644 index 000000000..899d7b705 --- /dev/null +++ b/tests/fixtures/dicom-pages/describeVolume.ts @@ -0,0 +1,28 @@ +import type vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData'; + +/** Public page 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-pages/enhancedFixtures.ts b/tests/fixtures/dicom-pages/enhancedFixtures.ts new file mode 100644 index 000000000..593fa73f2 --- /dev/null +++ b/tests/fixtures/dicom-pages/enhancedFixtures.ts @@ -0,0 +1,77 @@ +import { + buildSyntheticDicom, + combine, + ds, + sequence, + ul, +} from '../../specs/syntheticDicom'; + +const decimals = (group: number, element: number, values: readonly number[]) => + ds(group, element, values.join('\\')); + +const position = (value: readonly number[]) => + sequence(0x0020, 0x9113, [decimals(0x0020, 0x0032, value)]); + +const transformation = ([slope, intercept]: readonly [number, number]) => + sequence(0x0028, 0x9145, [ + combine( + ds(0x0028, 0x1052, String(intercept)), + ds(0x0028, 0x1053, String(slope)) + ), + ]); + +const temporalPosition = (value: number) => + sequence(0x0020, 0x9111, [ul(0x0020, 0x9128, value)]); + +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, [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) => + combine( + ...(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, [combine(...shared)]), + sequence(0x5200, 0x9230, frames), + ], + }); +} diff --git a/tests/fixtures/dicom-pages/fixtureData.ts b/tests/fixtures/dicom-pages/fixtureData.ts new file mode 100644 index 000000000..d5286eb49 --- /dev/null +++ b/tests/fixtures/dicom-pages/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-pages/loadVolume.ts b/tests/fixtures/dicom-pages/loadVolume.ts new file mode 100644 index 000000000..d1b6fa70e --- /dev/null +++ b/tests/fixtures/dicom-pages/loadVolume.ts @@ -0,0 +1,35 @@ +import { + allocateVolume, + type Volume, +} from '@/src/dicom/core/volume/allocateVolume'; +import { + emptyRegistry, + registerInstances, + type InstanceCollectionUpdate, +} 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. */ +export async function loadCollection( + update: InstanceCollectionUpdate, + previous?: Volume +) { + 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 })) { + if ('error' in loaded) throw loaded.error; + applyVolumeUpdate(image, loaded); + } + return { volume, image }; +} + +export async function loadInstanceVolume(instance: Instance) { + const [update] = registerInstances(emptyRegistry, [instance]).updates; + return { update, ...(await loadCollection(update)) }; +} diff --git a/tests/fixtures/dicom-pages/parity.html b/tests/fixtures/dicom-pages/parity.html new file mode 100644 index 000000000..611687a20 --- /dev/null +++ b/tests/fixtures/dicom-pages/parity.html @@ -0,0 +1,12 @@ + + + + + DICOM native frame parity + + +

DICOM native frame parity

+
+ + + diff --git a/tests/fixtures/dicom-pages/parity.ts b/tests/fixtures/dicom-pages/parity.ts new file mode 100644 index 000000000..e476da9ba --- /dev/null +++ b/tests/fixtures/dicom-pages/parity.ts @@ -0,0 +1,121 @@ +import { + getVolumeBufferType, + instancePixelFormats, + type VolumeBufferConstructor, +} 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, + 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 +// 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 gdcm = createRuntime(gdcmOnly); + +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, + units: DecodeUnit[], + Target: VolumeBufferConstructor +) { + const frames = await Promise.all( + 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)); + frames.reduce((offset, frame) => { + samples.set(frame, offset); + return offset + frame.length; + }, 0); + return samples; +} + +async function compare(name: string) { + const url = new URL( + `./corpus-data/${encodeURIComponent(name)}`, + document.baseURI + ); + 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 }; + 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 native = await decodeFrames(instance, units, Target); + return { + name, + plan: 'frames', + volume: Target.name, + gdcm: decoded.data.constructor.name, + native: native.constructor.name, + samples: native.length, + mismatch: firstMismatch(new Target(decoded.data), native), + rawMismatch: isFloat(decoded.data) + ? null + : firstMismatch(decoded.data, native), + }; +} + +async function run() { + const params = new URL(location.href).searchParams; + 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).catch((error: Error) => ({ + name, + error: error.message, + })) + ); + report('report', JSON.stringify(results)); + report('status', 'complete'); +} + +run().catch(failed); diff --git a/tests/fixtures/dicom-pages/server.mjs b/tests/fixtures/dicom-pages/server.mjs new file mode 100644 index 000000000..17970049f --- /dev/null +++ b/tests/fixtures/dicom-pages/server.mjs @@ -0,0 +1,142 @@ +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 { 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); + +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(/\/$/, '') }] }, + build: { + outDir, + emptyOutDir: true, + chunkSizeWarningLimit: Infinity, + rollupOptions: { input: resolve(fixture, `${kind}.html`) }, + }, + worker: { format: 'es' }, + }); + await copyItkAssets(resolve(outDir, 'assets')); +} + +/** 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('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 startDicomPages({ + kinds = ['core'], + 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 = []; + /** @type {Record} */ + const urls = {}; + try { + for (const kind of kinds) { + const outDir = resolve(directory, kind); + await buildPage(kind, outDir); + 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('/corpus-data', serveFixture(true)); + // A server that ignores Range answers every read with the file. + instance.middlewares.use('/unranged-data', serveFixture(false)); + }, + }, + ], + }); + 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-pages/shared.ts b/tests/fixtures/dicom-pages/shared.ts new file mode 100644 index 000000000..9821b15b2 --- /dev/null +++ b/tests/fixtures/dicom-pages/shared.ts @@ -0,0 +1,65 @@ +import { + createDicomRuntime, + type DicomRuntimeOptions, +} from '@/src/dicom/core/runtime/createDicomRuntime'; +import { fromBlob, fromUrl } from '@/src/dicom/core/source/byteSource'; +import { + planDecode, + singleDecoderTable, +} 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' +) => ({ + 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; + +/** 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) + : 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 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-pages/volumeCorpusReference.py b/tests/fixtures/dicom-pages/volumeCorpusReference.py new file mode 100644 index 000000000..e2ba25056 --- /dev/null +++ b/tests/fixtures/dicom-pages/volumeCorpusReference.py @@ -0,0 +1,109 @@ +"""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 + + +# 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 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] + if str(ds.get('SOPClassUID', '')) in FUNCTIONAL_GROUP_RESCALE + else [] + ) + 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(' 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, @@ -17,37 +16,125 @@ 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, 'SQ', concat(datasets.map(sequenceItem))); } -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]); - }) - ) +/** 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 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 ? [ul(0x0002, 0x0000, metaBytes.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,52 +142,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[] = [], - extraShared: Uint8Array[] = [] + { + 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('1\\0\\0\\0\\1\\0'), - ...extraShared, + 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 + ), ]); } @@ -114,82 +196,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 new file mode 100644 index 000000000..fc547b134 --- /dev/null +++ b/tests/nativePixelDicom.ts @@ -0,0 +1,245 @@ +// 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 { + 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'; +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 NUMBER_WIDTH: Record = { + US: 2, + SS: 2, + UL: 4, + SL: 4, + FL: 4, + FD: 8, +}; + +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); + 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) => + combine( + 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 enc.encode(value.length % 2 ? value + pad : value); + } + if (value instanceof Uint8Array) + return value.length % 2 ? combine(value, new Uint8Array(1)) : value; + if (vr === 'SQ') + return combine( + ...(value as DataElement[][]).map((item) => { + const body = encodeElements(item, encoding); + return combine( + 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_VRS.has(element.vr) + ? [ + enc.encode(element.vr), + new Uint8Array(2), + uint(value.length, 4, littleEndian), + ] + : [enc.encode(element.vr), uint(value.length, 2, littleEndian)] + : [uint(value.length, 4, littleEndian)]; + return combine(tagBytes(element.tag, littleEndian), ...head, value); +} + +const encodeElements = (elements: DataElement[], encoding: Encoding) => + combine( + ...[...elements] + .sort((a, b) => a.tag - b.tag) + .map((element) => encodeElement(element, 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 frameRescaleGroups = ( + rescales: ReadonlyArray +): DataElement => ({ + tag: 0x52009230, + vr: 'SQ', + value: rescales.map(([slope, intercept]) => [ + { + tag: 0x00289145, + vr: 'SQ', + value: [ + [ + { tag: 0x00281052, vr: 'DS', value: String(intercept) }, + { tag: 0x00281053, vr: 'DS', value: String(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; + // 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}`); + 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: String(rescale[1]) }, + { tag: 0x00281053, vr: 'DS', value: String(rescale[0]) } + ); + if (frameRescales) dataset.push(frameRescaleGroups(frameRescales)); + 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 5494eee30..2dcf32a33 100644 --- a/tests/pageobjects/volview.page.ts +++ b/tests/pageobjects/volview.page.ts @@ -68,6 +68,67 @@ 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'); + } + + /** Waits for the volume cards' "[N]" slice counts, ascending, to be `expected`. */ + async waitForVolumeCardSliceCounts(expected: number[]) { + await browser.waitUntil( + async () => { + 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, + timeoutMsg: `expected volume cards holding ${expected.join( + ', ' + )} slices`, + } + ); + } + + /** Deletes the volume whose card label carries `[sliceCount]`. */ + async deleteVolumeCard(sliceCount: number) { + const menu = $(`.volume-card*=[${sliceCount}]`).$( + 'button[data-testid="dataset-menu-button"]' + ); + await menu.waitForClickable(); + await menu.click(); + const remove = $('.v-overlay-container').$('.v-list-item=Delete'); + await remove.waitForClickable(); + await remove.click(); + } + get notifications() { return $('#notifications'); } @@ -92,8 +153,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' ); @@ -302,10 +372,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..a33077b7e 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,17 +128,27 @@ 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(); + for (const slot of [0, 1, 2]) + await expect($$('.grid-item')[slot].$('.slice-label')).toHaveText( + 'Slice: 9/16' + ); const before = await getSlices(); // Drag the crosshair well off centre in a view of the other image. @@ -124,10 +166,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..75ae9bd07 100644 --- a/tests/specs/dicom-dimension-mismatch.e2e.ts +++ b/tests/specs/dicom-dimension-mismatch.e2e.ts @@ -1,206 +1,69 @@ -// 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 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 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 }; - -async function writeSeries( - dirName: string, - series: Size, - outlier: Size, - outlierSlice: number, - manifestName: string -) { - const dir = makeTempDir(dirName); +const DIR_NAME = 'geometry-split'; +async function writeSeries(manifestName: string) { + const dir = makeTempDir(DIR_NAME); 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 resources = Array.from({ length: SLICE_COUNT }, (_, i) => { + const scout = i === 0; const filename = `slice-${i}.dcm`; fs.writeFileSync( path.join(dir, filename), buildSyntheticDicom({ studyUid, seriesUid, - sopUid, + sopUid: newUid(), instanceNumber: i + 1, - imageOrientationPatient: IMAGE_ORIENTATION_PATIENT, + imageOrientationPatient: [1, 0, 0, 0, 1, 0], imagePositionPatient: [0, 0, i], - rows, - cols, + rows: scout ? 8 : 4, + cols: scout ? 10 : 6, }) ); - 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(); - await browser.waitUntil( - async () => (await getRenderedSliceCount()) === SLICE_COUNT, - { - timeout: 30000, - timeoutMsg: `expected the 2D view to show a ${SLICE_COUNT} slice volume`, - } - ); - 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 { url: `tmp/${DIR_NAME}/${filename}`, name: filename }; }); - return details.getText(); -} - -async function loadAndReadRejection(manifestName: string) { - await volViewPage.open(`?urls=[tmp/${manifestName}]`); - await volViewPage.waitForNotification(); - await waitForSeriesToSettle(); - const errorCount = await volViewPage.getNotificationsCount(); - const text = await readErrorDetails(); - return { text, errorCount }; + await writeManifestToFile({ resources }, manifestName); } -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 - ); - - const { text, errorCount } = await loadAndReadRejection(manifestName); - - 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); - }); - - // 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 - ); - - const { text, errorCount } = await loadAndReadRejection(manifestName); - - 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); - }); - - // 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 +describe('DICOM series with instances of two pixel geometries', () => { + 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]); + + // 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( + (thumbnail) => thumbnail.getAttribute('src') + ); + return ( + sources.length === 2 && + sources.every((src) => !!src && src.startsWith('data:image/')) + ); + }, + { + timeout: DOWNLOAD_TIMEOUT, + 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`); + // 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 new file mode 100644 index 000000000..db569cf4f --- /dev/null +++ b/tests/specs/dicom-frame-reconstruction.e2e.ts @@ -0,0 +1,93 @@ +import { createHash } from 'node:crypto'; +import { writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { openDicomPage } from '../dicomPages'; +import { enhancedFixtureBytes } from '../fixtures/dicom-pages/enhancedFixtures'; +import { startDicomPages } from '../fixtures/dicom-pages/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], + }), + 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 scenarios = [ + { + name: 'uneven', + source: 'file', + values: [20, 120, 220], + reconstruction: 'irregular', + }, + { + name: 'uniform', + source: 'http', + values: [4, 4], + reconstruction: 'regular', + }, +]; + +describe('Encoded multiframe reconstruction contracts', () => { + let fixture: Awaited>; + before(async () => { + fixture = await startDicomPages({ kinds: ['corpus'], fixtures: frames }); + }); + after(async () => fixture?.close()); + + 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', () => { + 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 new file mode 100644 index 000000000..53576fc0c --- /dev/null +++ b/tests/specs/dicom-import-regressions.e2e.ts @@ -0,0 +1,208 @@ +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { PNG } from 'pngjs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { + buildSyntheticDicom, + newUid, + rawElement, + sequenceItem, + toImplicitVr, + undefinedLengthUnknown, +} from './syntheticDicom'; +import { dropFiles, makeTempDir } 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 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 dropFiles(paths); +} + +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 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('loads every slice in order 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], + pixelValue: i, + }) + ); + + await dropSlices(files); + await volViewPage.waitForVolumeCardSliceCounts([121]); + await volViewPage.waitForViews(); + await volViewPage.waitForLoadingIndicator( + $('[data-testid~="vtk-two-view"]') + ); + 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 dropSlices([ + buildSyntheticDicom({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + instanceNumber: 1, + imageOrientationPatient: AXIAL, + imagePositionPatient: [0, 0, 0], + 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('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], + 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(), + 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..2cd7cd61e --- /dev/null +++ b/tests/specs/dicom-japanese-name.e2e.ts @@ -0,0 +1,43 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import { cleanuptotal } from 'wdio-cleanuptotal-service'; + +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'; +import { newUid } from './syntheticDicom'; +import { writeManifestToFile } from './utils'; + +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 = `japanese-name-${stamp}.dcm`; + const filePath = path.join(TEMP_DIR, fileName); + fs.writeFileSync( + filePath, + buildSlice({ + studyUid: newUid(), + seriesUid: newUid(), + sopUid: newUid(), + specificCharacterSet: JAPANESE_CHARACTER_SET, + patientNameBytes: JAPANESE_NAME_BYTES, + }) + ); + cleanuptotal.addCleanup(async () => fs.unlinkSync(filePath)); + 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 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 fbc261b43..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('preserves the public DSC series Float64 output 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'); - const expected = STORED_VALUES.flatMap((stored) => - Array(ROWS * COLUMNS).fill(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 new file mode 100644 index 000000000..de88ae586 --- /dev/null +++ b/tests/specs/dicom-module-pages.e2e.ts @@ -0,0 +1,20 @@ +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 decode worker without VolView startup', () => { + let fixture: Awaited>; + before(async () => { + 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); + await expect($('#first-error')).toHaveText('DICOM decoder worker failed'); + await expect($('#queued-pixels')).toHaveText(CALIBRATED_PIXELS); + await expect($('#retry-pixels')).toHaveText(CALIBRATED_PIXELS); + }); +}); diff --git a/tests/specs/dicom-native-parity.e2e.ts b/tests/specs/dicom-native-parity.e2e.ts new file mode 100644 index 000000000..944dc215e --- /dev/null +++ b/tests/specs/dicom-native-parity.e2e.ts @@ -0,0 +1,202 @@ +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'; +import { + EXPLICIT_BE, + 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', + WordSC: '1.2.840.10008.5.1.4.1.1.7.3', +}; + +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] }], + ['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]] }], + ['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] }], + [`${name}-fractional-rescale`, true, { sopClassUid, pixelRepresentation: 1, rescale: [0.7, 2.5] }], + ] + ), +]; + +/** 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 [file] = Object.values(archive.files).filter((entry) => !entry.dir); + return [`${zip}/${file.name}`, await file.async('uint8array')] as const; +}; + +// 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; + 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 publicFiles = [ + ...[ + 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( + ([name, , options], index) => + [name, nativePixelDicom({ ...options, instance: index + 1 })] as const + ), + ...publicFiles, + ]; + cases = files.map(([name]) => name); + synthetic.forEach(([name, native]) => expectedNative.set(name, native)); + publicFiles.forEach(([name]) => + expectedNative.set(name, publicNative(name)) + ); + fixture = await startDicomPages({ + 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 (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-volume-composition.e2e.ts b/tests/specs/dicom-volume-composition.e2e.ts new file mode 100644 index 000000000..1a1502214 --- /dev/null +++ b/tests/specs/dicom-volume-composition.e2e.ts @@ -0,0 +1,110 @@ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import corpus from '../dicomCompositionCorpus.json'; +import { DATASET_CACHE } from '../downloadDatasets'; +import { waitForDicomPage } from '../dicomPages'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; +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 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, 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); + }); + } + } +}); + +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.waitForViewsLoaded(); + await waitForRenderedSlice( + `composition-${scenario.id}.png`, + 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..53e1fa07f --- /dev/null +++ b/tests/specs/dicom-volume-corpus.e2e.ts @@ -0,0 +1,175 @@ +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { Key } from 'webdriverio'; +import volumeCorpus from '../dicomVolumeCorpus.json'; +import { DATASET_CACHE } from '../downloadDatasets'; +import { openDicomPage } from '../dicomPages'; +import { nullPaddedFixtureBytes } from '../fixtures/dicom-pages/fixtureData'; +import { startDicomPages } from '../fixtures/dicom-pages/server.mjs'; +import { volViewPage } from '../pageobjects/volview.page'; +import { + waitForRenderedSlice, + waitForRenderedSliceChange, +} from './dicomRenderedSlice'; + +const corpus = volumeCorpus.datasets; + +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 startDicomPages({ + kinds: ['corpus'], + fixtures: { + ...files, + 'null-padded-numbers.dcm': nullPaddedFixtureBytes(), + 'null-padded-fractional-rescale.dcm': nullPaddedFixtureBytes( + fractionalCalibration + ), + }, + }); + }); + 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']) { + 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', () => { + 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.waitForViewsLoaded(); + 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/dicomElementFixtures.ts b/tests/specs/dicomElementFixtures.ts new file mode 100644 index 000000000..e934af549 --- /dev/null +++ b/tests/specs/dicomElementFixtures.ts @@ -0,0 +1,332 @@ +import { + attributeTagValue, + buildSyntheticCineDicom, + buildSyntheticDicom, + combine, + rawElement, + SyntheticSliceOptions, + undefinedLengthItem, + undefinedLengthSequence, +} from './syntheticDicom'; + +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); + +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( + 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 = combine( + 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 = combine( + 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 = combine( + 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; +}; + +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 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 = combine( + bytes(0xd4, 0xcf, 0xc0, 0xde), + ascii('^'), + bytes(0xc0, 0xdb, 0xb3), + ascii('='), + jisX0208(0x3b, 0x33, 0x45, 0x44), + ascii('^'), + 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 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)), + 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', + combine( + 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( + combine( + 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 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. + 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/dicomRenderedSlice.ts b/tests/specs/dicomRenderedSlice.ts new file mode 100644 index 000000000..b0fb50442 --- /dev/null +++ b/tests/specs/dicomRenderedSlice.ts @@ -0,0 +1,90 @@ +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) { + const [view] = await captureViewPixels( + '[data-testid~="vtk-two-view"]', + VIEW_INSET, + fileName + ); + if (!view) throw new Error('No slice viewport'); + return { ...view, height: view.data.length / 4 / view.width }; +} + +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, color = false) { + await $('header').moveTo(); + let image: RenderedSlice | undefined; + await browser.waitUntil( + async () => { + image = await captureSlice(fileName); + 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 +) { + await $('header').moveTo(); + await browser.waitUntil( + async () => { + const after = await captureSlice(fileName); + return hasImageContent(after) && imageChanged(before, after); + }, + { + timeoutMsg: + 'Expected slice navigation to change the interior image pixels', + } + ); +} diff --git a/tests/specs/imageCacheUtils.ts b/tests/specs/imageCacheUtils.ts index 78f680e11..10cbe0064 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) => { +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/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/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/octTestUtils.ts b/tests/specs/octTestUtils.ts index 4693d4066..629e70575 100644 --- a/tests/specs/octTestUtils.ts +++ b/tests/specs/octTestUtils.ts @@ -160,10 +160,12 @@ 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(); + // En face stays disabled until the complete volume has loaded. + 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..28b98b392 100644 --- a/tests/specs/pet-ct-sample.e2e.ts +++ b/tests/specs/pet-ct-sample.e2e.ts @@ -1,6 +1,6 @@ import * as path from 'path'; import { readFileSync, writeFileSync } from 'node:fs'; -import dicomParser from 'dicom-parser'; +import dcmjs from 'dcmjs'; import { TEMP_DIR } from '@/wdio.shared.conf'; import { PET_CT_DICOM_DATASETS } from '../datasets'; import { setValueVueInput, volViewPage } from '../pageobjects/volview.page'; @@ -40,13 +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.scrollIntoView(); + 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(); } @@ -61,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"]'); @@ -125,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(); @@ -149,28 +160,25 @@ 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'); - const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); - await sample.waitForExist(); - await waitForModuleTransitions(); - await sample.scrollIntoView({ block: 'center', behavior: 'instant' }); +} + +async function reopenSample( + expected: Awaited>, + range: string[], + preset = 'DICOM Hot Iron' +) { + await showSampleData(); 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(); @@ -186,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) ); @@ -220,6 +221,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' ) { @@ -227,29 +240,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( @@ -303,28 +304,19 @@ describe('PET/CT sample', () => { const ctFile = PET_CT_DICOM_DATASETS.find(({ name }) => name.startsWith('PET-CT-CT-') )!; - const tags = dicomParser.parseDicom( - 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 width = Number(tags.string('x00281051')!.split('\\')[0]); - const level = Number(tags.string('x00281050')!.split('\\')[0]); + const firstValue = (tag: string) => Number(dict[tag]!.Value[0]); + const width = firstValue('00281051'); + const level = firstValue('00281050'); expect(width).toBeGreaterThan(0); expect(Number.isFinite(level)).toBe(true); 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(); - } - const sample = volViewPage.samplesList.$('[title="PET/CT Chest"]'); - await sample.scrollIntoView({ block: 'center', behavior: 'instant' }); - await sample.waitForClickable(); - await sample.click(); + await showSampleData(); + await clickSample(); await expect($('[data-testid~="vtk-two-view"]')).toHaveText( expect.stringContaining('CT WB') ); @@ -382,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(); @@ -423,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') ); @@ -499,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/sample-rendering.e2e.ts b/tests/specs/sample-rendering.e2e.ts index 632bee255..ac6b8fbb7 100644 --- a/tests/specs/sample-rendering.e2e.ts +++ b/tests/specs/sample-rendering.e2e.ts @@ -11,7 +11,9 @@ describe('VolView', () => { await AppPage.open(); await AppPage.downloadProstateSample(); - await AppPage.waitForViews(); + + 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 new file mode 100644 index 000000000..dfbb2a6b0 --- /dev/null +++ b/tests/specs/session-overlapping-imports.e2e.ts @@ -0,0 +1,74 @@ +// 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. +import * as path from 'path'; +import { volViewPage } from '../pageobjects/volview.page'; +import { TEMP_DIR } from '../../wdio.shared.conf'; +import { + SESSION_SAVE_TIMEOUT, + dropFiles, + waitForFileExists, + writeAcquisitions, + writeManifestToFile, +} from './utils'; +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. +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 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 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); + }); + + 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); + 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(FIRST_PASS.sliceCount); + const survivor = [SECOND_PASS.sliceCount]; + 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..f2c4d5002 100644 --- a/tests/specs/syntheticDicom.ts +++ b/tests/specs/syntheticDicom.ts @@ -1,18 +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, -// 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'; 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(); -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); @@ -25,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); @@ -33,7 +35,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; @@ -44,66 +46,181 @@ 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', - 'OW', - 'SQ', - '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(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 = 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) => + 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) => + 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) => + rawElement( + g, + e, + 'PN', + v.length % 2 === 0 ? v : combine(v, new Uint8Array([0x20])) + ); + +// 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 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(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(group, element), - enc.encode(vr), - new Uint8Array(2), - writeLong(value.length), - value + elementHeader(group, element, vr, UNDEFINED_LENGTH), + items, + SEQUENCE_DELIMITER ); -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 us = (g: number, e: number, v: number) => - elemShort(g, e, 'US', writeShort(v)); +/** + * 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 +) => 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 +) => 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. +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 !== ITEM_GROUP) + 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'); + out.push( + sequenceItem( + toImplicitVr(value.subarray(contentStart, contentStart + length)) + ) + ); + 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(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. @@ -121,6 +238,14 @@ 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; +}; + export type SyntheticSliceOptions = { studyUid: string; seriesUid: string; @@ -134,7 +259,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,17 +273,59 @@ 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 { +/** 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, @@ -173,14 +342,24 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { rescaleSlope, rescaleIntercept, pixelValue = 0, - pixelSpacing = [1, 1] as const, + rgbPixels, + framePixelValues, + rootGeometry = true, + pixelSpacing = [1, 1], 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 +368,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 +397,41 @@ export function buildSyntheticDicom(opts: SyntheticSliceOptions): Uint8Array { ...(spacingBetweenSlices == null ? [] : [ds(0x0018, 0x0088, String(spacingBetweenSlices))]), + ...(ultrasoundRegion == null + ? [] + : [ + 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), 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?.join('\\') ?? ''), + ds(0x0020, 0x0037, imageOrientationPatient.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.join('\\'))] : []), us(0x0028, 0x0100, bitsAllocated), us(0x0028, 0x0101, bitsStored), us(0x0028, 0x0102, highBit), @@ -231,23 +440,58 @@ 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, + rawElement(0x7fe0, 0x0010, bitsAllocated === 8 ? 'OB' : 'OW', pixels) ); - const fileMetaBody = combine( - elemLong(0x0002, 0x0001, 'OB', new Uint8Array([0x00, 0x01])), - ui(0x0002, 0x0002, SOP_CLASS_MR), - ui(0x0002, 0x0003, sopUid), - ui(0x0002, 0x0010, TS_EXPLICIT_VR_LE) + return part10File( + sopClassUid, + sopUid, + implicitVr ? TS_IMPLICIT_VR_LE : TS_EXPLICIT_VR_LE, + implicitVr ? toImplicitVr(explicitDataset) : explicitDataset ); - const fileMeta = combine( - elemShort(0x0002, 0x0000, 'UL', writeLong(fileMetaBody.length)), - fileMetaBody +} + +/** 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 EncapsulatedFrames = { + /** Each frame's fragments, in order. */ + frames: readonly (readonly Uint8Array[])[]; + /** Whether the Basic Offset Table lists where each frame starts. */ + offsetTable?: boolean; +}; - return combine(new Uint8Array(128), enc.encode('DICM'), fileMeta, dataset); +/** 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(sequenceItem)) + ); + 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, SEQUENCE_DELIMITER); } export type SyntheticCineOptions = { @@ -262,11 +506,13 @@ 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( - opts: SyntheticCineOptions -): Uint8Array { +export function buildSyntheticCineDicom(opts: SyntheticCineOptions) { const { studyUid, seriesUid, @@ -274,15 +520,15 @@ export function buildSyntheticCineDicom( numberOfFrames = 3, rows = 4, cols = 5, - pixelSpacing = [1, 1] as const, + pixelSpacing = [1, 1], patientName = 'TEST', patientId = 'TEST001', seriesNumber = 1, studyDate = '20260101', + encapsulated, + extraElements = [], } = opts; - - const pixelData = new Uint8Array(numberOfFrames * rows * cols); - for (let i = 0; i < pixelData.length; i++) pixelData[i] = i % 251; + const frames = encapsulated?.frames.length ?? numberOfFrames; const dataset = combine( ui(0x0008, 0x0016, SOP_CLASS_ULTRASOUND_MULTIFRAME), @@ -290,6 +536,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,32 +545,39 @@ 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)), + 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), - elemLong(0x7fe0, 0x0010, 'OB', pixelData) + ...extraElements, + encapsulated + ? 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, TS_EXPLICIT_VR_LE) - ); - 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 01532ec11..130ed4c5b 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, @@ -299,6 +300,83 @@ 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); +} + +const ACQUISITION_SLICE_SPACING = 2.5; + +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 1e818edb7..d0e2d0e2b 100644 --- a/tests/unit/octFixture.ts +++ b/tests/unit/octFixture.ts @@ -1,90 +1,85 @@ -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 { 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 '@/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'; 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'; +import { createSyntheticOCT } from '../fixtures/oct/dicom'; -/** Reads the named VolView tags, standing in for the itk-wasm tag reader. */ -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]]; +/** 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 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[]) { + const update = plannedUpdate(instances); + if (update.members.length === instances.length) return allocateVolume(update); + return allocateVolume({ + members: instances, + collection: { + ...plannedUpdate([instances[0]]).collection, + reconstruction: { + kind: 'irregular', + reason: 'unreadable-geometry', + sliceSpacing: null, + }, + }, }); } -/** Uses synthetic pixels and production chunk/file loaders without a browser WASM worker. */ -export function createOCTFixture( +// Decodes every frame of an uncompressed little endian 16 bit instance. +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: [count('00280011'), count('00280010'), count('00280008', 1)], + data: Uint16Array.from({ length: length! / 2 }, (_, index) => + values.getUint16(index * 2, true) + ), + components: count('00280002', 1), + }; +}; + +/** 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()); - if (options.scanPattern) { - const data = dicomParser.parseDicom(bytes, { untilTag: 'x7fe00010' }); - overwriteDicomString( - data.elements.x00221618.items![0].dataSet!, - 'x00080100', - options.scanPattern - ); - } - const file = new File([bytes], 'synthetic-oct.dcm'); - const chunk = new Chunk({ - metaLoader: new DicomFileMetaLoader(file, readDicomTags), - dataLoader: new DicomFileDataLoader(file), - }); + const bytes = Uint8Array.from( + createSyntheticOCT({ scanPattern: options.scanPattern }) + ); + 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( + decodingWith(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 +102,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/vite.config.ts b/vite.config.ts index d17b0d6a1..1a1c0a526 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,