@dcmjs-org/video 0.0.0-stage → 1.0.0-beta.11

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