@dcmjs-org/dicomdir 1.0.0-beta.3 → 1.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/License.txt ADDED
@@ -0,0 +1,22 @@
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2017 Steve Pieper
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/package.json CHANGED
@@ -1,8 +1,12 @@
1
1
  {
2
2
  "name": "@dcmjs-org/dicomdir",
3
- "version": "1.0.0-beta.3",
3
+ "version": "1.0.0-beta.4",
4
4
  "description": "DICOMDIR (Media Storage Directory, PS3.10) building and writing: turns a flat file-set description into the PATIENT/STUDY/SERIES/leaf record hierarchy with real byte offsets, serialized in one pass",
5
5
  "main": "./src/index.js",
6
+ "files": [
7
+ "src",
8
+ "README.md"
9
+ ],
6
10
  "license": "MIT",
7
11
  "repository": {
8
12
  "type": "git",
@@ -10,10 +14,10 @@
10
14
  "directory": "packages/dicomdir"
11
15
  },
12
16
  "dependencies": {
13
- "@dcmjs-org/core": "1.0.0-beta.3"
17
+ "@dcmjs-org/core": "1.0.0-beta.4"
14
18
  },
15
19
  "devDependencies": {
16
- "@dcmjs-org/parser": "1.0.0-beta.3",
17
- "@dcmjs-org/legacy": "1.0.0-beta.3"
20
+ "@dcmjs-org/legacy": "1.0.0-beta.4",
21
+ "@dcmjs-org/parser": "1.0.0-beta.4"
18
22
  }
19
23
  }
@@ -1,285 +0,0 @@
1
- // packages/dicomdir/test/dicomdir.test.js
2
- //
3
- // DICOMDIR builder: record hierarchy, and — the critical property — real
4
- // byte offsets. Ground truth is the written buffer itself: every nonzero
5
- // offset value must land exactly on an FFFE,E000 item tag, and walking the
6
- // next/lower chains must visit every record once in hierarchy order.
7
-
8
- import { DicomMetaDictionary, validationLog } from "@dcmjs-org/core";
9
- // The legacy eager reader is the readback oracle only — a devDependency of
10
- // this package's tests, never a runtime import of its src/.
11
- import { DicomMessage } from "@dcmjs-org/legacy";
12
- import {
13
- writeDicomDir,
14
- MEDIA_STORAGE_DIRECTORY_SOP_CLASS_UID
15
- } from "../src/index.js";
16
-
17
- validationLog.setLevel(5);
18
-
19
- const MR_SOP_CLASS = "1.2.840.10008.5.1.4.1.1.4";
20
- const ELE = "1.2.840.10008.1.2.1";
21
-
22
- function entry(overrides = {}) {
23
- return {
24
- referencedFileID: ["DICOM", "IM000001"],
25
- sopClassUid: MR_SOP_CLASS,
26
- sopInstanceUid: "1.2.3.4.100",
27
- transferSyntaxUid: ELE,
28
- patient: { PatientID: "998877", PatientName: "DOE^JANE" },
29
- study: { StudyInstanceUID: "1.2.3.4", StudyDescription: "HEAD^BRAIN" },
30
- series: { SeriesInstanceUID: "1.2.3.4.5", Modality: "MR" },
31
- instance: { InstanceNumber: 1 },
32
- ...overrides
33
- };
34
- }
35
-
36
- function readDicomDir(arrayBuffer) {
37
- const dicomDict = DicomMessage.readFile(arrayBuffer);
38
- return {
39
- meta: DicomMetaDictionary.naturalizeDataset(dicomDict.meta),
40
- dataset: DicomMetaDictionary.naturalizeDataset(dicomDict.dict)
41
- };
42
- }
43
-
44
- function recordsOf(dataset) {
45
- const sequence = dataset.DirectoryRecordSequence;
46
- return Array.isArray(sequence) ? sequence : [sequence];
47
- }
48
-
49
- /** Assert the four bytes at `offset` are the FFFE,E000 item tag (LE). */
50
- function expectItemTagAt(bytes, offset) {
51
- expect(bytes[offset]).toBe(0xfe);
52
- expect(bytes[offset + 1]).toBe(0xff);
53
- expect(bytes[offset + 2]).toBe(0x00);
54
- expect(bytes[offset + 3]).toBe(0xe0);
55
- }
56
-
57
- describe("record hierarchy", () => {
58
- test("one entry yields PATIENT/STUDY/SERIES/IMAGE", () => {
59
- const { dataset } = readDicomDir(writeDicomDir([entry()]));
60
- expect(recordsOf(dataset).map(r => r.DirectoryRecordType)).toEqual([
61
- "PATIENT",
62
- "STUDY",
63
- "SERIES",
64
- "IMAGE"
65
- ]);
66
- });
67
-
68
- test("two entries in one series share the branch", () => {
69
- const { dataset } = readDicomDir(
70
- writeDicomDir([
71
- entry(),
72
- entry({
73
- referencedFileID: ["DICOM", "IM000002"],
74
- sopInstanceUid: "1.2.3.4.101",
75
- instance: { InstanceNumber: 2 }
76
- })
77
- ])
78
- );
79
- expect(recordsOf(dataset).map(r => r.DirectoryRecordType)).toEqual([
80
- "PATIENT",
81
- "STUDY",
82
- "SERIES",
83
- "IMAGE",
84
- "IMAGE"
85
- ]);
86
- });
87
-
88
- test("two patients chain as siblings", () => {
89
- const { dataset } = readDicomDir(
90
- writeDicomDir([
91
- entry(),
92
- entry({
93
- patient: { PatientID: "22446688", PatientName: "FOX^JANE" },
94
- study: { StudyInstanceUID: "9.8.7" },
95
- series: { SeriesInstanceUID: "9.8.7.6", Modality: "MR" },
96
- sopInstanceUid: "9.8.7.6.5",
97
- referencedFileID: ["DICOM", "IM000002"]
98
- })
99
- ])
100
- );
101
- const types = recordsOf(dataset).map(r => r.DirectoryRecordType);
102
- expect(types.filter(t => t === "PATIENT")).toHaveLength(2);
103
- });
104
-
105
- test("leaf carries the file reference", () => {
106
- const { dataset } = readDicomDir(writeDicomDir([entry()]));
107
- const image = recordsOf(dataset).find(
108
- r => r.DirectoryRecordType === "IMAGE"
109
- );
110
- expect(image.ReferencedFileID).toEqual(["DICOM", "IM000001"]);
111
- expect(image.ReferencedSOPClassUIDInFile).toBe(MR_SOP_CLASS);
112
- expect(image.ReferencedSOPInstanceUIDInFile).toBe("1.2.3.4.100");
113
- expect(image.ReferencedTransferSyntaxUIDInFile).toBe(ELE);
114
- });
115
- });
116
-
117
- describe("offsets are real byte positions", () => {
118
- const entries = [
119
- entry(),
120
- entry({
121
- referencedFileID: ["DICOM", "IM000002"],
122
- sopInstanceUid: "1.2.3.4.101",
123
- instance: { InstanceNumber: 2 }
124
- }),
125
- entry({
126
- patient: { PatientID: "22446688", PatientName: "FOX^JANE" },
127
- study: { StudyInstanceUID: "9.8.7" },
128
- series: { SeriesInstanceUID: "9.8.7.6", Modality: "MR" },
129
- sopInstanceUid: "9.8.7.6.5",
130
- referencedFileID: ["DICOM", "IM000003"]
131
- })
132
- ];
133
-
134
- const buffer = writeDicomDir(entries, { fileSetUID: "2.25.42" });
135
- const bytes = new Uint8Array(buffer);
136
- const { dataset } = readDicomDir(buffer);
137
- const records = recordsOf(dataset);
138
-
139
- test("every nonzero offset lands on an FFFE,E000 item tag", () => {
140
- const offsets = [
141
- dataset.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity,
142
- dataset.OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity,
143
- ...records.flatMap(r => [
144
- r.OffsetOfTheNextDirectoryRecord,
145
- r.OffsetOfReferencedLowerLevelDirectoryEntity
146
- ])
147
- ].filter(offset => offset !== 0);
148
-
149
- expect(offsets.length).toBeGreaterThan(0);
150
- for (const offset of offsets) {
151
- expectItemTagAt(bytes, offset);
152
- }
153
- });
154
-
155
- test("chain links + first root offset address every record exactly once", () => {
156
- // Every record is referenced exactly once: the first root record by
157
- // the root offset, every other record by exactly one next/lower
158
- // link. The union must therefore have exactly one offset per record,
159
- // each landing on an item tag. Records were flattened depth-first,
160
- // so sorted offsets correspond to sequence order.
161
- const referenced = records
162
- .flatMap(r => [
163
- r.OffsetOfTheNextDirectoryRecord,
164
- r.OffsetOfReferencedLowerLevelDirectoryEntity
165
- ])
166
- .filter(offset => offset !== 0);
167
- const all = [
168
- dataset.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity,
169
- ...referenced
170
- ];
171
-
172
- expect(all).toHaveLength(records.length); // no double references
173
- const unique = [...new Set(all)].sort((a, b) => a - b);
174
- expect(unique).toHaveLength(records.length); // no shared targets
175
- for (const offset of unique) {
176
- expectItemTagAt(bytes, offset);
177
- }
178
- });
179
-
180
- test("offsets are strictly increasing in sequence order", () => {
181
- const referenced = records
182
- .flatMap(r => [
183
- r.OffsetOfTheNextDirectoryRecord,
184
- r.OffsetOfReferencedLowerLevelDirectoryEntity
185
- ])
186
- .filter(o => o !== 0);
187
- const all = [
188
- dataset.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity,
189
- ...referenced
190
- ];
191
- const sorted = [...new Set(all)].sort((a, b) => a - b);
192
- expect(sorted[0]).toBe(
193
- dataset.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity
194
- );
195
- });
196
-
197
- test("root first/last point at the two PATIENT records", () => {
198
- const first =
199
- dataset.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity;
200
- const last =
201
- dataset.OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity;
202
- expect(first).not.toBe(0);
203
- expect(last).not.toBe(0);
204
- expect(last).toBeGreaterThan(first);
205
- // First PATIENT's next-sibling link is the last PATIENT.
206
- expect(records[0].OffsetOfTheNextDirectoryRecord).toBe(last);
207
- // Last sibling terminates its chain.
208
- const lastPatient = records.find(
209
- (r, i) => r.DirectoryRecordType === "PATIENT" && i > 0
210
- );
211
- expect(lastPatient.OffsetOfTheNextDirectoryRecord).toBe(0);
212
- });
213
-
214
- test("deterministic: same entries + fileSetUID -> identical bytes", () => {
215
- const again = writeDicomDir(entries, { fileSetUID: "2.25.42" });
216
- expect(new Uint8Array(again)).toEqual(bytes);
217
- });
218
- });
219
-
220
- describe("file meta and root attributes", () => {
221
- const buffer = writeDicomDir([entry()], {
222
- fileSetID: "FOX_CD",
223
- fileSetUID: "2.25.7"
224
- });
225
- const { meta, dataset } = readDicomDir(buffer);
226
-
227
- test("meta group carries the Media Storage Directory SOP class", () => {
228
- expect(meta.MediaStorageSOPClassUID).toBe(
229
- MEDIA_STORAGE_DIRECTORY_SOP_CLASS_UID
230
- );
231
- expect(meta.MediaStorageSOPInstanceUID).toBe("2.25.7");
232
- expect(meta.TransferSyntaxUID).toBe(ELE);
233
- });
234
-
235
- test("body has file-set attributes but no SOP Common", () => {
236
- expect(dataset.FileSetID).toBe("FOX_CD");
237
- expect(dataset.FileSetConsistencyFlag).toBe(0);
238
- expect(dataset.SOPClassUID).toBeUndefined();
239
- expect(dataset.SOPInstanceUID).toBeUndefined();
240
- });
241
- });
242
-
243
- describe("validation", () => {
244
- test("non-conformant file ID component throws with guidance", () => {
245
- expect(() =>
246
- writeDicomDir([
247
- entry({ referencedFileID: ["series1", "img001.dcm"] })
248
- ])
249
- ).toThrow(/not ISO 9660 level 1 conformant/);
250
- });
251
-
252
- test("allowNonConformingFileIDs bypasses the check", () => {
253
- const buffer = writeDicomDir(
254
- [entry({ referencedFileID: ["series1", "img001.dcm"] })],
255
- { allowNonConformingFileIDs: true }
256
- );
257
- const { dataset } = readDicomDir(buffer);
258
- const image = recordsOf(dataset).find(
259
- r => r.DirectoryRecordType === "IMAGE"
260
- );
261
- expect(image.ReferencedFileID).toEqual(["series1", "img001.dcm"]);
262
- });
263
-
264
- test("missing PatientID throws", () => {
265
- expect(() =>
266
- writeDicomDir([entry({ patient: { PatientName: "X" } })])
267
- ).toThrow(/PatientID is required/);
268
- });
269
-
270
- test("missing StudyInstanceUID throws", () => {
271
- expect(() =>
272
- writeDicomDir([entry({ study: { StudyID: "1" } })])
273
- ).toThrow(/StudyInstanceUID is required/);
274
- });
275
-
276
- test("empty file set writes with zero root offsets", () => {
277
- const { dataset } = readDicomDir(writeDicomDir([]));
278
- expect(
279
- dataset.OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity
280
- ).toBe(0);
281
- expect(
282
- dataset.OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity
283
- ).toBe(0);
284
- });
285
- });
@@ -1,303 +0,0 @@
1
- // packages/dicomdir/test/mediaRoundTrip.long.test.js
2
- //
3
- // Opt-in long test: a full media round trip at video scale. Skipped unless
4
- // DCMJS_LONG_TESTS is set, because it writes a multi-gigabyte file to the
5
- // temp directory:
6
- //
7
- // DCMJS_LONG_TESTS=1 pnpm jest packages/dicomdir
8
- //
9
- // What it pins: a DICOMDIR itself never contains pixel data — the records
10
- // carry only paths and identity attributes, so writeDicomDir's cost does not
11
- // depend on how big the referenced files are. The size-sensitive half of a
12
- // media workflow is reading the referenced files back, and that must go
13
- // through the bounded-memory streaming path. So this test builds the media
14
- // a real burner would: a synthesized MPEG-4 (Sup 149/225-style) video
15
- // instance far larger than any sane heap allocation, streamed to disk chunk
16
- // by chunk, plus the DICOMDIR that indexes it. Then it reads the media back
17
- // the way a workstation would: parse the DICOMDIR (ordinary Part 10, tiny),
18
- // resolve ReferencedFileID to the file on disk, and stream-parse the huge
19
- // file through fromPart10Stream with a listener that retains nothing —
20
- // proving the indexed file is readable end-to-end at a size that would OOM
21
- // any buffer-everything path. (The memory *bounds* of the streaming parser
22
- // are pinned separately by the K5b tests in test/eventStream/.)
23
- //
24
- // Size defaults to 2 GiB of pixel fragments; override with
25
- // DCMJS_LONG_TEST_VIDEO_BYTES (bytes, rounded down to whole fragments).
26
-
27
- import fs from "fs";
28
- import os from "os";
29
- import path from "path";
30
- import {
31
- fromPart10,
32
- fromPart10Stream,
33
- NaturalizedListener,
34
- EventStreamListener
35
- } from "@dcmjs-org/parser";
36
- import { writeDicomDir } from "../src/index.js";
37
-
38
- const LONG = !!process.env.DCMJS_LONG_TESTS;
39
- const longTest = LONG ? test : test.skip;
40
-
41
- const MPEG4_TS = "1.2.840.10008.1.2.4.102"; // MPEG-4 AVC/H.264 HiP@4.1
42
- const VIDEO_PHOTOGRAPHIC_SOP_CLASS = "1.2.840.10008.5.1.4.1.1.77.4.1";
43
- const SOP_INSTANCE_UID = "1.2.3.4.200";
44
-
45
- const FRAGMENT_SIZE = 4 * 1024 * 1024; // 4 MiB per on-wire fragment
46
- const DEFAULT_PIXEL_BYTES = 2 * 1024 * 1024 * 1024; // 2 GiB
47
- const PIXEL_BYTES =
48
- Number(process.env.DCMJS_LONG_TEST_VIDEO_BYTES) || DEFAULT_PIXEL_BYTES;
49
- const FRAGMENT_COUNT = Math.max(1, Math.floor(PIXEL_BYTES / FRAGMENT_SIZE));
50
-
51
- // --- Minimal explicit-VR-little-endian byte emission -----------------------
52
- // Just enough to synthesize the video file's envelope; the dicomdir package
53
- // writer is NOT used for this file — the point is to index a file produced
54
- // independently, as burned media would be.
55
-
56
- function asciiEven(s) {
57
- const padded = s.length % 2 ? s + "\0" : s;
58
- const bytes = new Uint8Array(padded.length);
59
- for (let i = 0; i < padded.length; i++) {
60
- bytes[i] = padded.charCodeAt(i);
61
- }
62
- return bytes;
63
- }
64
-
65
- /** Short-form element (UI/CS/US/IS...): 2-byte length. */
66
- function shortElem(group, element, vr, valueBytes) {
67
- const out = new Uint8Array(8 + valueBytes.length);
68
- const dv = new DataView(out.buffer);
69
- dv.setUint16(0, group, true);
70
- dv.setUint16(2, element, true);
71
- out[4] = vr.charCodeAt(0);
72
- out[5] = vr.charCodeAt(1);
73
- dv.setUint16(6, valueBytes.length, true);
74
- out.set(valueBytes, 8);
75
- return out;
76
- }
77
-
78
- /** Long-form element (OB/OW...): 2 reserved bytes + 4-byte length. */
79
- function longElemHeader(group, element, vr, length) {
80
- const out = new Uint8Array(12);
81
- const dv = new DataView(out.buffer);
82
- dv.setUint16(0, group, true);
83
- dv.setUint16(2, element, true);
84
- out[4] = vr.charCodeAt(0);
85
- out[5] = vr.charCodeAt(1);
86
- dv.setUint32(8, length, true);
87
- return out;
88
- }
89
-
90
- function itemHeader(length) {
91
- const out = new Uint8Array(8);
92
- const dv = new DataView(out.buffer);
93
- dv.setUint16(0, 0xfffe, true);
94
- dv.setUint16(2, 0xe000, true);
95
- dv.setUint32(4, length, true);
96
- return out;
97
- }
98
-
99
- function sequenceDelimiter() {
100
- const out = new Uint8Array(8);
101
- const dv = new DataView(out.buffer);
102
- dv.setUint16(0, 0xfffe, true);
103
- dv.setUint16(2, 0xe0dd, true);
104
- dv.setUint32(4, 0, true);
105
- return out;
106
- }
107
-
108
- function us(n) {
109
- const out = new Uint8Array(2);
110
- new DataView(out.buffer).setUint16(0, n, true);
111
- return out;
112
- }
113
-
114
- /**
115
- * Yield the complete Part 10 video file as chunks: preamble + DICM, FMI,
116
- * a small dataset, then FRAGMENT_COUNT encapsulated pixel fragments of
117
- * FRAGMENT_SIZE bytes each (fragment i filled with i & 0xff). Only one
118
- * fragment's bytes exist at a time.
119
- */
120
- function* videoFileChunks() {
121
- const preamble = new Uint8Array(132);
122
- preamble.set(asciiEven("DICM"), 128);
123
- yield preamble;
124
-
125
- const fmiElements = [
126
- longElemHeader(0x0002, 0x0001, "OB", 2),
127
- new Uint8Array([0, 1]),
128
- shortElem(
129
- 0x0002,
130
- 0x0002,
131
- "UI",
132
- asciiEven(VIDEO_PHOTOGRAPHIC_SOP_CLASS)
133
- ),
134
- shortElem(0x0002, 0x0003, "UI", asciiEven(SOP_INSTANCE_UID)),
135
- shortElem(0x0002, 0x0010, "UI", asciiEven(MPEG4_TS))
136
- ];
137
- const fmiLength = fmiElements.reduce((n, b) => n + b.length, 0);
138
- const groupLength = new Uint8Array(4);
139
- new DataView(groupLength.buffer).setUint32(0, fmiLength, true);
140
- yield shortElem(0x0002, 0x0000, "UL", groupLength);
141
- yield* fmiElements;
142
-
143
- yield shortElem(
144
- 0x0008,
145
- 0x0016,
146
- "UI",
147
- asciiEven(VIDEO_PHOTOGRAPHIC_SOP_CLASS)
148
- );
149
- yield shortElem(0x0008, 0x0018, "UI", asciiEven(SOP_INSTANCE_UID));
150
- yield shortElem(0x0008, 0x0060, "CS", asciiEven("XC"));
151
- yield shortElem(0x0028, 0x0008, "IS", asciiEven(String(FRAGMENT_COUNT)));
152
- yield shortElem(0x0028, 0x0010, "US", us(512));
153
- yield shortElem(0x0028, 0x0011, "US", us(512));
154
-
155
- // (7FE0,0010) OB undefined length, empty Basic Offset Table, fragments.
156
- yield longElemHeader(0x7fe0, 0x0010, "OB", 0xffffffff);
157
- yield itemHeader(0);
158
- for (let i = 0; i < FRAGMENT_COUNT; i++) {
159
- yield itemHeader(FRAGMENT_SIZE);
160
- const fragment = new Uint8Array(FRAGMENT_SIZE);
161
- fragment.fill(i & 0xff);
162
- yield fragment;
163
- }
164
- yield sequenceDelimiter();
165
- }
166
-
167
- /** Stream the chunks to disk without accumulating them in memory. */
168
- async function writeVideoFile(filePath) {
169
- const stream = fs.createWriteStream(filePath);
170
- let size = 0;
171
- for (const chunk of videoFileChunks()) {
172
- size += chunk.length;
173
- if (!stream.write(chunk)) {
174
- await new Promise(resolve => stream.once("drain", resolve));
175
- }
176
- }
177
- await new Promise((resolve, reject) => {
178
- stream.end(() => resolve());
179
- stream.on("error", reject);
180
- });
181
- return size;
182
- }
183
-
184
- /**
185
- * A listener that retains nothing: it counts the pixel-data fragment bytes
186
- * and remembers the identity values it sees. Binary events are scoped to
187
- * (7FE0,0010) because FileMetaInformationVersion is also OB and emits its
188
- * own (non-encapsulated) startBinary. If the huge file's pixel data were
189
- * ever materialized instead of streamed, jest's heap would not survive it.
190
- */
191
- class CountingListener extends EventStreamListener {
192
- constructor() {
193
- super();
194
- this.pixelBytes = 0;
195
- this.pixelEncapsulated = null;
196
- this.uiValues = [];
197
- this._inPixelData = false;
198
- }
199
- _baseStartElement(tag) {
200
- this._inPixelData = tag === "7FE00010";
201
- }
202
- _baseStartBinary(info = {}) {
203
- if (this._inPixelData) {
204
- this.pixelEncapsulated = !!info.encapsulated;
205
- }
206
- }
207
- _baseBinaryFragment(buf) {
208
- if (this._inPixelData) {
209
- this.pixelBytes += buf.byteLength ?? buf.length ?? 0;
210
- }
211
- }
212
- _baseValue(value) {
213
- if (typeof value === "string" && /^[0-9.]+$/.test(value)) {
214
- this.uiValues.push(value);
215
- }
216
- }
217
- }
218
-
219
- describe("dicomdir — long media round trip at video scale", () => {
220
- let mediaRoot;
221
-
222
- beforeAll(() => {
223
- if (!LONG) {
224
- return;
225
- }
226
- mediaRoot = fs.mkdtempSync(path.join(os.tmpdir(), "dcmjs-media-"));
227
- fs.mkdirSync(path.join(mediaRoot, "VIDEO"));
228
- });
229
-
230
- afterAll(() => {
231
- if (mediaRoot) {
232
- fs.rmSync(mediaRoot, { recursive: true, force: true });
233
- }
234
- });
235
-
236
- longTest(
237
- "indexes a multi-GiB video file and reads the media back streaming",
238
- async () => {
239
- // --- Burn the media: huge video file + the DICOMDIR indexing it.
240
- const videoPath = path.join(mediaRoot, "VIDEO", "MOV00001");
241
- const videoSize = await writeVideoFile(videoPath);
242
- expect(videoSize).toBeGreaterThan(FRAGMENT_COUNT * FRAGMENT_SIZE);
243
-
244
- const dicomdirBytes = writeDicomDir(
245
- [
246
- {
247
- referencedFileID: ["VIDEO", "MOV00001"],
248
- sopClassUid: VIDEO_PHOTOGRAPHIC_SOP_CLASS,
249
- sopInstanceUid: SOP_INSTANCE_UID,
250
- transferSyntaxUid: MPEG4_TS,
251
- patient: {
252
- PatientID: "998877",
253
- PatientName: "DOE^JANE"
254
- },
255
- study: { StudyInstanceUID: "1.2.3.4" },
256
- series: {
257
- SeriesInstanceUID: "1.2.3.4.5",
258
- Modality: "XC"
259
- },
260
- instance: { InstanceNumber: 1 }
261
- }
262
- ],
263
- { fileSetID: "VIDEO_CD" }
264
- );
265
- fs.writeFileSync(
266
- path.join(mediaRoot, "DICOMDIR"),
267
- new Uint8Array(dicomdirBytes)
268
- );
269
-
270
- // The DICOMDIR indexes the file; it does not contain it. Its size
271
- // must be unrelated to the gigabytes it references.
272
- expect(dicomdirBytes.byteLength).toBeLessThan(4096);
273
-
274
- // --- Read the media back: DICOMDIR first, like a workstation.
275
- const dirListener = new NaturalizedListener();
276
- const dirBuffer = fs.readFileSync(path.join(mediaRoot, "DICOMDIR"));
277
- await fromPart10(
278
- dirBuffer.buffer.slice(
279
- dirBuffer.byteOffset,
280
- dirBuffer.byteOffset + dirBuffer.byteLength
281
- ),
282
- dirListener
283
- );
284
- const records = dirListener.result.DirectoryRecordSequence;
285
- const image = records.find(r => r.DirectoryRecordType === "IMAGE");
286
- expect(image.ReferencedFileID).toEqual(["VIDEO", "MOV00001"]);
287
- expect(image.ReferencedSOPInstanceUIDInFile).toBe(SOP_INSTANCE_UID);
288
- expect(image.ReferencedTransferSyntaxUIDInFile).toBe(MPEG4_TS);
289
-
290
- // --- Resolve the record to the file on disk and stream-parse it.
291
- const resolved = path.join(mediaRoot, ...image.ReferencedFileID);
292
- expect(fs.statSync(resolved).size).toBe(videoSize);
293
-
294
- const counter = new CountingListener();
295
- await fromPart10Stream(fs.createReadStream(resolved), counter);
296
-
297
- expect(counter.pixelEncapsulated).toBe(true);
298
- expect(counter.pixelBytes).toBe(FRAGMENT_COUNT * FRAGMENT_SIZE);
299
- expect(counter.uiValues).toContain(SOP_INSTANCE_UID);
300
- },
301
- 20 * 60 * 1000
302
- );
303
- });
@@ -1,80 +0,0 @@
1
- // packages/dicomdir/test/standalone.test.js
2
- //
3
- // The package exists to build and write DICOMDIRs; what 1.0 additionally
4
- // promises is that it does so without the legacy engines. This file pins
5
- // that second property: it imports nothing from @dcmjs-org/legacy — jest
6
- // gives each test file its own module registry, so no eager DicomMessage
7
- // is ever wired into core's late-binding seam here. Writing a DICOMDIR serializes a
8
- // DirectoryRecordSequence, which exercises core's sequence writer with no
9
- // injected engine; before SequenceOfItems.writeBytes called back into
10
- // writeDataSet directly, this write threw.
11
-
12
- import { writeDicomDir } from "../src/index.js";
13
-
14
- const MR_SOP_CLASS = "1.2.840.10008.5.1.4.1.1.4";
15
- const ELE = "1.2.840.10008.1.2.1";
16
-
17
- function countItemTags(bytes) {
18
- // FFFE,E000 little-endian with the undefined-length marker the item
19
- // headers carry — anchoring on all eight bytes keeps value bytes from
20
- // matching by accident.
21
- let count = 0;
22
- for (let i = 0; i + 8 <= bytes.length; i++) {
23
- if (
24
- bytes[i] === 0xfe &&
25
- bytes[i + 1] === 0xff &&
26
- bytes[i + 2] === 0x00 &&
27
- bytes[i + 3] === 0xe0 &&
28
- bytes[i + 4] === 0xff &&
29
- bytes[i + 5] === 0xff &&
30
- bytes[i + 6] === 0xff &&
31
- bytes[i + 7] === 0xff
32
- ) {
33
- count++;
34
- }
35
- }
36
- return count;
37
- }
38
-
39
- test("writes a complete DICOMDIR with no eager engine loaded", () => {
40
- const arrayBuffer = writeDicomDir(
41
- [
42
- {
43
- referencedFileID: ["DICOM", "IM000001"],
44
- sopClassUid: MR_SOP_CLASS,
45
- sopInstanceUid: "1.2.3.4.100",
46
- transferSyntaxUid: ELE,
47
- patient: { PatientID: "998877", PatientName: "DOE^JANE" },
48
- study: { StudyInstanceUID: "1.2.3.4" },
49
- series: { SeriesInstanceUID: "1.2.3.4.5", Modality: "MR" },
50
- instance: { InstanceNumber: 1 }
51
- }
52
- ],
53
- { fileSetID: "MY_CD", fileSetUID: "2.25.99" }
54
- );
55
- const bytes = new Uint8Array(arrayBuffer);
56
-
57
- // Part 10 magic after the 128-byte preamble.
58
- expect(String.fromCharCode(...bytes.slice(128, 132))).toBe("DICM");
59
- // One entry yields PATIENT/STUDY/SERIES/IMAGE — four record items.
60
- expect(countItemTags(bytes)).toBe(4);
61
- // Deterministic under a fixed fileSetUID, same as the main suite.
62
- const again = new Uint8Array(
63
- writeDicomDir(
64
- [
65
- {
66
- referencedFileID: ["DICOM", "IM000001"],
67
- sopClassUid: MR_SOP_CLASS,
68
- sopInstanceUid: "1.2.3.4.100",
69
- transferSyntaxUid: ELE,
70
- patient: { PatientID: "998877", PatientName: "DOE^JANE" },
71
- study: { StudyInstanceUID: "1.2.3.4" },
72
- series: { SeriesInstanceUID: "1.2.3.4.5", Modality: "MR" },
73
- instance: { InstanceNumber: 1 }
74
- }
75
- ],
76
- { fileSetID: "MY_CD", fileSetUID: "2.25.99" }
77
- )
78
- );
79
- expect(again).toEqual(bytes);
80
- });