@dcmjs-org/video 0.0.0-stage → 1.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/License.txt +22 -0
- package/README.md +141 -2
- package/package.json +21 -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/License.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
The MIT License (MIT)
|
|
3
|
+
|
|
4
|
+
Copyright (c) 2017 Steve Pieper
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,142 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dcmjs-org/video
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MP4-to-DICOM video encapsulation for dcmjs (Supplement 225). The package
|
|
4
|
+
reads the MP4 header without a decode, and puts the H.264 stream of the MP4
|
|
5
|
+
into a Video Photographic Image instance. The stream goes into the pixel data
|
|
6
|
+
fragments without a change, so the round trip is byte-identical.
|
|
7
|
+
|
|
8
|
+
- `parseMp4Info(bytes | reader)` (async) — the geometry, the timing, and
|
|
9
|
+
the transfer syntax of an MP4, without a decode.
|
|
10
|
+
- `buildVideoDataset(mp4Info, options)` (sync) — the dataset without
|
|
11
|
+
`PixelData`. It calls `createInstance` from `@dcmjs-org/core`, then sets
|
|
12
|
+
the stream attributes.
|
|
13
|
+
- `encapsulateVideo(mp4Bytes, options)` (async) — the buffered path. It
|
|
14
|
+
returns a `Promise` of the dataset with `PixelData` as fragments.
|
|
15
|
+
- `createVideoEventSource(input, options)` (async) — the streaming path.
|
|
16
|
+
It returns a `Promise` of `{ run, info, dataset }`:
|
|
17
|
+
- `run(listener)` emits the dataset and the fragments as events, with
|
|
18
|
+
one fragment in memory at a time. It returns a `Promise`.
|
|
19
|
+
- `info` is the `parseMp4Info` result.
|
|
20
|
+
- `dataset` is the `buildVideoDataset` result, without `PixelData`.
|
|
21
|
+
- `extractEncapsulatedVideo(dataset)` — gets the MP4 stream back from a
|
|
22
|
+
naturalized video instance.
|
|
23
|
+
- `videoBase` and `videoPhotographicBase` — the default base blocks.
|
|
24
|
+
|
|
25
|
+
The functions that read an MP4 are async, because `parseMp4Info` accepts a
|
|
26
|
+
random-access reader. `input` of `createVideoEventSource` is MP4 bytes or
|
|
27
|
+
such a reader.
|
|
28
|
+
|
|
29
|
+
The codec-free image builder (`buildImageDataset`) and the JPEG and H.264
|
|
30
|
+
header inspection are in `@dcmjs-org/imaging`.
|
|
31
|
+
|
|
32
|
+
## Options
|
|
33
|
+
|
|
34
|
+
The options of `buildVideoDataset`, `encapsulateVideo`, and
|
|
35
|
+
`createVideoEventSource` follow CORE-USR-1 in `packages/core/README.md`: the
|
|
36
|
+
`createInstance` controls, `overrides`, and these control keys. All of
|
|
37
|
+
them are options. `overrides` is a naturalized DICOM provider with the
|
|
38
|
+
forms of `baseDicom`, and holds only DICOM attributes. A control key never
|
|
39
|
+
goes in `overrides`. An extra option key has no effect (CORE-USR-7).
|
|
40
|
+
|
|
41
|
+
- `baseDicom` (default `videoBase`) — base blocks. `videoBase` has no
|
|
42
|
+
`predecessorBase`, so `predecessor: true` needs a custom base
|
|
43
|
+
(VID-USR-8).
|
|
44
|
+
- `fragmentBytes` (default 256 MiB) — the size of each `PixelData`
|
|
45
|
+
fragment. `buildVideoDataset` ignores it.
|
|
46
|
+
|
|
47
|
+
```js
|
|
48
|
+
const video = await encapsulateVideo(mp4Bytes, {
|
|
49
|
+
instance: priorInstanceInSeries,
|
|
50
|
+
dataLevel: "series",
|
|
51
|
+
overrides: { SeriesDescription: "Endoscopy" }
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Scope and change rule
|
|
56
|
+
|
|
57
|
+
The shared requirements of `createInstance` (CORE-USR-n, CORE-IMP-n in
|
|
58
|
+
`packages/core/README.md`) apply to the video builders. This README lists
|
|
59
|
+
only the requirements of this package.
|
|
60
|
+
|
|
61
|
+
The change rule of the core README applies. Change a user requirement
|
|
62
|
+
(VID-USR-n) only when it describes the behaviour wrongly, or when the
|
|
63
|
+
intended user-facing behaviour changes, and name the change in the pull
|
|
64
|
+
request. The implementation requirements (VID-IMP-n) describe the current
|
|
65
|
+
approach, and can change freely. Do not renumber an identifier.
|
|
66
|
+
|
|
67
|
+
## § User requirements
|
|
68
|
+
|
|
69
|
+
- **VID-USR-1** `instance` is where the new video goes (CORE-USR-3). The
|
|
70
|
+
default levels do not copy the identity of `instance` (CORE-USR-4).
|
|
71
|
+
Without a `SOPClassUID` override, and without a custom `levels` that
|
|
72
|
+
lists `SOPClassUID`, `videoBase` sets the Video Photographic Image
|
|
73
|
+
`SOPClassUID`.
|
|
74
|
+
- **VID-USR-2** The stream attributes come from the MP4: `CineRate`,
|
|
75
|
+
`FrameTime`, `NumberOfFrames`, `Rows`, `Columns`,
|
|
76
|
+
`EncapsulatedPixelDataValueTotalLength (7FE0,0003)`, and
|
|
77
|
+
`_meta.TransferSyntaxUID`. `buildVideoDataset` sets them after
|
|
78
|
+
`createInstance`, and replaces an override of them with no warning.
|
|
79
|
+
This rule applies to each form of `overrides`. A field that `mp4Info`
|
|
80
|
+
does not give writes no attribute, so the value of the base, of
|
|
81
|
+
`instance`, or of `overrides` stays. The `_meta` rule of CORE-USR-13
|
|
82
|
+
applies: the builder always sets `_meta.TransferSyntaxUID`, and keeps
|
|
83
|
+
the other `_meta` keys. `encapsulateVideo` and `createVideoEventSource`
|
|
84
|
+
set `PixelData` from the stream. `createVideoEventSource` does not
|
|
85
|
+
change the `_meta` of the dataset that it returns. It makes the file
|
|
86
|
+
meta group of its events in a separate object. The file meta group
|
|
87
|
+
gets each key of the dataset `_meta`, for example
|
|
88
|
+
`ImplementationVersionName`. `createVideoEventSource` always sets
|
|
89
|
+
`TransferSyntaxUID`, `MediaStorageSOPClassUID`, and
|
|
90
|
+
`MediaStorageSOPInstanceUID` from the dataset. It sets
|
|
91
|
+
`FileMetaInformationVersion`, `ImplementationClassUID`, and
|
|
92
|
+
`ImplementationVersionName` only when the dataset `_meta` has no value.
|
|
93
|
+
Thus a caller can set these three keys and other file meta keys in
|
|
94
|
+
`overrides._meta`.
|
|
95
|
+
- **VID-USR-3** A caller can set in `overrides` the Image Pixel values
|
|
96
|
+
that the MPEG-4 AVC transfer syntaxes mandate (`SamplesPerPixel`,
|
|
97
|
+
`PhotometricInterpretation`, `PlanarConfiguration`, `BitsAllocated`,
|
|
98
|
+
`BitsStored`, `HighBit`, `PixelRepresentation`), and
|
|
99
|
+
`LossyImageCompression`. The builder permits this on purpose. A
|
|
100
|
+
conformant reader uses the values of the codec stream, and these values
|
|
101
|
+
take precedence over the dataset values.
|
|
102
|
+
- **VID-USR-4** An MP4 with a codec that no DICOM video transfer syntax
|
|
103
|
+
carries throws an error. The error gives an `ffmpeg` command that makes a
|
|
104
|
+
supported stream (H.264 Baseline, Main, or High, up to Level 4.2).
|
|
105
|
+
- **VID-USR-5** `fragmentBytes` is an even integer from 2 to 2^32-2. Each
|
|
106
|
+
other value throws an error.
|
|
107
|
+
- **VID-USR-6** `extractEncapsulatedVideo` returns the stream that was
|
|
108
|
+
encapsulated, byte for byte. It removes the pad byte of an odd-length
|
|
109
|
+
last fragment through the declared total length. A dataset that is not
|
|
110
|
+
a video throws an error. A video dataset has the Video Photographic
|
|
111
|
+
Image `SOPClassUID` or a video transfer syntax, and has `PixelData`.
|
|
112
|
+
- **VID-USR-7** `parseMp4Info`, and thus `encapsulateVideo` and
|
|
113
|
+
`createVideoEventSource`, throw an error for an MP4 that they cannot
|
|
114
|
+
read (CORE-IMP-11): no `ftyp` box first, a malformed box, no `moov`
|
|
115
|
+
box, no video track, a video track without `mdhd` or a sample
|
|
116
|
+
description, a malformed `stts` box, or no frame rate.
|
|
117
|
+
- **VID-USR-8** `videoBase` does not include `predecessorBase`
|
|
118
|
+
(CORE-USR-9). With the default base, `predecessor: true` has no effect:
|
|
119
|
+
the result has no `PredecessorDocumentsSequence`, and the builder throws
|
|
120
|
+
no predecessor error. For a predecessor, give
|
|
121
|
+
`baseDicom: combineBases(videoBase, predecessorBase)`, with
|
|
122
|
+
`predecessorBase` from `@dcmjs-org/core`.
|
|
123
|
+
|
|
124
|
+
## § Implementation requirements
|
|
125
|
+
|
|
126
|
+
- **VID-IMP-1** `videoBase` is `defaultInstanceBase`,
|
|
127
|
+
`videoPhotographicBase` (SOP class, Modality `XC`, the Image Pixel values
|
|
128
|
+
of VID-USR-3, `LossyImageCompression` `"01"`) (CORE-IMP-3). `videoBase`
|
|
129
|
+
has no `predecessorBase` (VID-USR-8).
|
|
130
|
+
- **VID-IMP-2** `buildVideoDataset` removes its control key `fragmentBytes`
|
|
131
|
+
before it calls `createInstance` (CORE-IMP-9), and passes `overrides`
|
|
132
|
+
and `postProcess` through.
|
|
133
|
+
- **VID-IMP-3** `EncapsulatedPixelDataValueTotalLength` is a BigInt,
|
|
134
|
+
because VR UV is a 64-bit unsigned integer.
|
|
135
|
+
- **VID-IMP-4** `extractEncapsulatedVideo` keeps all of the bytes when the
|
|
136
|
+
dataset has no total length, and returns `declaredLength: null`, so the
|
|
137
|
+
caller can choose a warning.
|
|
138
|
+
|
|
139
|
+
## Dependencies
|
|
140
|
+
|
|
141
|
+
The package builds on `@dcmjs-org/core`, `@dcmjs-org/imaging` (the shared
|
|
142
|
+
`h264TransferSyntaxUID` map), and `@dcmjs-org/parser`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dcmjs-org/video",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-beta.4",
|
|
4
|
+
"description": "MP4-to-DICOM video encapsulation for dcmjs (Supplement 225): MP4 header inspection without decoding, and wrapping/streaming an MP4's H.264 stream into a Video Photographic Image instance. Codec-free image building lives in @dcmjs-org/imaging",
|
|
5
|
+
"main": "./src/index.js",
|
|
6
|
+
"files": [
|
|
7
|
+
"src",
|
|
8
|
+
"README.md"
|
|
9
|
+
],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/dcmjs-org/dcmjs.git",
|
|
14
|
+
"directory": "packages/video"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@dcmjs-org/core": "1.0.0-beta.4",
|
|
18
|
+
"@dcmjs-org/imaging": "1.0.0-beta.4",
|
|
19
|
+
"@dcmjs-org/parser": "1.0.0-beta.4"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@dcmjs-org/generator": "1.0.0-beta.4"
|
|
23
|
+
}
|
|
6
24
|
}
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
// src/encapsulated/encapsulatedVideo.js
|
|
2
|
+
//
|
|
3
|
+
// Video encapsulation (Supplement 225): an MP4's H.264 stream travels inside
|
|
4
|
+
// a Video Photographic Image instance VERBATIM — the pixel data fragments are
|
|
5
|
+
// consecutive byte ranges of the one MP4 stream, so extraction is
|
|
6
|
+
// concatenation and the round trip is byte-identical. Two directions,
|
|
7
|
+
// mirroring encapsulatedPdf.js:
|
|
8
|
+
//
|
|
9
|
+
// buildVideoDataset(mp4Info, options) — dataset shell (no PixelData), used
|
|
10
|
+
// by both the buffered and the streaming encapsulation paths.
|
|
11
|
+
// encapsulateVideo(mp4Bytes, options) — MP4 in (buffered): dataset plus
|
|
12
|
+
// PixelData as fragment-sized ArrayBuffer slices.
|
|
13
|
+
// extractEncapsulatedVideo(dataset) — MP4 out: recover the stream from a
|
|
14
|
+
// naturalized video instance, truncated to the declared total length.
|
|
15
|
+
//
|
|
16
|
+
// The (7FE0,0003) Encapsulated Pixel Data Value Total Length element (VR UV,
|
|
17
|
+
// uint64) records the exact stream length so the required trailing pad byte
|
|
18
|
+
// on an odd-length final fragment can be dropped on extraction.
|
|
19
|
+
|
|
20
|
+
import {
|
|
21
|
+
combineBases,
|
|
22
|
+
createInstance,
|
|
23
|
+
defaultInstanceBase,
|
|
24
|
+
isVideoTransferSyntax
|
|
25
|
+
} from "@dcmjs-org/core";
|
|
26
|
+
import { parseMp4Info } from "../image/mp4Info.js";
|
|
27
|
+
|
|
28
|
+
const VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID = "1.2.840.10008.5.1.4.1.1.77.1.4.1";
|
|
29
|
+
|
|
30
|
+
// 256 MiB: small enough that one in-flight fragment stays comfortably in
|
|
31
|
+
// memory, large enough that a 21.8 GB stream is only ~82 fragments.
|
|
32
|
+
const DEFAULT_FRAGMENT_BYTES = 256 * 1024 * 1024;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Validate/default the encapsulation fragment size. Fragment item lengths are
|
|
36
|
+
* 32-bit and must be even (PS3.5 §A.4), so the size must be an even integer
|
|
37
|
+
* below 2^32-2.
|
|
38
|
+
*
|
|
39
|
+
* @param {number} [fragmentBytes]
|
|
40
|
+
* @returns {number}
|
|
41
|
+
*/
|
|
42
|
+
function normalizeFragmentBytes(fragmentBytes) {
|
|
43
|
+
if (fragmentBytes === undefined || fragmentBytes === null) {
|
|
44
|
+
return DEFAULT_FRAGMENT_BYTES;
|
|
45
|
+
}
|
|
46
|
+
if (
|
|
47
|
+
!Number.isInteger(fragmentBytes) ||
|
|
48
|
+
fragmentBytes < 2 ||
|
|
49
|
+
fragmentBytes % 2 !== 0 ||
|
|
50
|
+
fragmentBytes >= 0xfffffffe
|
|
51
|
+
) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`fragmentBytes must be an even integer between 2 and 2^32-2 ` +
|
|
54
|
+
`(fragment item lengths are even 32-bit values); got ${fragmentBytes}`
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
return fragmentBytes;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The corrective error for codecs no DICOM video transfer syntax carries. */
|
|
61
|
+
function unsupportedCodecError(info) {
|
|
62
|
+
const profile =
|
|
63
|
+
info.profileIdc !== null
|
|
64
|
+
? ` profile ${info.profileIdc} level ${(info.levelIdc / 10).toFixed(
|
|
65
|
+
1
|
|
66
|
+
)}`
|
|
67
|
+
: "";
|
|
68
|
+
return new Error(
|
|
69
|
+
`unsupported video codec '${info.codec}'${profile} — DICOM video ` +
|
|
70
|
+
"encapsulation supports H.264 Baseline/Main/High up to Level 4.2. " +
|
|
71
|
+
"Transcode first, e.g.: ffmpeg -i in.mp4 -c:v libx264 " +
|
|
72
|
+
"-profile:v high -level 4.2 -c:a copy out.mp4"
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The Video Photographic Image attributes that do not depend on the stream:
|
|
78
|
+
* XC modality, and the Image Pixel values that every MPEG-4 AVC transfer
|
|
79
|
+
* syntax mandates (PS3.5 §8.2.6); the stream carries the real subsampling.
|
|
80
|
+
*/
|
|
81
|
+
const videoPhotographicBase = {
|
|
82
|
+
SOPClassUID: VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
|
|
83
|
+
Modality: "XC",
|
|
84
|
+
SamplesPerPixel: 3,
|
|
85
|
+
PhotometricInterpretation: "YBR_PARTIAL_420",
|
|
86
|
+
PlanarConfiguration: 0,
|
|
87
|
+
BitsAllocated: 8,
|
|
88
|
+
BitsStored: 8,
|
|
89
|
+
HighBit: 7,
|
|
90
|
+
PixelRepresentation: 0,
|
|
91
|
+
LossyImageCompression: "01"
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The default base of `buildVideoDataset`: core instance defaults and the
|
|
96
|
+
* Video Photographic Image block. It has no `predecessorBase`, so
|
|
97
|
+
* `predecessor: true` has no effect; use
|
|
98
|
+
* `combineBases(videoBase, predecessorBase)` for a predecessor
|
|
99
|
+
* (CORE-USR-9). Use `.items` to build a variant.
|
|
100
|
+
*/
|
|
101
|
+
const videoBase = combineBases(defaultInstanceBase, videoPhotographicBase);
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Build the naturalized dataset shell for a Video Photographic Image
|
|
105
|
+
* instance — everything except PixelData, which the caller supplies either
|
|
106
|
+
* buffered (encapsulateVideo) or as a fragment event stream
|
|
107
|
+
* (createVideoEventSource).
|
|
108
|
+
*
|
|
109
|
+
* The dataset comes from {@link createInstance} with `videoBase`; the
|
|
110
|
+
* options follow CORE-USR-1 (`packages/core/README.md`), and the video rules
|
|
111
|
+
* are VID-USR-n in `packages/video/README.md`. The options object holds the
|
|
112
|
+
* controls; the DICOM attributes go in `options.overrides` (a naturalized
|
|
113
|
+
* DICOM provider with the forms of `baseDicom`). An extra option key has no
|
|
114
|
+
* effect (CORE-USR-7). With `dataLevel: "series"`, `instance` is the sample
|
|
115
|
+
* instance in the series (CORE-USR-5).
|
|
116
|
+
*
|
|
117
|
+
* The stream attributes are set last, and replace an override from each
|
|
118
|
+
* form of `overrides` (VID-USR-2): CineRate and FrameTime from the measured
|
|
119
|
+
* frame rate, NumberOfFrames, Rows, Columns, `_meta.TransferSyntaxUID`, and
|
|
120
|
+
* the (7FE0,0003) total length as a BigInt (VR UV is a uint64). A field
|
|
121
|
+
* that `mp4Info` does not give writes no attribute. The element list
|
|
122
|
+
* mirrors the Supplement 225 fixture.
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* buildVideoDataset(mp4Info, {
|
|
126
|
+
* instance,
|
|
127
|
+
* overrides: { SeriesDescription: "Endoscopy" }
|
|
128
|
+
* });
|
|
129
|
+
*
|
|
130
|
+
* @param {Object} mp4Info - parseMp4Info result
|
|
131
|
+
* @param {Object} [options] - the createInstance options (`baseDicom`
|
|
132
|
+
* defaults to `videoBase`; `overrides` holds the DICOM attributes;
|
|
133
|
+
* createInstance calls `postProcess` before the builder sets the stream
|
|
134
|
+
* attributes), plus the control option of the callers (`fragmentBytes`),
|
|
135
|
+
* which is ignored here
|
|
136
|
+
* @returns {Object} naturalized dataset with _meta/_vrMap, no PixelData
|
|
137
|
+
*/
|
|
138
|
+
function buildVideoDataset(mp4Info, options = {}) {
|
|
139
|
+
if (!mp4Info.transferSyntaxUID) {
|
|
140
|
+
throw unsupportedCodecError(mp4Info);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// fragmentBytes is a control key of the callers (CORE-IMP-9).
|
|
144
|
+
const { baseDicom = videoBase, fragmentBytes, ...rest } = options;
|
|
145
|
+
const dataset = createInstance({ baseDicom, ...rest });
|
|
146
|
+
|
|
147
|
+
const streamAttributes = {
|
|
148
|
+
CineRate: mp4Info.cineRate,
|
|
149
|
+
FrameTime: mp4Info.frameTime,
|
|
150
|
+
NumberOfFrames: mp4Info.numberOfFrames,
|
|
151
|
+
Rows: mp4Info.rows,
|
|
152
|
+
Columns: mp4Info.columns
|
|
153
|
+
};
|
|
154
|
+
for (const [keyword, value] of Object.entries(streamAttributes)) {
|
|
155
|
+
if (value !== undefined) {
|
|
156
|
+
dataset[keyword] = value;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
// Exact stream length, without the pad byte of an odd-length final
|
|
160
|
+
// fragment (Sup 225).
|
|
161
|
+
dataset.EncapsulatedPixelDataValueTotalLength = BigInt(
|
|
162
|
+
mp4Info.mp4ByteLength
|
|
163
|
+
);
|
|
164
|
+
// A copy that keeps the other _meta keys (CORE-USR-13).
|
|
165
|
+
dataset._meta = {
|
|
166
|
+
...(dataset._meta || {}),
|
|
167
|
+
TransferSyntaxUID: { Value: [mp4Info.transferSyntaxUID] }
|
|
168
|
+
};
|
|
169
|
+
dataset._vrMap = { ...(dataset._vrMap || {}), PixelData: "OB" };
|
|
170
|
+
return dataset;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Wrap MP4 bytes into a naturalized video instance, buffered: PixelData is an
|
|
175
|
+
* array of fragment-sized ArrayBuffer slices ready for datasetToDict /
|
|
176
|
+
* datasetToBuffer. For files too large to buffer, use
|
|
177
|
+
* createVideoEventSource instead.
|
|
178
|
+
*
|
|
179
|
+
* @param {ArrayBuffer|Uint8Array} mp4Bytes
|
|
180
|
+
* @param {Object} [options] - the buildVideoDataset options (the DICOM
|
|
181
|
+
* attributes go in `overrides`), plus `fragmentBytes`
|
|
182
|
+
* @returns {Promise<Object>} naturalized dataset
|
|
183
|
+
*/
|
|
184
|
+
async function encapsulateVideo(mp4Bytes, options = {}) {
|
|
185
|
+
const bytes =
|
|
186
|
+
mp4Bytes instanceof ArrayBuffer
|
|
187
|
+
? new Uint8Array(mp4Bytes)
|
|
188
|
+
: new Uint8Array(
|
|
189
|
+
mp4Bytes.buffer,
|
|
190
|
+
mp4Bytes.byteOffset,
|
|
191
|
+
mp4Bytes.byteLength
|
|
192
|
+
);
|
|
193
|
+
const info = await parseMp4Info(bytes);
|
|
194
|
+
const dataset = buildVideoDataset(info, options);
|
|
195
|
+
const fragmentBytes = normalizeFragmentBytes(options.fragmentBytes);
|
|
196
|
+
|
|
197
|
+
const fragments = [];
|
|
198
|
+
for (let offset = 0; offset < bytes.byteLength; offset += fragmentBytes) {
|
|
199
|
+
const end = Math.min(offset + fragmentBytes, bytes.byteLength);
|
|
200
|
+
// slice() so each fragment is an exact, unshared ArrayBuffer.
|
|
201
|
+
fragments.push(
|
|
202
|
+
bytes.buffer.slice(
|
|
203
|
+
bytes.byteOffset + offset,
|
|
204
|
+
bytes.byteOffset + end
|
|
205
|
+
)
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
dataset.PixelData = fragments;
|
|
209
|
+
return dataset;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Unwrap one naturalized binary payload to fragments of Uint8Array. */
|
|
213
|
+
function toFragmentList(payload) {
|
|
214
|
+
if (payload === undefined || payload === null) {
|
|
215
|
+
return [];
|
|
216
|
+
}
|
|
217
|
+
// A naturalized binary value is a list of fragments; DICOM JSON input
|
|
218
|
+
// can also give { InlineBinary } (a buffer, a view, base64, or a list).
|
|
219
|
+
if (
|
|
220
|
+
typeof payload === "object" &&
|
|
221
|
+
!(payload instanceof ArrayBuffer) &&
|
|
222
|
+
!ArrayBuffer.isView(payload) &&
|
|
223
|
+
!Array.isArray(payload) &&
|
|
224
|
+
payload.InlineBinary !== undefined
|
|
225
|
+
) {
|
|
226
|
+
payload = payload.InlineBinary;
|
|
227
|
+
}
|
|
228
|
+
const list = Array.isArray(payload) ? payload : [payload];
|
|
229
|
+
return list.map(fragment => {
|
|
230
|
+
if (typeof fragment === "string") {
|
|
231
|
+
const binary = atob(fragment);
|
|
232
|
+
const decoded = new Uint8Array(binary.length);
|
|
233
|
+
for (let i = 0; i < binary.length; i++) {
|
|
234
|
+
decoded[i] = binary.charCodeAt(i);
|
|
235
|
+
}
|
|
236
|
+
return decoded;
|
|
237
|
+
}
|
|
238
|
+
if (
|
|
239
|
+
fragment &&
|
|
240
|
+
typeof fragment === "object" &&
|
|
241
|
+
!(fragment instanceof ArrayBuffer) &&
|
|
242
|
+
!ArrayBuffer.isView(fragment) &&
|
|
243
|
+
fragment.InlineBinary !== undefined
|
|
244
|
+
) {
|
|
245
|
+
return toFragmentList(fragment)[0];
|
|
246
|
+
}
|
|
247
|
+
return ArrayBuffer.isView(fragment)
|
|
248
|
+
? new Uint8Array(
|
|
249
|
+
fragment.buffer,
|
|
250
|
+
fragment.byteOffset,
|
|
251
|
+
fragment.byteLength
|
|
252
|
+
)
|
|
253
|
+
: new Uint8Array(fragment);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The meta transfer syntax of a naturalized dataset, tolerant of shape. */
|
|
258
|
+
function metaTransferSyntax(dataset) {
|
|
259
|
+
const meta = dataset._meta;
|
|
260
|
+
if (!meta) {
|
|
261
|
+
return undefined;
|
|
262
|
+
}
|
|
263
|
+
const entry = meta.TransferSyntaxUID || meta["00020010"];
|
|
264
|
+
if (!entry) {
|
|
265
|
+
return undefined;
|
|
266
|
+
}
|
|
267
|
+
if (typeof entry === "string") {
|
|
268
|
+
return entry;
|
|
269
|
+
}
|
|
270
|
+
return Array.isArray(entry.Value) ? entry.Value[0] : entry.Value;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Recover the verbatim video stream from a naturalized video instance.
|
|
275
|
+
*
|
|
276
|
+
* Fragments are concatenated and the result truncated to the declared
|
|
277
|
+
* (7FE0,0003) total length, which drops the pad byte a Part 10 writer adds
|
|
278
|
+
* to an odd-length final fragment. When the element is absent (older
|
|
279
|
+
* producers), nothing is trimmed and `declaredLength` is null so the caller
|
|
280
|
+
* can decide how loudly to warn. A dataset that is not a video throws an
|
|
281
|
+
* error (VID-USR-6).
|
|
282
|
+
*
|
|
283
|
+
* @param {Object} dataset - naturalized video instance
|
|
284
|
+
* @returns {{ bytes: Uint8Array, transferSyntaxUID: string|undefined,
|
|
285
|
+
* declaredLength: number|null }}
|
|
286
|
+
*/
|
|
287
|
+
function extractEncapsulatedVideo(dataset) {
|
|
288
|
+
const transferSyntaxUID = metaTransferSyntax(dataset);
|
|
289
|
+
const isVideo =
|
|
290
|
+
dataset.SOPClassUID === VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID ||
|
|
291
|
+
isVideoTransferSyntax(transferSyntaxUID);
|
|
292
|
+
if (!isVideo || dataset.PixelData === undefined) {
|
|
293
|
+
throw new Error(
|
|
294
|
+
"extractEncapsulatedVideo: dataset is not an encapsulated video " +
|
|
295
|
+
"instance (expected SOP Class " +
|
|
296
|
+
VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID +
|
|
297
|
+
" or a video transfer syntax, with PixelData). " +
|
|
298
|
+
(transferSyntaxUID
|
|
299
|
+
? `Found transfer syntax ${transferSyntaxUID}. `
|
|
300
|
+
: "") +
|
|
301
|
+
"For an Encapsulated PDF use extractEncapsulatedPdf; for " +
|
|
302
|
+
"pixel images read the dataset with NaturalizedListener."
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const fragments = toFragmentList(dataset.PixelData);
|
|
307
|
+
const total = fragments.reduce((n, f) => n + f.byteLength, 0);
|
|
308
|
+
const out = new Uint8Array(total);
|
|
309
|
+
let offset = 0;
|
|
310
|
+
for (const fragment of fragments) {
|
|
311
|
+
out.set(fragment, offset);
|
|
312
|
+
offset += fragment.byteLength;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const declared = dataset.EncapsulatedPixelDataValueTotalLength;
|
|
316
|
+
const declaredLength =
|
|
317
|
+
declared === undefined || declared === null
|
|
318
|
+
? null
|
|
319
|
+
: Number(Array.isArray(declared) ? declared[0] : declared);
|
|
320
|
+
|
|
321
|
+
const bytes =
|
|
322
|
+
declaredLength !== null && declaredLength <= out.byteLength
|
|
323
|
+
? out.subarray(0, declaredLength)
|
|
324
|
+
: out;
|
|
325
|
+
|
|
326
|
+
return { bytes, transferSyntaxUID, declaredLength };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export {
|
|
330
|
+
videoBase,
|
|
331
|
+
videoPhotographicBase,
|
|
332
|
+
buildVideoDataset,
|
|
333
|
+
encapsulateVideo,
|
|
334
|
+
extractEncapsulatedVideo,
|
|
335
|
+
normalizeFragmentBytes,
|
|
336
|
+
VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
|
|
337
|
+
DEFAULT_FRAGMENT_BYTES
|
|
338
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// src/encapsulated/index.js — the video half of the encapsulated module.
|
|
2
|
+
// The PDF half (encapsulatePdf) is in @dcmjs-org/encapsulated.
|
|
3
|
+
import {
|
|
4
|
+
videoBase,
|
|
5
|
+
videoPhotographicBase,
|
|
6
|
+
buildVideoDataset,
|
|
7
|
+
encapsulateVideo,
|
|
8
|
+
extractEncapsulatedVideo,
|
|
9
|
+
VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
|
|
10
|
+
DEFAULT_FRAGMENT_BYTES
|
|
11
|
+
} from "./encapsulatedVideo.js";
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
videoBase,
|
|
15
|
+
videoPhotographicBase,
|
|
16
|
+
buildVideoDataset,
|
|
17
|
+
encapsulateVideo,
|
|
18
|
+
extractEncapsulatedVideo,
|
|
19
|
+
VIDEO_PHOTOGRAPHIC_SOP_CLASS_UID,
|
|
20
|
+
DEFAULT_FRAGMENT_BYTES
|
|
21
|
+
};
|
|
@@ -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";
|