@dcmjs-org/video 1.0.0-beta.3 → 1.0.0-beta.5

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/dist/index.mjs ADDED
@@ -0,0 +1,799 @@
1
+ import { h264TransferSyntaxUID } from '@dcmjs-org/imaging';
2
+ import { combineBases, defaultInstanceBase, createInstance, isVideoTransferSyntax, EXPLICIT_LITTLE_ENDIAN, DicomMetaDictionary } from '@dcmjs-org/core';
3
+ import { fromDataSet, EVENT_STREAM_VOCABULARY } from '@dcmjs-org/parser';
4
+
5
+ // src/image/mp4Info.js
6
+ //
7
+ // Minimal MP4 (ISO BMFF) header inspection: walk the box structure to recover
8
+ // the geometry and timing DICOM needs (Rows/Columns/NumberOfFrames/frame rate)
9
+ // and identify the matching video transfer syntax — WITHOUT decoding any
10
+ // pixels. H.264 in MP4 is a legal DICOM transfer syntax family (Supplement
11
+ // 225), so the MP4 stream can be carried as encapsulated PixelData verbatim;
12
+ // only the moov metadata must be understood.
13
+ //
14
+ // The moov box normally sits AFTER the (potentially enormous) mdat box, so the
15
+ // parser works against a random-access reader — { size, read(offset, length) }
16
+ // — and never buffers more than the moov box itself (a few MB even for a
17
+ // 20 GB file). Plain Uint8Array/ArrayBuffer input is wrapped in an in-memory
18
+ // reader so both call styles share one code path.
19
+
20
+
21
+ /** Wrap in-memory bytes in the random-access reader contract. */
22
+ function memoryReader$1(input) {
23
+ const bytes =
24
+ input instanceof ArrayBuffer
25
+ ? new Uint8Array(input)
26
+ : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
27
+ return {
28
+ size: bytes.byteLength,
29
+ read: (offset, length) =>
30
+ Promise.resolve(bytes.subarray(offset, offset + length))
31
+ };
32
+ }
33
+
34
+ function isReader(input) {
35
+ return (
36
+ input &&
37
+ typeof input === "object" &&
38
+ typeof input.read === "function" &&
39
+ typeof input.size === "number"
40
+ );
41
+ }
42
+
43
+ /** Big-endian readers over a Uint8Array (MP4 box fields are big-endian). */
44
+ function u16(bytes, offset) {
45
+ return (bytes[offset] << 8) | bytes[offset + 1];
46
+ }
47
+ function u32(bytes, offset) {
48
+ return (
49
+ (bytes[offset] * 0x1000000 +
50
+ (bytes[offset + 1] << 16) +
51
+ (bytes[offset + 2] << 8) +
52
+ bytes[offset + 3]) >>>
53
+ 0
54
+ );
55
+ }
56
+ function u64(bytes, offset) {
57
+ // Box sizes and v1 durations: safe as a Number (files < 2^53 bytes).
58
+ return u32(bytes, offset) * 0x100000000 + u32(bytes, offset + 4);
59
+ }
60
+ function fourCC(bytes, offset) {
61
+ return String.fromCharCode(
62
+ bytes[offset],
63
+ bytes[offset + 1],
64
+ bytes[offset + 2],
65
+ bytes[offset + 3]
66
+ );
67
+ }
68
+
69
+ /**
70
+ * Iterate the child boxes of a byte range inside an in-memory buffer.
71
+ * Yields { type, offset, size, headerLength } with offset relative to `bytes`.
72
+ */
73
+ function* boxes(bytes, start, end) {
74
+ let offset = start;
75
+ while (offset + 8 <= end) {
76
+ let size = u32(bytes, offset);
77
+ const type = fourCC(bytes, offset + 4);
78
+ let headerLength = 8;
79
+ if (size === 1) {
80
+ size = u64(bytes, offset + 8);
81
+ headerLength = 16;
82
+ } else if (size === 0) {
83
+ size = end - offset;
84
+ }
85
+ if (size < headerLength || offset + size > end) {
86
+ return; // malformed child; stop rather than walk garbage
87
+ }
88
+ yield { type, offset, size, headerLength };
89
+ offset += size;
90
+ }
91
+ }
92
+
93
+ function findBox(bytes, start, end, type) {
94
+ for (const box of boxes(bytes, start, end)) {
95
+ if (box.type === type) {
96
+ return box;
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+
102
+ /**
103
+ * Inspect an MP4 file and return what DICOM video encapsulation needs.
104
+ *
105
+ * @param {Uint8Array|ArrayBuffer|{size: number, read: (offset: number,
106
+ * length: number) => Promise<Uint8Array>}} input - the MP4 bytes, or a
107
+ * random-access reader over them (the streaming path for large files)
108
+ * @returns {Promise<{ rows, columns, numberOfFrames, frameRate, cineRate,
109
+ * frameTime, codec, profileIdc, levelIdc, transferSyntaxUID: string|null,
110
+ * mp4ByteLength }>}
111
+ * @throws on non-MP4 input or when no video track is present
112
+ */
113
+ async function parseMp4Info(input) {
114
+ const reader = isReader(input) ? input : memoryReader$1(input);
115
+
116
+ // Top-level scan: a handful of 16-byte header reads regardless of file
117
+ // size. The first box must be ftyp — that is also the validity check.
118
+ let offset = 0;
119
+ let moovLocation = null;
120
+ let first = true;
121
+ while (offset + 8 <= reader.size) {
122
+ const head = await reader.read(
123
+ offset,
124
+ Math.min(16, reader.size - offset)
125
+ );
126
+ let size = u32(head, 0);
127
+ const type = fourCC(head, 4);
128
+ if (size === 1) {
129
+ if (head.byteLength < 16) {
130
+ break;
131
+ }
132
+ size = u64(head, 8);
133
+ } else if (size === 0) {
134
+ size = reader.size - offset;
135
+ }
136
+ if (first && type !== "ftyp") {
137
+ throw new Error(
138
+ "parseMp4Info: input is not an MP4 file (missing ftyp box)"
139
+ );
140
+ }
141
+ first = false;
142
+ if (size < 8 || offset + size > reader.size) {
143
+ throw new Error(
144
+ `parseMp4Info: malformed box '${type}' at offset ${offset}`
145
+ );
146
+ }
147
+ if (type === "moov") {
148
+ moovLocation = { offset, size };
149
+ break;
150
+ }
151
+ offset += size;
152
+ }
153
+ if (!moovLocation) {
154
+ throw new Error(
155
+ "parseMp4Info: no moov box found — truncated or still-recording MP4"
156
+ );
157
+ }
158
+
159
+ // The moov box is metadata only (a few MB at most); buffer it whole.
160
+ const moov = await reader.read(moovLocation.offset, moovLocation.size);
161
+
162
+ // First trak whose handler is "vide".
163
+ let video = null;
164
+ for (const trak of boxes(moov, 8, moov.byteLength)) {
165
+ if (trak.type !== "trak") {
166
+ continue;
167
+ }
168
+ const trakEnd = trak.offset + trak.size;
169
+ const mdia = findBox(moov, trak.offset + 8, trakEnd, "mdia");
170
+ if (!mdia) {
171
+ continue;
172
+ }
173
+ const mdiaEnd = mdia.offset + mdia.size;
174
+ const hdlr = findBox(moov, mdia.offset + 8, mdiaEnd, "hdlr");
175
+ // hdlr: 8 header + 4 version/flags + 4 pre_defined, then handler_type
176
+ if (!hdlr || fourCC(moov, hdlr.offset + 16) !== "vide") {
177
+ continue;
178
+ }
179
+ video = { mdia, mdiaEnd };
180
+ break;
181
+ }
182
+ if (!video) {
183
+ throw new Error(
184
+ "parseMp4Info: no video track found in the MP4 (audio-only file?)"
185
+ );
186
+ }
187
+
188
+ const { mdia, mdiaEnd } = video;
189
+
190
+ // mdhd → timescale/duration (v0: 32-bit fields, v1: 64-bit times).
191
+ const mdhd = findBox(moov, mdia.offset + 8, mdiaEnd, "mdhd");
192
+ if (!mdhd) {
193
+ throw new Error("parseMp4Info: video track has no mdhd box");
194
+ }
195
+ const mdhdVersion = moov[mdhd.offset + 8];
196
+ let timescale, duration;
197
+ if (mdhdVersion === 1) {
198
+ timescale = u32(moov, mdhd.offset + 12 + 16);
199
+ duration = u64(moov, mdhd.offset + 12 + 20);
200
+ } else {
201
+ timescale = u32(moov, mdhd.offset + 12 + 8);
202
+ duration = u32(moov, mdhd.offset + 12 + 12);
203
+ }
204
+
205
+ const minf = findBox(moov, mdia.offset + 8, mdiaEnd, "minf");
206
+ const stbl =
207
+ minf && findBox(moov, minf.offset + 8, minf.offset + minf.size, "stbl");
208
+ const stsd =
209
+ stbl && findBox(moov, stbl.offset + 8, stbl.offset + stbl.size, "stsd");
210
+ if (!stsd) {
211
+ throw new Error("parseMp4Info: video track has no sample description");
212
+ }
213
+ const stblEnd = stbl.offset + stbl.size;
214
+
215
+ // stsd: 8 header + 4 version/flags + 4 entry_count, then sample entries.
216
+ const entry = stsd.offset + 16;
217
+ const entrySize = u32(moov, entry);
218
+ const codec = fourCC(moov, entry + 4);
219
+ // VisualSampleEntry: 8 box header + 6 reserved + 2 data_reference_index
220
+ // + 16 pre_defined/reserved → width at +32, height at +34 (validated
221
+ // against real encoder output, not just the spec).
222
+ const columns = u16(moov, entry + 32);
223
+ const rows = u16(moov, entry + 34);
224
+
225
+ // avcC → AVCDecoderConfigurationRecord: profile_idc and level_idc are
226
+ // bytes 1 and 3 of the record. The fixed part of a VisualSampleEntry is
227
+ // 86 bytes; codec-specific child boxes follow.
228
+ let profileIdc = null;
229
+ let levelIdc = null;
230
+ if (codec === "avc1" || codec === "avc3") {
231
+ const avcC = findBox(moov, entry + 86, entry + entrySize, "avcC");
232
+ if (avcC) {
233
+ profileIdc = moov[avcC.offset + 9];
234
+ levelIdc = moov[avcC.offset + 11];
235
+ }
236
+ }
237
+
238
+ // Frame count: stsz sample_count (authoritative), stts sum as fallback.
239
+ let numberOfFrames = 0;
240
+ const stsz = findBox(moov, stbl.offset + 8, stblEnd, "stsz");
241
+ if (stsz) {
242
+ numberOfFrames = u32(moov, stsz.offset + 16);
243
+ }
244
+ const stts = findBox(moov, stbl.offset + 8, stblEnd, "stts");
245
+ if (!numberOfFrames && stts) {
246
+ const entryCount = u32(moov, stts.offset + 12);
247
+ // Each stts entry is 8 bytes after the 16-byte fixed part. A raw
248
+ // entry_count beyond the box's own size is malformed: walking it
249
+ // would read zero-coerced garbage past the box and block the thread
250
+ // for seconds at large counts (review finding 15).
251
+ if (16 + entryCount * 8 > stts.size) {
252
+ throw new Error(
253
+ `parseMp4Info: malformed stts box — entry_count ${entryCount} ` +
254
+ `does not fit in a ${stts.size}-byte box`
255
+ );
256
+ }
257
+ for (let i = 0; i < entryCount; i++) {
258
+ numberOfFrames += u32(moov, stts.offset + 16 + i * 8);
259
+ }
260
+ }
261
+
262
+ // Frame rate: exact from a single-entry stts (constant frame rate);
263
+ // otherwise the average over the track (variable frame rate).
264
+ let frameRate = null;
265
+ if (stts && u32(moov, stts.offset + 12) === 1) {
266
+ const sampleDelta = u32(moov, stts.offset + 20);
267
+ if (sampleDelta > 0) {
268
+ frameRate = timescale / sampleDelta;
269
+ }
270
+ }
271
+ if (!frameRate && duration > 0 && numberOfFrames > 0) {
272
+ frameRate = (numberOfFrames * timescale) / duration;
273
+ }
274
+ if (!frameRate) {
275
+ throw new Error(
276
+ "parseMp4Info: could not determine the frame rate from the video track"
277
+ );
278
+ }
279
+
280
+ return {
281
+ rows,
282
+ columns,
283
+ numberOfFrames,
284
+ frameRate,
285
+ cineRate: Math.round(frameRate),
286
+ // FrameTime (0018,1063) is DS: milliseconds per frame as a string.
287
+ frameTime: (1000 / frameRate).toFixed(6),
288
+ codec,
289
+ profileIdc,
290
+ levelIdc,
291
+ transferSyntaxUID:
292
+ profileIdc !== null
293
+ ? h264TransferSyntaxUID(profileIdc, levelIdc)
294
+ : null,
295
+ mp4ByteLength: reader.size
296
+ };
297
+ }
298
+
299
+ // src/encapsulated/encapsulatedVideo.js
300
+ //
301
+ // Video encapsulation (Supplement 225): an MP4's H.264 stream travels inside
302
+ // a Video Photographic Image instance VERBATIM — the pixel data fragments are
303
+ // consecutive byte ranges of the one MP4 stream, so extraction is
304
+ // concatenation and the round trip is byte-identical. Two directions,
305
+ // mirroring encapsulatedPdf.js:
306
+ //
307
+ // buildVideoDataset(mp4Info, options) — dataset shell (no PixelData), used
308
+ // by both the buffered and the streaming encapsulation paths.
309
+ // encapsulateVideo(mp4Bytes, options) — MP4 in (buffered): dataset plus
310
+ // PixelData as fragment-sized ArrayBuffer slices.
311
+ // extractEncapsulatedVideo(dataset) — MP4 out: recover the stream from a
312
+ // naturalized video instance, truncated to the declared total length.
313
+ //
314
+ // The (7FE0,0003) Encapsulated Pixel Data Value Total Length element (VR UV,
315
+ // uint64) records the exact stream length so the required trailing pad byte
316
+ // on an odd-length final fragment can be dropped on extraction.
317
+
318
+
319
+ const VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID = "1.2.840.10008.5.1.4.1.1.77.1.4.1";
320
+
321
+ // 256 MiB: small enough that one in-flight fragment stays comfortably in
322
+ // memory, large enough that a 21.8 GB stream is only ~82 fragments.
323
+ const DEFAULT_FRAGMENT_BYTES = 256 * 1024 * 1024;
324
+
325
+ /**
326
+ * Validate/default the encapsulation fragment size. Fragment item lengths are
327
+ * 32-bit and must be even (PS3.5 §A.4), so the size must be an even integer
328
+ * below 2^32-2.
329
+ *
330
+ * @param {number} [fragmentBytes]
331
+ * @returns {number}
332
+ */
333
+ function normalizeFragmentBytes(fragmentBytes) {
334
+ if (fragmentBytes === undefined || fragmentBytes === null) {
335
+ return DEFAULT_FRAGMENT_BYTES;
336
+ }
337
+ if (
338
+ !Number.isInteger(fragmentBytes) ||
339
+ fragmentBytes < 2 ||
340
+ fragmentBytes % 2 !== 0 ||
341
+ fragmentBytes >= 0xfffffffe
342
+ ) {
343
+ throw new Error(
344
+ `fragmentBytes must be an even integer between 2 and 2^32-2 ` +
345
+ `(fragment item lengths are even 32-bit values); got ${fragmentBytes}`
346
+ );
347
+ }
348
+ return fragmentBytes;
349
+ }
350
+
351
+ /** The corrective error for codecs no DICOM video transfer syntax carries. */
352
+ function unsupportedCodecError(info) {
353
+ const profile =
354
+ info.profileIdc !== null
355
+ ? ` profile ${info.profileIdc} level ${(info.levelIdc / 10).toFixed(
356
+ 1
357
+ )}`
358
+ : "";
359
+ return new Error(
360
+ `unsupported video codec '${info.codec}'${profile} — DICOM video ` +
361
+ "encapsulation supports H.264 Baseline/Main/High up to Level 4.2. " +
362
+ "Transcode first, e.g.: ffmpeg -i in.mp4 -c:v libx264 " +
363
+ "-profile:v high -level 4.2 -c:a copy out.mp4"
364
+ );
365
+ }
366
+
367
+ /**
368
+ * The Video Photographic Image attributes that do not depend on the stream:
369
+ * XC modality, and the Image Pixel values that every MPEG-4 AVC transfer
370
+ * syntax mandates (PS3.5 §8.2.6); the stream carries the real subsampling.
371
+ */
372
+ const videoPhotographicBase = {
373
+ SOPClassUID: VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
374
+ Modality: "XC",
375
+ SamplesPerPixel: 3,
376
+ PhotometricInterpretation: "YBR_PARTIAL_420",
377
+ PlanarConfiguration: 0,
378
+ BitsAllocated: 8,
379
+ BitsStored: 8,
380
+ HighBit: 7,
381
+ PixelRepresentation: 0,
382
+ LossyImageCompression: "01"
383
+ };
384
+
385
+ /**
386
+ * The default base of `buildVideoDataset`: core instance defaults and the
387
+ * Video Photographic Image block. It has no `predecessorBase`, so
388
+ * `predecessor: true` has no effect; use
389
+ * `combineBases(videoBase, predecessorBase)` for a predecessor
390
+ * (CORE-USR-9). Use `.items` to build a variant.
391
+ */
392
+ const videoBase = combineBases(defaultInstanceBase, videoPhotographicBase);
393
+
394
+ /**
395
+ * Build the naturalized dataset shell for a Video Photographic Image
396
+ * instance — everything except PixelData, which the caller supplies either
397
+ * buffered (encapsulateVideo) or as a fragment event stream
398
+ * (createVideoEventSource).
399
+ *
400
+ * The dataset comes from {@link createInstance} with `videoBase`; the
401
+ * options follow CORE-USR-1 (`packages/core/README.md`), and the video rules
402
+ * are VID-USR-n in `packages/video/README.md`. The options object holds the
403
+ * controls; the DICOM attributes go in `options.overrides` (a naturalized
404
+ * DICOM provider with the forms of `baseDicom`). An extra option key has no
405
+ * effect (CORE-USR-7). With `dataLevel: "series"`, `instance` is the sample
406
+ * instance in the series (CORE-USR-5).
407
+ *
408
+ * The stream attributes are set last, and replace an override from each
409
+ * form of `overrides` (VID-USR-2): CineRate and FrameTime from the measured
410
+ * frame rate, NumberOfFrames, Rows, Columns, `_meta.TransferSyntaxUID`, and
411
+ * the (7FE0,0003) total length as a BigInt (VR UV is a uint64). A field
412
+ * that `mp4Info` does not give writes no attribute. The element list
413
+ * mirrors the Supplement 225 fixture.
414
+ *
415
+ * @example
416
+ * buildVideoDataset(mp4Info, {
417
+ * instance,
418
+ * overrides: { SeriesDescription: "Endoscopy" }
419
+ * });
420
+ *
421
+ * @param {Object} mp4Info - parseMp4Info result
422
+ * @param {Object} [options] - the createInstance options (`baseDicom`
423
+ * defaults to `videoBase`; `overrides` holds the DICOM attributes;
424
+ * createInstance calls `postProcess` before the builder sets the stream
425
+ * attributes), plus the control option of the callers (`fragmentBytes`),
426
+ * which is ignored here
427
+ * @returns {Object} naturalized dataset with _meta/_vrMap, no PixelData
428
+ */
429
+ function buildVideoDataset(mp4Info, options = {}) {
430
+ if (!mp4Info.transferSyntaxUID) {
431
+ throw unsupportedCodecError(mp4Info);
432
+ }
433
+
434
+ // fragmentBytes is a control key of the callers (CORE-IMP-9).
435
+ const { baseDicom = videoBase, fragmentBytes, ...rest } = options;
436
+ const dataset = createInstance({ baseDicom, ...rest });
437
+
438
+ const streamAttributes = {
439
+ CineRate: mp4Info.cineRate,
440
+ FrameTime: mp4Info.frameTime,
441
+ NumberOfFrames: mp4Info.numberOfFrames,
442
+ Rows: mp4Info.rows,
443
+ Columns: mp4Info.columns
444
+ };
445
+ for (const [keyword, value] of Object.entries(streamAttributes)) {
446
+ if (value !== undefined) {
447
+ dataset[keyword] = value;
448
+ }
449
+ }
450
+ // Exact stream length, without the pad byte of an odd-length final
451
+ // fragment (Sup 225).
452
+ dataset.EncapsulatedPixelDataValueTotalLength = BigInt(
453
+ mp4Info.mp4ByteLength
454
+ );
455
+ // A copy that keeps the other _meta keys (CORE-USR-13).
456
+ dataset._meta = {
457
+ ...(dataset._meta || {}),
458
+ TransferSyntaxUID: { Value: [mp4Info.transferSyntaxUID] }
459
+ };
460
+ dataset._vrMap = { ...(dataset._vrMap || {}), PixelData: "OB" };
461
+ return dataset;
462
+ }
463
+
464
+ /**
465
+ * Wrap MP4 bytes into a naturalized video instance, buffered: PixelData is an
466
+ * array of fragment-sized ArrayBuffer slices ready for datasetToDict /
467
+ * datasetToBuffer. For files too large to buffer, use
468
+ * createVideoEventSource instead.
469
+ *
470
+ * @param {ArrayBuffer|Uint8Array} mp4Bytes
471
+ * @param {Object} [options] - the buildVideoDataset options (the DICOM
472
+ * attributes go in `overrides`), plus `fragmentBytes`
473
+ * @returns {Promise<Object>} naturalized dataset
474
+ */
475
+ async function encapsulateVideo(mp4Bytes, options = {}) {
476
+ const bytes =
477
+ mp4Bytes instanceof ArrayBuffer
478
+ ? new Uint8Array(mp4Bytes)
479
+ : new Uint8Array(
480
+ mp4Bytes.buffer,
481
+ mp4Bytes.byteOffset,
482
+ mp4Bytes.byteLength
483
+ );
484
+ const info = await parseMp4Info(bytes);
485
+ const dataset = buildVideoDataset(info, options);
486
+ const fragmentBytes = normalizeFragmentBytes(options.fragmentBytes);
487
+
488
+ const fragments = [];
489
+ for (let offset = 0; offset < bytes.byteLength; offset += fragmentBytes) {
490
+ const end = Math.min(offset + fragmentBytes, bytes.byteLength);
491
+ // slice() so each fragment is an exact, unshared ArrayBuffer.
492
+ fragments.push(
493
+ bytes.buffer.slice(
494
+ bytes.byteOffset + offset,
495
+ bytes.byteOffset + end
496
+ )
497
+ );
498
+ }
499
+ dataset.PixelData = fragments;
500
+ return dataset;
501
+ }
502
+
503
+ /** Unwrap one naturalized binary payload to fragments of Uint8Array. */
504
+ function toFragmentList(payload) {
505
+ if (payload === undefined || payload === null) {
506
+ return [];
507
+ }
508
+ // A naturalized binary value is a list of fragments; DICOM JSON input
509
+ // can also give { InlineBinary } (a buffer, a view, base64, or a list).
510
+ if (
511
+ typeof payload === "object" &&
512
+ !(payload instanceof ArrayBuffer) &&
513
+ !ArrayBuffer.isView(payload) &&
514
+ !Array.isArray(payload) &&
515
+ payload.InlineBinary !== undefined
516
+ ) {
517
+ payload = payload.InlineBinary;
518
+ }
519
+ const list = Array.isArray(payload) ? payload : [payload];
520
+ return list.map(fragment => {
521
+ if (typeof fragment === "string") {
522
+ const binary = atob(fragment);
523
+ const decoded = new Uint8Array(binary.length);
524
+ for (let i = 0; i < binary.length; i++) {
525
+ decoded[i] = binary.charCodeAt(i);
526
+ }
527
+ return decoded;
528
+ }
529
+ if (
530
+ fragment &&
531
+ typeof fragment === "object" &&
532
+ !(fragment instanceof ArrayBuffer) &&
533
+ !ArrayBuffer.isView(fragment) &&
534
+ fragment.InlineBinary !== undefined
535
+ ) {
536
+ return toFragmentList(fragment)[0];
537
+ }
538
+ return ArrayBuffer.isView(fragment)
539
+ ? new Uint8Array(
540
+ fragment.buffer,
541
+ fragment.byteOffset,
542
+ fragment.byteLength
543
+ )
544
+ : new Uint8Array(fragment);
545
+ });
546
+ }
547
+
548
+ /** The meta transfer syntax of a naturalized dataset, tolerant of shape. */
549
+ function metaTransferSyntax(dataset) {
550
+ const meta = dataset._meta;
551
+ if (!meta) {
552
+ return undefined;
553
+ }
554
+ const entry = meta.TransferSyntaxUID || meta["00020010"];
555
+ if (!entry) {
556
+ return undefined;
557
+ }
558
+ if (typeof entry === "string") {
559
+ return entry;
560
+ }
561
+ return Array.isArray(entry.Value) ? entry.Value[0] : entry.Value;
562
+ }
563
+
564
+ /**
565
+ * Recover the verbatim video stream from a naturalized video instance.
566
+ *
567
+ * Fragments are concatenated and the result truncated to the declared
568
+ * (7FE0,0003) total length, which drops the pad byte a Part 10 writer adds
569
+ * to an odd-length final fragment. When the element is absent (older
570
+ * producers), nothing is trimmed and `declaredLength` is null so the caller
571
+ * can decide how loudly to warn. A dataset that is not a video throws an
572
+ * error (VID-USR-6).
573
+ *
574
+ * @param {Object} dataset - naturalized video instance
575
+ * @returns {{ bytes: Uint8Array, transferSyntaxUID: string|undefined,
576
+ * declaredLength: number|null }}
577
+ */
578
+ function extractEncapsulatedVideo(dataset) {
579
+ const transferSyntaxUID = metaTransferSyntax(dataset);
580
+ const isVideo =
581
+ dataset.SOPClassUID === VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID ||
582
+ isVideoTransferSyntax(transferSyntaxUID);
583
+ if (!isVideo || dataset.PixelData === undefined) {
584
+ throw new Error(
585
+ "extractEncapsulatedVideo: dataset is not an encapsulated video " +
586
+ "instance (expected SOP Class " +
587
+ VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID +
588
+ " or a video transfer syntax, with PixelData). " +
589
+ (transferSyntaxUID
590
+ ? `Found transfer syntax ${transferSyntaxUID}. `
591
+ : "") +
592
+ "For an Encapsulated PDF use extractEncapsulatedPdf; for " +
593
+ "pixel images read the dataset with NaturalizedListener."
594
+ );
595
+ }
596
+
597
+ const fragments = toFragmentList(dataset.PixelData);
598
+ const total = fragments.reduce((n, f) => n + f.byteLength, 0);
599
+ const out = new Uint8Array(total);
600
+ let offset = 0;
601
+ for (const fragment of fragments) {
602
+ out.set(fragment, offset);
603
+ offset += fragment.byteLength;
604
+ }
605
+
606
+ const declared = dataset.EncapsulatedPixelDataValueTotalLength;
607
+ const declaredLength =
608
+ declared === undefined || declared === null
609
+ ? null
610
+ : Number(Array.isArray(declared) ? declared[0] : declared);
611
+
612
+ const bytes =
613
+ declaredLength !== null && declaredLength <= out.byteLength
614
+ ? out.subarray(0, declaredLength)
615
+ : out;
616
+
617
+ return { bytes, transferSyntaxUID, declaredLength };
618
+ }
619
+
620
+ // src/eventStream/fromVideo.js
621
+ //
622
+ // MP4 → event stream (Supplement 225 video encapsulation). The dataset shell
623
+ // is built eagerly (stable UIDs across re-runs); running the
624
+ // stream replays the shell, then emits the MP4 as encapsulated PixelData
625
+ // fragments read one at a time from a random-access reader — so a 21.8 GB
626
+ // file streams with at most one fragment in memory, and the same code path
627
+ // serves in-memory bytes.
628
+ //
629
+ // The natural sink is StreamingPart10Writer, which turns each binaryFragment
630
+ // into one fragment item (undefined-length OB, empty Basic Offset Table,
631
+ // even-padded items, sequence delimiter). Backpressure is honored between
632
+ // fragments via listener.awaitDrain().
633
+
634
+
635
+ const PIXEL_DATA_TAG = "7FE00010";
636
+
637
+ const IMPLEMENTATION_CLASS_UID =
638
+ "2.25.80302813137786398554742050926734630921603366648225212145404";
639
+
640
+ /**
641
+ * Denaturalize a dataset into the plain `{ meta, dict }` shape fromDataSet
642
+ * consumes: the file meta group is minted from the dataset identity exactly
643
+ * the way legacy's datasetToDict does it, minus the DicomDict wrapper —
644
+ * nothing here writes bytes, so no writer object is needed. The meta group
645
+ * is a local object: the `_meta` of `dataset` does not change
646
+ * (CORE-USR-13, CORE-IMP-7).
647
+ *
648
+ * Each other `_meta` key (its `Value[0]`) goes into the file meta group
649
+ * (VID-USR-2). The defaults of `FileMetaInformationVersion`,
650
+ * `ImplementationClassUID`, and `ImplementationVersionName` apply only when
651
+ * `_meta` has no value. `MediaStorageSOPClassUID`,
652
+ * `MediaStorageSOPInstanceUID`, and `TransferSyntaxUID` always come from the
653
+ * dataset.
654
+ */
655
+ function datasetToMetaDict(dataset) {
656
+ const fileMetaInformationVersionArray = new Uint8Array(2);
657
+ fileMetaInformationVersionArray[1] = 1;
658
+
659
+ const TransferSyntaxUID =
660
+ dataset._meta?.TransferSyntaxUID?.Value?.[0] || EXPLICIT_LITTLE_ENDIAN;
661
+
662
+ const callerMeta = {};
663
+ for (const [keyword, entry] of Object.entries(dataset._meta || {})) {
664
+ const value = Array.isArray(entry?.Value) ? entry.Value[0] : entry;
665
+ if (value !== undefined && value !== null && value !== "") {
666
+ callerMeta[keyword] = value;
667
+ }
668
+ }
669
+
670
+ const meta = {
671
+ FileMetaInformationVersion: fileMetaInformationVersionArray.buffer,
672
+ ImplementationClassUID: IMPLEMENTATION_CLASS_UID,
673
+ ImplementationVersionName: "dcmjs-0.0",
674
+ ...callerMeta,
675
+ MediaStorageSOPClassUID: dataset.SOPClassUID,
676
+ MediaStorageSOPInstanceUID: dataset.SOPInstanceUID,
677
+ TransferSyntaxUID
678
+ };
679
+
680
+ return {
681
+ meta: DicomMetaDictionary.denaturalizeDataset(meta),
682
+ dict: DicomMetaDictionary.denaturalizeDataset(dataset)
683
+ };
684
+ }
685
+
686
+ /** Wrap in-memory bytes in the random-access reader contract. */
687
+ function memoryReader(input) {
688
+ const bytes =
689
+ input instanceof ArrayBuffer
690
+ ? new Uint8Array(input)
691
+ : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
692
+ return {
693
+ size: bytes.byteLength,
694
+ read: (offset, length) =>
695
+ Promise.resolve(bytes.subarray(offset, offset + length))
696
+ };
697
+ }
698
+
699
+ /**
700
+ * Fragments must reach buffered sinks as EXACT buffers: the collector →
701
+ * DicomDict.write path resolves a typed-array view to its whole backing
702
+ * ArrayBuffer (byteOffset is lost), so a subarray view would serialize the
703
+ * wrong bytes. Views that already span their full backing buffer (the
704
+ * fd-read case in streaming CLIs) pass through copy-free.
705
+ */
706
+ function exactFragment(fragment) {
707
+ if (
708
+ ArrayBuffer.isView(fragment) &&
709
+ (fragment.byteOffset !== 0 ||
710
+ fragment.byteLength !== fragment.buffer.byteLength)
711
+ ) {
712
+ return fragment.buffer.slice(
713
+ fragment.byteOffset,
714
+ fragment.byteOffset + fragment.byteLength
715
+ );
716
+ }
717
+ return fragment;
718
+ }
719
+
720
+ /**
721
+ * A forwarding view of `listener` that swallows endDataSet, so the dataset
722
+ * shell can be replayed first and the stream closed only after the pixel
723
+ * data fragments. awaitDrain/setDrain forward too — backpressure must
724
+ * survive the wrapper or the shell replay would run ungated.
725
+ */
726
+ function withoutEndDataSet(listener) {
727
+ const wrapper = {};
728
+ for (const method of EVENT_STREAM_VOCABULARY) {
729
+ wrapper[method] = (...args) => listener[method](...args);
730
+ }
731
+ wrapper.endDataSet = () => {};
732
+ wrapper.awaitDrain = () => listener.awaitDrain();
733
+ wrapper.setDrain = fn => listener.setDrain(fn);
734
+ return wrapper;
735
+ }
736
+
737
+ /**
738
+ * Rebuild a dict with its tags in ascending order. fromDataSet emits entries
739
+ * in key order and StreamingPart10Writer writes them as they arrive, so key
740
+ * order IS file order; naturalized→denaturalized dicts follow property
741
+ * insertion order, which need not be tag order. Fixed-width uppercase hex
742
+ * sorts lexicographically === numerically.
743
+ */
744
+ function sortDict(dict) {
745
+ const sorted = {};
746
+ for (const tag of Object.keys(dict).sort()) {
747
+ sorted[tag] = dict[tag];
748
+ }
749
+ return sorted;
750
+ }
751
+
752
+ /**
753
+ * Create the video event source. The function is async, because
754
+ * `parseMp4Info` reads the MP4 header through the reader. The returned
755
+ * `dataset` is the result of `buildVideoDataset`, without `PixelData`;
756
+ * `run(listener)` emits the dataset, then the MP4 as `PixelData` fragments.
757
+ *
758
+ * @param {Uint8Array|ArrayBuffer|{size, read(offset, length)}} input - MP4
759
+ * bytes or a random-access reader over them
760
+ * @param {Object} [options] - the buildVideoDataset options (the DICOM
761
+ * attributes go in `overrides`), plus `fragmentBytes`
762
+ * @returns {Promise<{ run: (listener) => Promise<void>, info: Object,
763
+ * dataset: Object }>}
764
+ */
765
+ async function createVideoEventSource(input, options = {}) {
766
+ const reader =
767
+ input instanceof ArrayBuffer || ArrayBuffer.isView(input)
768
+ ? memoryReader(input)
769
+ : input;
770
+ const info = await parseMp4Info(reader);
771
+ const dataset = buildVideoDataset(info, options);
772
+ const fragmentBytes = normalizeFragmentBytes(options.fragmentBytes);
773
+
774
+ const dicomDict = datasetToMetaDict(dataset);
775
+ dicomDict.dict = sortDict(dicomDict.dict);
776
+
777
+ async function run(listener) {
778
+ await fromDataSet(dicomDict, withoutEndDataSet(listener));
779
+
780
+ listener.startElement(PIXEL_DATA_TAG, { vr: "OB", length: -1 });
781
+ listener.startBinary({ encapsulated: true });
782
+ for (let offset = 0; offset < reader.size; offset += fragmentBytes) {
783
+ const length = Math.min(fragmentBytes, reader.size - offset);
784
+ listener.binaryFragment(
785
+ exactFragment(await reader.read(offset, length))
786
+ );
787
+ // The defined backpressure checkpoint between fragments.
788
+ await listener.awaitDrain();
789
+ }
790
+ listener.endBinary();
791
+ listener.endElement();
792
+ listener.endDataSet();
793
+ }
794
+
795
+ return { run, info, dataset };
796
+ }
797
+
798
+ export { DEFAULT_FRAGMENT_BYTES, VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID, buildVideoDataset, createVideoEventSource, encapsulateVideo, extractEncapsulatedVideo, parseMp4Info, videoBase, videoPhotographicBase };
799
+ //# sourceMappingURL=index.mjs.map