@dcmjs-org/video 0.0.0-stage → 1.0.0-beta.3
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/README.md +141 -2
- package/package.json +17 -3
- package/src/encapsulated/encapsulatedVideo.js +338 -0
- package/src/encapsulated/index.js +21 -0
- package/src/eventStream/fromVideo.js +184 -0
- package/src/image/index.js +8 -0
- package/src/image/mp4Info.js +296 -0
- package/src/index.js +14 -0
- package/test/encapsulatedVideo.test.js +176 -0
- package/test/eventStream/fromVideo.test.js +231 -0
- package/test/mp4Info.test.js +115 -0
- package/test/utils/makeTinyMp4.js +240 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// src/eventStream/fromVideo.js
|
|
2
|
+
//
|
|
3
|
+
// MP4 → event stream (Supplement 225 video encapsulation). The dataset shell
|
|
4
|
+
// is built eagerly (stable UIDs across re-runs); running the
|
|
5
|
+
// stream replays the shell, then emits the MP4 as encapsulated PixelData
|
|
6
|
+
// fragments read one at a time from a random-access reader — so a 21.8 GB
|
|
7
|
+
// file streams with at most one fragment in memory, and the same code path
|
|
8
|
+
// serves in-memory bytes.
|
|
9
|
+
//
|
|
10
|
+
// The natural sink is StreamingPart10Writer, which turns each binaryFragment
|
|
11
|
+
// into one fragment item (undefined-length OB, empty Basic Offset Table,
|
|
12
|
+
// even-padded items, sequence delimiter). Backpressure is honored between
|
|
13
|
+
// fragments via listener.awaitDrain().
|
|
14
|
+
|
|
15
|
+
import { DicomMetaDictionary, EXPLICIT_LITTLE_ENDIAN } from "@dcmjs-org/core";
|
|
16
|
+
import { fromDataSet, EVENT_STREAM_VOCABULARY } from "@dcmjs-org/parser";
|
|
17
|
+
import { parseMp4Info } from "../image/mp4Info.js";
|
|
18
|
+
import {
|
|
19
|
+
buildVideoDataset,
|
|
20
|
+
normalizeFragmentBytes
|
|
21
|
+
} from "../encapsulated/encapsulatedVideo.js";
|
|
22
|
+
|
|
23
|
+
const PIXEL_DATA_TAG = "7FE00010";
|
|
24
|
+
|
|
25
|
+
const IMPLEMENTATION_CLASS_UID =
|
|
26
|
+
"2.25.80302813137786398554742050926734630921603366648225212145404";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Denaturalize a dataset into the plain `{ meta, dict }` shape fromDataSet
|
|
30
|
+
* consumes: the file meta group is minted from the dataset identity exactly
|
|
31
|
+
* the way legacy's datasetToDict does it, minus the DicomDict wrapper —
|
|
32
|
+
* nothing here writes bytes, so no writer object is needed. The meta group
|
|
33
|
+
* is a local object: the `_meta` of `dataset` does not change
|
|
34
|
+
* (CORE-USR-13, CORE-IMP-7).
|
|
35
|
+
*
|
|
36
|
+
* Each other `_meta` key (its `Value[0]`) goes into the file meta group
|
|
37
|
+
* (VID-USR-2). The defaults of `FileMetaInformationVersion`,
|
|
38
|
+
* `ImplementationClassUID`, and `ImplementationVersionName` apply only when
|
|
39
|
+
* `_meta` has no value. `MediaStorageSOPClassUID`,
|
|
40
|
+
* `MediaStorageSOPInstanceUID`, and `TransferSyntaxUID` always come from the
|
|
41
|
+
* dataset.
|
|
42
|
+
*/
|
|
43
|
+
function datasetToMetaDict(dataset) {
|
|
44
|
+
const fileMetaInformationVersionArray = new Uint8Array(2);
|
|
45
|
+
fileMetaInformationVersionArray[1] = 1;
|
|
46
|
+
|
|
47
|
+
const TransferSyntaxUID =
|
|
48
|
+
dataset._meta?.TransferSyntaxUID?.Value?.[0] || EXPLICIT_LITTLE_ENDIAN;
|
|
49
|
+
|
|
50
|
+
const callerMeta = {};
|
|
51
|
+
for (const [keyword, entry] of Object.entries(dataset._meta || {})) {
|
|
52
|
+
const value = Array.isArray(entry?.Value) ? entry.Value[0] : entry;
|
|
53
|
+
if (value !== undefined && value !== null && value !== "") {
|
|
54
|
+
callerMeta[keyword] = value;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const meta = {
|
|
59
|
+
FileMetaInformationVersion: fileMetaInformationVersionArray.buffer,
|
|
60
|
+
ImplementationClassUID: IMPLEMENTATION_CLASS_UID,
|
|
61
|
+
ImplementationVersionName: "dcmjs-0.0",
|
|
62
|
+
...callerMeta,
|
|
63
|
+
MediaStorageSOPClassUID: dataset.SOPClassUID,
|
|
64
|
+
MediaStorageSOPInstanceUID: dataset.SOPInstanceUID,
|
|
65
|
+
TransferSyntaxUID
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
meta: DicomMetaDictionary.denaturalizeDataset(meta),
|
|
70
|
+
dict: DicomMetaDictionary.denaturalizeDataset(dataset)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Wrap in-memory bytes in the random-access reader contract. */
|
|
75
|
+
function memoryReader(input) {
|
|
76
|
+
const bytes =
|
|
77
|
+
input instanceof ArrayBuffer
|
|
78
|
+
? new Uint8Array(input)
|
|
79
|
+
: new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
80
|
+
return {
|
|
81
|
+
size: bytes.byteLength,
|
|
82
|
+
read: (offset, length) =>
|
|
83
|
+
Promise.resolve(bytes.subarray(offset, offset + length))
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Fragments must reach buffered sinks as EXACT buffers: the collector →
|
|
89
|
+
* DicomDict.write path resolves a typed-array view to its whole backing
|
|
90
|
+
* ArrayBuffer (byteOffset is lost), so a subarray view would serialize the
|
|
91
|
+
* wrong bytes. Views that already span their full backing buffer (the
|
|
92
|
+
* fd-read case in streaming CLIs) pass through copy-free.
|
|
93
|
+
*/
|
|
94
|
+
function exactFragment(fragment) {
|
|
95
|
+
if (
|
|
96
|
+
ArrayBuffer.isView(fragment) &&
|
|
97
|
+
(fragment.byteOffset !== 0 ||
|
|
98
|
+
fragment.byteLength !== fragment.buffer.byteLength)
|
|
99
|
+
) {
|
|
100
|
+
return fragment.buffer.slice(
|
|
101
|
+
fragment.byteOffset,
|
|
102
|
+
fragment.byteOffset + fragment.byteLength
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
return fragment;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A forwarding view of `listener` that swallows endDataSet, so the dataset
|
|
110
|
+
* shell can be replayed first and the stream closed only after the pixel
|
|
111
|
+
* data fragments. awaitDrain/setDrain forward too — backpressure must
|
|
112
|
+
* survive the wrapper or the shell replay would run ungated.
|
|
113
|
+
*/
|
|
114
|
+
function withoutEndDataSet(listener) {
|
|
115
|
+
const wrapper = {};
|
|
116
|
+
for (const method of EVENT_STREAM_VOCABULARY) {
|
|
117
|
+
wrapper[method] = (...args) => listener[method](...args);
|
|
118
|
+
}
|
|
119
|
+
wrapper.endDataSet = () => {};
|
|
120
|
+
wrapper.awaitDrain = () => listener.awaitDrain();
|
|
121
|
+
wrapper.setDrain = fn => listener.setDrain(fn);
|
|
122
|
+
return wrapper;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Rebuild a dict with its tags in ascending order. fromDataSet emits entries
|
|
127
|
+
* in key order and StreamingPart10Writer writes them as they arrive, so key
|
|
128
|
+
* order IS file order; naturalized→denaturalized dicts follow property
|
|
129
|
+
* insertion order, which need not be tag order. Fixed-width uppercase hex
|
|
130
|
+
* sorts lexicographically === numerically.
|
|
131
|
+
*/
|
|
132
|
+
function sortDict(dict) {
|
|
133
|
+
const sorted = {};
|
|
134
|
+
for (const tag of Object.keys(dict).sort()) {
|
|
135
|
+
sorted[tag] = dict[tag];
|
|
136
|
+
}
|
|
137
|
+
return sorted;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Create the video event source. The function is async, because
|
|
142
|
+
* `parseMp4Info` reads the MP4 header through the reader. The returned
|
|
143
|
+
* `dataset` is the result of `buildVideoDataset`, without `PixelData`;
|
|
144
|
+
* `run(listener)` emits the dataset, then the MP4 as `PixelData` fragments.
|
|
145
|
+
*
|
|
146
|
+
* @param {Uint8Array|ArrayBuffer|{size, read(offset, length)}} input - MP4
|
|
147
|
+
* bytes or a random-access reader over them
|
|
148
|
+
* @param {Object} [options] - the buildVideoDataset options (the DICOM
|
|
149
|
+
* attributes go in `overrides`), plus `fragmentBytes`
|
|
150
|
+
* @returns {Promise<{ run: (listener) => Promise<void>, info: Object,
|
|
151
|
+
* dataset: Object }>}
|
|
152
|
+
*/
|
|
153
|
+
export async function createVideoEventSource(input, options = {}) {
|
|
154
|
+
const reader =
|
|
155
|
+
input instanceof ArrayBuffer || ArrayBuffer.isView(input)
|
|
156
|
+
? memoryReader(input)
|
|
157
|
+
: input;
|
|
158
|
+
const info = await parseMp4Info(reader);
|
|
159
|
+
const dataset = buildVideoDataset(info, options);
|
|
160
|
+
const fragmentBytes = normalizeFragmentBytes(options.fragmentBytes);
|
|
161
|
+
|
|
162
|
+
const dicomDict = datasetToMetaDict(dataset);
|
|
163
|
+
dicomDict.dict = sortDict(dicomDict.dict);
|
|
164
|
+
|
|
165
|
+
async function run(listener) {
|
|
166
|
+
await fromDataSet(dicomDict, withoutEndDataSet(listener));
|
|
167
|
+
|
|
168
|
+
listener.startElement(PIXEL_DATA_TAG, { vr: "OB", length: -1 });
|
|
169
|
+
listener.startBinary({ encapsulated: true });
|
|
170
|
+
for (let offset = 0; offset < reader.size; offset += fragmentBytes) {
|
|
171
|
+
const length = Math.min(fragmentBytes, reader.size - offset);
|
|
172
|
+
listener.binaryFragment(
|
|
173
|
+
exactFragment(await reader.read(offset, length))
|
|
174
|
+
);
|
|
175
|
+
// The defined backpressure checkpoint between fragments.
|
|
176
|
+
await listener.awaitDrain();
|
|
177
|
+
}
|
|
178
|
+
listener.endBinary();
|
|
179
|
+
listener.endElement();
|
|
180
|
+
listener.endDataSet();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return { run, info, dataset };
|
|
184
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// src/image/index.js — MP4 header inspection. The codec-free image builders
|
|
2
|
+
// (buildImageDataset, parseJpegInfo) and the h264 transfer-syntax mapping now
|
|
3
|
+
// live in @dcmjs-org/imaging; only MP4 container parsing stays here.
|
|
4
|
+
import { parseMp4Info } from "./mp4Info.js";
|
|
5
|
+
|
|
6
|
+
export { parseMp4Info };
|
|
7
|
+
|
|
8
|
+
export default { parseMp4Info };
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// src/image/mp4Info.js
|
|
2
|
+
//
|
|
3
|
+
// Minimal MP4 (ISO BMFF) header inspection: walk the box structure to recover
|
|
4
|
+
// the geometry and timing DICOM needs (Rows/Columns/NumberOfFrames/frame rate)
|
|
5
|
+
// and identify the matching video transfer syntax — WITHOUT decoding any
|
|
6
|
+
// pixels. H.264 in MP4 is a legal DICOM transfer syntax family (Supplement
|
|
7
|
+
// 225), so the MP4 stream can be carried as encapsulated PixelData verbatim;
|
|
8
|
+
// only the moov metadata must be understood.
|
|
9
|
+
//
|
|
10
|
+
// The moov box normally sits AFTER the (potentially enormous) mdat box, so the
|
|
11
|
+
// parser works against a random-access reader — { size, read(offset, length) }
|
|
12
|
+
// — and never buffers more than the moov box itself (a few MB even for a
|
|
13
|
+
// 20 GB file). Plain Uint8Array/ArrayBuffer input is wrapped in an in-memory
|
|
14
|
+
// reader so both call styles share one code path.
|
|
15
|
+
|
|
16
|
+
// The AVC profile/level → transfer syntax mapping moved to @dcmjs-org/imaging
|
|
17
|
+
// (it's shared, codec-free lookup). parseMp4Info uses it to label the stream.
|
|
18
|
+
import { h264TransferSyntaxUID } from "@dcmjs-org/imaging";
|
|
19
|
+
|
|
20
|
+
/** Wrap in-memory bytes in the random-access reader contract. */
|
|
21
|
+
function memoryReader(input) {
|
|
22
|
+
const bytes =
|
|
23
|
+
input instanceof ArrayBuffer
|
|
24
|
+
? new Uint8Array(input)
|
|
25
|
+
: new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
26
|
+
return {
|
|
27
|
+
size: bytes.byteLength,
|
|
28
|
+
read: (offset, length) =>
|
|
29
|
+
Promise.resolve(bytes.subarray(offset, offset + length))
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isReader(input) {
|
|
34
|
+
return (
|
|
35
|
+
input &&
|
|
36
|
+
typeof input === "object" &&
|
|
37
|
+
typeof input.read === "function" &&
|
|
38
|
+
typeof input.size === "number"
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Big-endian readers over a Uint8Array (MP4 box fields are big-endian). */
|
|
43
|
+
function u16(bytes, offset) {
|
|
44
|
+
return (bytes[offset] << 8) | bytes[offset + 1];
|
|
45
|
+
}
|
|
46
|
+
function u32(bytes, offset) {
|
|
47
|
+
return (
|
|
48
|
+
(bytes[offset] * 0x1000000 +
|
|
49
|
+
(bytes[offset + 1] << 16) +
|
|
50
|
+
(bytes[offset + 2] << 8) +
|
|
51
|
+
bytes[offset + 3]) >>>
|
|
52
|
+
0
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
function u64(bytes, offset) {
|
|
56
|
+
// Box sizes and v1 durations: safe as a Number (files < 2^53 bytes).
|
|
57
|
+
return u32(bytes, offset) * 0x100000000 + u32(bytes, offset + 4);
|
|
58
|
+
}
|
|
59
|
+
function fourCC(bytes, offset) {
|
|
60
|
+
return String.fromCharCode(
|
|
61
|
+
bytes[offset],
|
|
62
|
+
bytes[offset + 1],
|
|
63
|
+
bytes[offset + 2],
|
|
64
|
+
bytes[offset + 3]
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Iterate the child boxes of a byte range inside an in-memory buffer.
|
|
70
|
+
* Yields { type, offset, size, headerLength } with offset relative to `bytes`.
|
|
71
|
+
*/
|
|
72
|
+
function* boxes(bytes, start, end) {
|
|
73
|
+
let offset = start;
|
|
74
|
+
while (offset + 8 <= end) {
|
|
75
|
+
let size = u32(bytes, offset);
|
|
76
|
+
const type = fourCC(bytes, offset + 4);
|
|
77
|
+
let headerLength = 8;
|
|
78
|
+
if (size === 1) {
|
|
79
|
+
size = u64(bytes, offset + 8);
|
|
80
|
+
headerLength = 16;
|
|
81
|
+
} else if (size === 0) {
|
|
82
|
+
size = end - offset;
|
|
83
|
+
}
|
|
84
|
+
if (size < headerLength || offset + size > end) {
|
|
85
|
+
return; // malformed child; stop rather than walk garbage
|
|
86
|
+
}
|
|
87
|
+
yield { type, offset, size, headerLength };
|
|
88
|
+
offset += size;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function findBox(bytes, start, end, type) {
|
|
93
|
+
for (const box of boxes(bytes, start, end)) {
|
|
94
|
+
if (box.type === type) {
|
|
95
|
+
return box;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Inspect an MP4 file and return what DICOM video encapsulation needs.
|
|
103
|
+
*
|
|
104
|
+
* @param {Uint8Array|ArrayBuffer|{size: number, read: (offset: number,
|
|
105
|
+
* length: number) => Promise<Uint8Array>}} input - the MP4 bytes, or a
|
|
106
|
+
* random-access reader over them (the streaming path for large files)
|
|
107
|
+
* @returns {Promise<{ rows, columns, numberOfFrames, frameRate, cineRate,
|
|
108
|
+
* frameTime, codec, profileIdc, levelIdc, transferSyntaxUID: string|null,
|
|
109
|
+
* mp4ByteLength }>}
|
|
110
|
+
* @throws on non-MP4 input or when no video track is present
|
|
111
|
+
*/
|
|
112
|
+
export async function parseMp4Info(input) {
|
|
113
|
+
const reader = isReader(input) ? input : memoryReader(input);
|
|
114
|
+
|
|
115
|
+
// Top-level scan: a handful of 16-byte header reads regardless of file
|
|
116
|
+
// size. The first box must be ftyp — that is also the validity check.
|
|
117
|
+
let offset = 0;
|
|
118
|
+
let moovLocation = null;
|
|
119
|
+
let first = true;
|
|
120
|
+
while (offset + 8 <= reader.size) {
|
|
121
|
+
const head = await reader.read(
|
|
122
|
+
offset,
|
|
123
|
+
Math.min(16, reader.size - offset)
|
|
124
|
+
);
|
|
125
|
+
let size = u32(head, 0);
|
|
126
|
+
const type = fourCC(head, 4);
|
|
127
|
+
if (size === 1) {
|
|
128
|
+
if (head.byteLength < 16) {
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
size = u64(head, 8);
|
|
132
|
+
} else if (size === 0) {
|
|
133
|
+
size = reader.size - offset;
|
|
134
|
+
}
|
|
135
|
+
if (first && type !== "ftyp") {
|
|
136
|
+
throw new Error(
|
|
137
|
+
"parseMp4Info: input is not an MP4 file (missing ftyp box)"
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
first = false;
|
|
141
|
+
if (size < 8 || offset + size > reader.size) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`parseMp4Info: malformed box '${type}' at offset ${offset}`
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
if (type === "moov") {
|
|
147
|
+
moovLocation = { offset, size };
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
offset += size;
|
|
151
|
+
}
|
|
152
|
+
if (!moovLocation) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
"parseMp4Info: no moov box found — truncated or still-recording MP4"
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// The moov box is metadata only (a few MB at most); buffer it whole.
|
|
159
|
+
const moov = await reader.read(moovLocation.offset, moovLocation.size);
|
|
160
|
+
|
|
161
|
+
// First trak whose handler is "vide".
|
|
162
|
+
let video = null;
|
|
163
|
+
for (const trak of boxes(moov, 8, moov.byteLength)) {
|
|
164
|
+
if (trak.type !== "trak") {
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const trakEnd = trak.offset + trak.size;
|
|
168
|
+
const mdia = findBox(moov, trak.offset + 8, trakEnd, "mdia");
|
|
169
|
+
if (!mdia) {
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const mdiaEnd = mdia.offset + mdia.size;
|
|
173
|
+
const hdlr = findBox(moov, mdia.offset + 8, mdiaEnd, "hdlr");
|
|
174
|
+
// hdlr: 8 header + 4 version/flags + 4 pre_defined, then handler_type
|
|
175
|
+
if (!hdlr || fourCC(moov, hdlr.offset + 16) !== "vide") {
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
video = { mdia, mdiaEnd };
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
if (!video) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
"parseMp4Info: no video track found in the MP4 (audio-only file?)"
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const { mdia, mdiaEnd } = video;
|
|
188
|
+
|
|
189
|
+
// mdhd → timescale/duration (v0: 32-bit fields, v1: 64-bit times).
|
|
190
|
+
const mdhd = findBox(moov, mdia.offset + 8, mdiaEnd, "mdhd");
|
|
191
|
+
if (!mdhd) {
|
|
192
|
+
throw new Error("parseMp4Info: video track has no mdhd box");
|
|
193
|
+
}
|
|
194
|
+
const mdhdVersion = moov[mdhd.offset + 8];
|
|
195
|
+
let timescale, duration;
|
|
196
|
+
if (mdhdVersion === 1) {
|
|
197
|
+
timescale = u32(moov, mdhd.offset + 12 + 16);
|
|
198
|
+
duration = u64(moov, mdhd.offset + 12 + 20);
|
|
199
|
+
} else {
|
|
200
|
+
timescale = u32(moov, mdhd.offset + 12 + 8);
|
|
201
|
+
duration = u32(moov, mdhd.offset + 12 + 12);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const minf = findBox(moov, mdia.offset + 8, mdiaEnd, "minf");
|
|
205
|
+
const stbl =
|
|
206
|
+
minf && findBox(moov, minf.offset + 8, minf.offset + minf.size, "stbl");
|
|
207
|
+
const stsd =
|
|
208
|
+
stbl && findBox(moov, stbl.offset + 8, stbl.offset + stbl.size, "stsd");
|
|
209
|
+
if (!stsd) {
|
|
210
|
+
throw new Error("parseMp4Info: video track has no sample description");
|
|
211
|
+
}
|
|
212
|
+
const stblEnd = stbl.offset + stbl.size;
|
|
213
|
+
|
|
214
|
+
// stsd: 8 header + 4 version/flags + 4 entry_count, then sample entries.
|
|
215
|
+
const entry = stsd.offset + 16;
|
|
216
|
+
const entrySize = u32(moov, entry);
|
|
217
|
+
const codec = fourCC(moov, entry + 4);
|
|
218
|
+
// VisualSampleEntry: 8 box header + 6 reserved + 2 data_reference_index
|
|
219
|
+
// + 16 pre_defined/reserved → width at +32, height at +34 (validated
|
|
220
|
+
// against real encoder output, not just the spec).
|
|
221
|
+
const columns = u16(moov, entry + 32);
|
|
222
|
+
const rows = u16(moov, entry + 34);
|
|
223
|
+
|
|
224
|
+
// avcC → AVCDecoderConfigurationRecord: profile_idc and level_idc are
|
|
225
|
+
// bytes 1 and 3 of the record. The fixed part of a VisualSampleEntry is
|
|
226
|
+
// 86 bytes; codec-specific child boxes follow.
|
|
227
|
+
let profileIdc = null;
|
|
228
|
+
let levelIdc = null;
|
|
229
|
+
if (codec === "avc1" || codec === "avc3") {
|
|
230
|
+
const avcC = findBox(moov, entry + 86, entry + entrySize, "avcC");
|
|
231
|
+
if (avcC) {
|
|
232
|
+
profileIdc = moov[avcC.offset + 9];
|
|
233
|
+
levelIdc = moov[avcC.offset + 11];
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Frame count: stsz sample_count (authoritative), stts sum as fallback.
|
|
238
|
+
let numberOfFrames = 0;
|
|
239
|
+
const stsz = findBox(moov, stbl.offset + 8, stblEnd, "stsz");
|
|
240
|
+
if (stsz) {
|
|
241
|
+
numberOfFrames = u32(moov, stsz.offset + 16);
|
|
242
|
+
}
|
|
243
|
+
const stts = findBox(moov, stbl.offset + 8, stblEnd, "stts");
|
|
244
|
+
if (!numberOfFrames && stts) {
|
|
245
|
+
const entryCount = u32(moov, stts.offset + 12);
|
|
246
|
+
// Each stts entry is 8 bytes after the 16-byte fixed part. A raw
|
|
247
|
+
// entry_count beyond the box's own size is malformed: walking it
|
|
248
|
+
// would read zero-coerced garbage past the box and block the thread
|
|
249
|
+
// for seconds at large counts (review finding 15).
|
|
250
|
+
if (16 + entryCount * 8 > stts.size) {
|
|
251
|
+
throw new Error(
|
|
252
|
+
`parseMp4Info: malformed stts box — entry_count ${entryCount} ` +
|
|
253
|
+
`does not fit in a ${stts.size}-byte box`
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
for (let i = 0; i < entryCount; i++) {
|
|
257
|
+
numberOfFrames += u32(moov, stts.offset + 16 + i * 8);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Frame rate: exact from a single-entry stts (constant frame rate);
|
|
262
|
+
// otherwise the average over the track (variable frame rate).
|
|
263
|
+
let frameRate = null;
|
|
264
|
+
if (stts && u32(moov, stts.offset + 12) === 1) {
|
|
265
|
+
const sampleDelta = u32(moov, stts.offset + 20);
|
|
266
|
+
if (sampleDelta > 0) {
|
|
267
|
+
frameRate = timescale / sampleDelta;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (!frameRate && duration > 0 && numberOfFrames > 0) {
|
|
271
|
+
frameRate = (numberOfFrames * timescale) / duration;
|
|
272
|
+
}
|
|
273
|
+
if (!frameRate) {
|
|
274
|
+
throw new Error(
|
|
275
|
+
"parseMp4Info: could not determine the frame rate from the video track"
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
return {
|
|
280
|
+
rows,
|
|
281
|
+
columns,
|
|
282
|
+
numberOfFrames,
|
|
283
|
+
frameRate,
|
|
284
|
+
cineRate: Math.round(frameRate),
|
|
285
|
+
// FrameTime (0018,1063) is DS: milliseconds per frame as a string.
|
|
286
|
+
frameTime: (1000 / frameRate).toFixed(6),
|
|
287
|
+
codec,
|
|
288
|
+
profileIdc,
|
|
289
|
+
levelIdc,
|
|
290
|
+
transferSyntaxUID:
|
|
291
|
+
profileIdc !== null
|
|
292
|
+
? h264TransferSyntaxUID(profileIdc, levelIdc)
|
|
293
|
+
: null,
|
|
294
|
+
mp4ByteLength: reader.size
|
|
295
|
+
};
|
|
296
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// The public surface of @dcmjs-org/video.
|
|
2
|
+
//
|
|
3
|
+
// parseMp4Info walks an MP4's moov box to recover the geometry and timing
|
|
4
|
+
// DICOM needs WITHOUT decoding any pixels, so the compressed stream can travel
|
|
5
|
+
// into encapsulated PixelData verbatim. The encapsulated module wraps an MP4's
|
|
6
|
+
// H.264 stream into a Video Photographic Image instance (and recovers it
|
|
7
|
+
// byte-identically). createVideoEventSource is the streaming path: MP4 →
|
|
8
|
+
// contract events, one fragment in memory at a time, for any event-stream sink.
|
|
9
|
+
//
|
|
10
|
+
// Codec-free image building (buildImageDataset) and JPEG/H.264 header
|
|
11
|
+
// inspection live in @dcmjs-org/imaging; this package depends on it.
|
|
12
|
+
export * from "./image/index.js";
|
|
13
|
+
export * from "./encapsulated/index.js";
|
|
14
|
+
export { createVideoEventSource } from "./eventStream/fromVideo.js";
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// test/encapsulatedVideo.test.js
|
|
2
|
+
//
|
|
3
|
+
// buildVideoDataset / encapsulateVideo / extractEncapsulatedVideo — the
|
|
4
|
+
// buffered video encapsulation layer. Element values are pinned against the
|
|
5
|
+
// Supplement 225 reference fixture's dataset (large-files
|
|
6
|
+
// build_dicom_video.py) so the JS builder and the independent Python oracle
|
|
7
|
+
// agree on the instance shape.
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
buildVideoDataset,
|
|
11
|
+
encapsulateVideo,
|
|
12
|
+
extractEncapsulatedVideo,
|
|
13
|
+
normalizeFragmentBytes,
|
|
14
|
+
VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
|
|
15
|
+
DEFAULT_FRAGMENT_BYTES
|
|
16
|
+
} from "../src/encapsulated/encapsulatedVideo.js";
|
|
17
|
+
import { parseMp4Info } from "../src/image/mp4Info.js";
|
|
18
|
+
import { makeTinyMp4 } from "./utils/makeTinyMp4.js";
|
|
19
|
+
|
|
20
|
+
const H264_HIGH_42 = "1.2.840.10008.1.2.4.104.1";
|
|
21
|
+
|
|
22
|
+
describe("buildVideoDataset", () => {
|
|
23
|
+
let info;
|
|
24
|
+
beforeAll(async () => {
|
|
25
|
+
info = await parseMp4Info(makeTinyMp4());
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it("joins the study of a source instance, and control keys stay out", () => {
|
|
29
|
+
const source = {
|
|
30
|
+
PatientID: "JD-001",
|
|
31
|
+
StudyInstanceUID: "2.25.1",
|
|
32
|
+
SeriesInstanceUID: "2.25.2",
|
|
33
|
+
SOPClassUID: VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
|
|
34
|
+
SOPInstanceUID: "2.25.3",
|
|
35
|
+
Modality: "XC"
|
|
36
|
+
};
|
|
37
|
+
const dataset = buildVideoDataset(info, {
|
|
38
|
+
instance: source,
|
|
39
|
+
predecessor: true,
|
|
40
|
+
fragmentBytes: 2,
|
|
41
|
+
overrides: { Rows: 1 }
|
|
42
|
+
});
|
|
43
|
+
expect(dataset.PatientID).toBe("JD-001");
|
|
44
|
+
expect(dataset.StudyInstanceUID).toBe("2.25.1");
|
|
45
|
+
expect(dataset.SeriesInstanceUID).not.toBe("2.25.2");
|
|
46
|
+
// videoBase has no predecessorBase (VID-USR-8).
|
|
47
|
+
expect(dataset).not.toHaveProperty("PredecessorDocumentsSequence");
|
|
48
|
+
expect(dataset.Rows).toBe(48);
|
|
49
|
+
expect(dataset.fragmentBytes).toBeUndefined();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("mirrors the Supplement 225 reference element list", () => {
|
|
53
|
+
const dataset = buildVideoDataset(info, {
|
|
54
|
+
overrides: { PatientName: "DOE^JANE", PatientID: "JD-001" }
|
|
55
|
+
});
|
|
56
|
+
expect(dataset.SOPClassUID).toBe(VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID);
|
|
57
|
+
expect(dataset.Modality).toBe("XC");
|
|
58
|
+
expect(dataset.PatientName).toBe("DOE^JANE");
|
|
59
|
+
expect(dataset.PatientID).toBe("JD-001");
|
|
60
|
+
expect(dataset.StudyID).toBe("");
|
|
61
|
+
expect(dataset.CineRate).toBe(60);
|
|
62
|
+
expect(dataset.FrameTime).toBe("16.666667");
|
|
63
|
+
expect(dataset.SamplesPerPixel).toBe(3);
|
|
64
|
+
expect(dataset.PhotometricInterpretation).toBe("YBR_PARTIAL_420");
|
|
65
|
+
expect(dataset.PlanarConfiguration).toBe(0);
|
|
66
|
+
expect(dataset.NumberOfFrames).toBe(12);
|
|
67
|
+
expect(dataset.Rows).toBe(48);
|
|
68
|
+
expect(dataset.Columns).toBe(64);
|
|
69
|
+
expect(dataset.BitsAllocated).toBe(8);
|
|
70
|
+
expect(dataset.BitsStored).toBe(8);
|
|
71
|
+
expect(dataset.HighBit).toBe(7);
|
|
72
|
+
expect(dataset.PixelRepresentation).toBe(0);
|
|
73
|
+
expect(dataset.LossyImageCompression).toBe("01");
|
|
74
|
+
expect(dataset.EncapsulatedPixelDataValueTotalLength).toBe(
|
|
75
|
+
BigInt(info.mp4ByteLength)
|
|
76
|
+
);
|
|
77
|
+
expect(dataset._meta.TransferSyntaxUID.Value).toEqual([H264_HIGH_42]);
|
|
78
|
+
expect(dataset._vrMap.PixelData).toBe("OB");
|
|
79
|
+
expect(dataset.PixelData).toBeUndefined();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("mints fresh UIDs and honors overrides", () => {
|
|
83
|
+
const a = buildVideoDataset(info);
|
|
84
|
+
const b = buildVideoDataset(info);
|
|
85
|
+
expect(a.SOPInstanceUID).not.toBe(b.SOPInstanceUID);
|
|
86
|
+
const pinned = buildVideoDataset(info, {
|
|
87
|
+
overrides: {
|
|
88
|
+
StudyInstanceUID: "1.2.3.4",
|
|
89
|
+
SeriesInstanceUID: "1.2.3.4.5"
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
expect(pinned.StudyInstanceUID).toBe("1.2.3.4");
|
|
93
|
+
expect(pinned.SeriesInstanceUID).toBe("1.2.3.4.5");
|
|
94
|
+
// API: an _meta key other than TransferSyntaxUID stays (VID-USR-2).
|
|
95
|
+
const meta = buildVideoDataset(info, {
|
|
96
|
+
overrides: {
|
|
97
|
+
_meta: { ImplementationVersionName: { Value: ["X"] } }
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
expect(meta._meta.ImplementationVersionName).toEqual({ Value: ["X"] });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("throws the transcode corrective error for unsupported codecs", async () => {
|
|
104
|
+
const hevcInfo = await parseMp4Info(makeTinyMp4({ codec: "hev1" }));
|
|
105
|
+
expect(() => buildVideoDataset(hevcInfo)).toThrow(/ffmpeg/);
|
|
106
|
+
expect(() => buildVideoDataset(hevcInfo)).toThrow(/hev1/);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
describe("normalizeFragmentBytes", () => {
|
|
111
|
+
it("defaults and validates", () => {
|
|
112
|
+
expect(normalizeFragmentBytes(undefined)).toBe(DEFAULT_FRAGMENT_BYTES);
|
|
113
|
+
expect(normalizeFragmentBytes(4096)).toBe(4096);
|
|
114
|
+
expect(() => normalizeFragmentBytes(4097)).toThrow(/even/);
|
|
115
|
+
expect(() => normalizeFragmentBytes(0)).toThrow(/even integer/);
|
|
116
|
+
expect(() => normalizeFragmentBytes(1.5)).toThrow(/even integer/);
|
|
117
|
+
expect(() => normalizeFragmentBytes(0xfffffffe)).toThrow(
|
|
118
|
+
/even integer/
|
|
119
|
+
);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe("encapsulateVideo / extractEncapsulatedVideo", () => {
|
|
124
|
+
it("splits the stream into fragment-sized slices", async () => {
|
|
125
|
+
const mp4 = makeTinyMp4(); // 1001-byte odd mdat payload
|
|
126
|
+
const dataset = await encapsulateVideo(mp4, { fragmentBytes: 1024 });
|
|
127
|
+
expect(Array.isArray(dataset.PixelData)).toBe(true);
|
|
128
|
+
const total = dataset.PixelData.reduce((n, f) => n + f.byteLength, 0);
|
|
129
|
+
expect(total).toBe(mp4.byteLength);
|
|
130
|
+
expect(dataset.PixelData.length).toBe(Math.ceil(mp4.byteLength / 1024));
|
|
131
|
+
// every fragment but the last is exactly fragmentBytes
|
|
132
|
+
for (const fragment of dataset.PixelData.slice(0, -1)) {
|
|
133
|
+
expect(fragment.byteLength).toBe(1024);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("round-trips byte-identically, dropping the declared-length overrun", async () => {
|
|
138
|
+
const mp4 = makeTinyMp4();
|
|
139
|
+
const dataset = await encapsulateVideo(mp4, { fragmentBytes: 512 });
|
|
140
|
+
// Simulate the Part 10 writer's pad byte on the odd final fragment.
|
|
141
|
+
const last = new Uint8Array(
|
|
142
|
+
dataset.PixelData[dataset.PixelData.length - 1]
|
|
143
|
+
);
|
|
144
|
+
const padded = new Uint8Array(last.byteLength + (last.byteLength % 2));
|
|
145
|
+
padded.set(last);
|
|
146
|
+
dataset.PixelData[dataset.PixelData.length - 1] = padded.buffer;
|
|
147
|
+
|
|
148
|
+
const { bytes, transferSyntaxUID, declaredLength } =
|
|
149
|
+
extractEncapsulatedVideo(dataset);
|
|
150
|
+
expect(declaredLength).toBe(mp4.byteLength);
|
|
151
|
+
expect(transferSyntaxUID).toBe(H264_HIGH_42);
|
|
152
|
+
expect(bytes.byteLength).toBe(mp4.byteLength);
|
|
153
|
+
expect(Buffer.compare(Buffer.from(bytes), Buffer.from(mp4))).toBe(0);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("keeps everything and reports null when no total length is declared", async () => {
|
|
157
|
+
const mp4 = makeTinyMp4({ mdatLength: 1000 }); // even → no padding
|
|
158
|
+
const dataset = await encapsulateVideo(mp4);
|
|
159
|
+
delete dataset.EncapsulatedPixelDataValueTotalLength;
|
|
160
|
+
const { bytes, declaredLength } = extractEncapsulatedVideo(dataset);
|
|
161
|
+
expect(declaredLength).toBeNull();
|
|
162
|
+
expect(bytes.byteLength).toBe(mp4.byteLength);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("rejects a non-video dataset with a corrective error", () => {
|
|
166
|
+
expect(() =>
|
|
167
|
+
extractEncapsulatedVideo({
|
|
168
|
+
SOPClassUID: "1.2.840.10008.5.1.4.1.1.104.1", // Encapsulated PDF
|
|
169
|
+
PatientName: "FOX^JANE",
|
|
170
|
+
_meta: {
|
|
171
|
+
TransferSyntaxUID: { Value: ["1.2.840.10008.1.2.1"] }
|
|
172
|
+
}
|
|
173
|
+
})
|
|
174
|
+
).toThrow(/not an encapsulated video/);
|
|
175
|
+
});
|
|
176
|
+
});
|