@dcmjs-org/imaging 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 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,253 @@
1
- # Temporary Holding Version
1
+ # @dcmjs-org/imaging
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The codec-free image builder of dcmjs. This package is the image counterpart
4
+ of `@dcmjs-org/video`. It puts decoded pixels into a conformant DICOM image
5
+ instance. It also reads the headers of compressed streams. It does not decode
6
+ pixels, and it does not read MP4 containers. A consumer that builds only
7
+ image instances uses this package, and does not need the larger video
8
+ package.
9
+
10
+ - `buildImageDataset(decodedImage, options)` — wrap decoded pixels into a
11
+ naturalized image instance. The default is Secondary Capture (`OT`).
12
+ `SECONDARY_CAPTURE_SOP_CLASS_UID` and `imageBase` are exported with it.
13
+ - `derivedImageBase(derivedFrom, { lossy })` — a base block that marks the
14
+ image as derived. `buildImageDataset` adds it for `derivedFrom`, and a
15
+ caller can add it to a custom `baseDicom`.
16
+ - `derivedImageAttributes(derivedFrom, { lossy })` — the plain function
17
+ under `derivedImageBase`: `ImageType`, `SourceImageSequence`, and the
18
+ Lossy Image Compression attributes.
19
+ - `parseJpegInfo(bytes)` — gets the geometry, the photometric
20
+ interpretation, and the matching DICOM transfer syntax from the frame
21
+ header of a JPEG (IMG-USR-11). It does not decode the pixels.
22
+ - `h264TransferSyntaxUID(profileIdc, levelIdc)` — gives the DICOM transfer
23
+ syntax that can carry an AVC profile and level (Supplement 225), or
24
+ `null`.
25
+
26
+ `@dcmjs-org/video` puts compressed streams into DICOM. It also reads MP4
27
+ headers, and encapsulates and streams video. That package uses the shared
28
+ `h264TransferSyntaxUID` map of this package.
29
+
30
+ ## Options of `buildImageDataset`
31
+
32
+ The options follow CORE-USR-1 in `packages/core/README.md`: the
33
+ `createInstance` controls, `overrides`, and these control keys. All of
34
+ them are options. `overrides` is a naturalized DICOM provider with the
35
+ forms of `baseDicom`, and holds only DICOM attributes. A control key never
36
+ goes in `overrides`. An extra option key has no effect (CORE-USR-7).
37
+
38
+ - `baseDicom` (default `imageBase`) — base blocks. `imageBase` has no
39
+ `predecessorBase`, so `predecessor: true` needs a custom base
40
+ (IMG-USR-10).
41
+ - `derivedFrom` — a naturalized instance, or an array of them, that the
42
+ image is derived from. Each needs `SOPClassUID` and `SOPInstanceUID`. An
43
+ empty array is the same as no `derivedFrom`.
44
+ - `lossy` (default `true`) — `false`, or `{ method, ratio }`. It has an
45
+ effect only with `derivedFrom` (IMG-USR-8).
46
+ - `encapsulated` — `{ transferSyntaxUID, frames }`: pre-encoded frames, in
47
+ place of `decodedImage.pixels`.
48
+
49
+ The geometry fields of `decodedImage` (`rows`, `columns`, `samplesPerPixel`,
50
+ and the others of IMG-USR-2) have no default. A decoded value replaces the
51
+ value from the base, from `instance`, or from `overrides`. A field that the
52
+ decoded image does not give writes nothing, and that value stays. Give the
53
+ photometric attributes in `overrides` when the decoder does not give them.
54
+
55
+ ```js
56
+ const image = buildImageDataset(decodedImage, {
57
+ instance: priorInstanceInSeries,
58
+ dataLevel: "series",
59
+ derivedFrom: [sourceA, sourceB],
60
+ overrides: { BodyPartExamined: "CHEST" }
61
+ });
62
+
63
+ // The same derivation in a custom base:
64
+ const base = combineBases(imageBase, { Modality: "MR" });
65
+ const derived = buildImageDataset(decodedImage, {
66
+ baseDicom: combineBases(base, derivedImageBase(sourceA, { lossy: false }))
67
+ });
68
+ ```
69
+
70
+ ## Scope and change rule
71
+
72
+ The shared requirements of `createInstance` (CORE-USR-n, CORE-IMP-n in
73
+ `packages/core/README.md`) apply to `buildImageDataset`. This README lists
74
+ only the requirements of this package.
75
+
76
+ The change rule of the core README applies. Change a user requirement
77
+ (IMG-USR-n) only when it describes the behaviour wrongly, or when the
78
+ intended user-facing behaviour changes, and name the change in the pull
79
+ request. The implementation requirements (IMG-IMP-n) describe the current
80
+ approach, and can change freely. Do not renumber an identifier.
81
+
82
+ ## § User requirements
83
+
84
+ - **IMG-USR-1** `instance` is where the new image goes (CORE-USR-3). It is
85
+ not the source of a derivation. `derivedFrom` is the source of a
86
+ derivation, and it is a separate option.
87
+ - **IMG-USR-2** The geometry attributes are `Rows`, `Columns`,
88
+ `SamplesPerPixel`, `PhotometricInterpretation`, `BitsAllocated`,
89
+ `BitsStored`, `HighBit`, `PixelRepresentation`, `PlanarConfiguration`,
90
+ and `NumberOfFrames`. The builder sets the geometry that the decoded
91
+ input gives, and `PixelData`, after `createInstance`.
92
+ - The decoded input gives a value in these cases:
93
+ - A field of `decodedImage` (`rows`, `columns`, `samplesPerPixel`,
94
+ `photometricInterpretation`, `bitsAllocated`, `bitsStored`,
95
+ `highBit`, `pixelRepresentation`, `planarConfiguration`,
96
+ `numberOfFrames`) that is not `undefined`, `null`, or `""`.
97
+ - `BitsAllocated` always comes from the typed-array width of
98
+ `pixels`.
99
+ - `PixelRepresentation` is 1 for an `Int8Array`, an `Int16Array`,
100
+ or an `Int32Array` when `decodedImage` has no
101
+ `pixelRepresentation`.
102
+ - `NumberOfFrames` always comes from `encapsulated.frames.length`.
103
+ - `HighBit` is `bitsStored` - 1 when `decodedImage` has
104
+ `bitsStored` and has no `highBit`.
105
+ - The builder calculates no other value. For example, it does not
106
+ calculate `HighBit` from `BitsAllocated`, or from a `BitsStored`
107
+ of the base, of `instance`, or of `overrides`. It does not
108
+ calculate `BitsStored` from `BitsAllocated`.
109
+ - A decoded value replaces the base value, the inherited value, and the
110
+ override, with no warning. This rule applies to each form of
111
+ `overrides`, also to a function and to an array.
112
+ - The builder does not write a geometry attribute that the decoded
113
+ input does not give, and does not remove it. The value from the
114
+ base, from `instance`, or from `overrides` stays. Without one of
115
+ these, the result does not have the attribute. The builder writes
116
+ no default.
117
+ - The builder writes `PlanarConfiguration` only when the effective
118
+ `SamplesPerPixel` is more than 1. The builder writes `NumberOfFrames`
119
+ in three cases: the decoded count is more than 1,
120
+ `decodedImage.numberOfFrames` gives the count, or the dataset
121
+ already has a `NumberOfFrames`. Thus a count of 1 from
122
+ `encapsulated.frames.length` alone does not add `NumberOfFrames`.
123
+ - The builder checks the effective geometry before it writes the
124
+ geometry (IMG-USR-9).
125
+ - `_vrMap.PixelData` is `OW` for 16-bit native pixels, else `OB`.
126
+ Encapsulated frames always use `OB`.
127
+ - The `_meta` rule of CORE-USR-13 applies. For `encapsulated`, the
128
+ builder sets `_meta.TransferSyntaxUID` to the transfer syntax of the
129
+ frames. Without `encapsulated`, the builder sets Explicit VR Little
130
+ Endian only when the merged `_meta` has no `TransferSyntaxUID`. Thus
131
+ a `TransferSyntaxUID` override in `_meta` stays.
132
+ - **IMG-USR-3** With a non-empty `derivedFrom`, the result is a derived
133
+ image:
134
+ - `ImageType` is `DERIVED\SECONDARY`.
135
+ - `SourceImageSequence` has one item for each source, in order.
136
+ - `LossyImageCompression` is `"01"`. For `lossy: false` it is `"00"`,
137
+ but when a source has `"01"`, the result keeps `"01"`, because a lossy
138
+ image stays lossy (PS3.3 C.7.6.1.1.5).
139
+ - `LossyImageCompressionMethod` and `LossyImageCompressionRatio` keep
140
+ the history of the lossy steps (PS3.3 C.7.6.1.1.5). The values of each
141
+ lossy source come first, in `derivedFrom` order. Then come `method`
142
+ and `ratio` of a `lossy` object. One value is a plain value, and more
143
+ values are an array.
144
+ - PS3.3 C.7.6.1.1.5 pairs each ratio with the method at the same
145
+ position. When the result has ratios, and the number of ratios is not
146
+ the number of methods, the result has no `LossyImageCompressionRatio`.
147
+ The builder then logs one warning.
148
+ - `SOPClassUID` stays the value of the base (Secondary Capture for
149
+ `imageBase`).
150
+ - These values are base values (IMG-IMP-1). An inherited value or an
151
+ override replaces them (CORE-USR-6). For example, a custom `levels`
152
+ that inherits `ImageType` or `LossyImageCompression` gives the value
153
+ of `instance`, and not the derived value.
154
+ - An empty `derivedFrom` array is the same as no `derivedFrom`.
155
+ - **IMG-USR-4** Each `derivedFrom` item is a naturalized instance, full or
156
+ partial. The builder reads the DICOM keywords `SOPClassUID`,
157
+ `SOPInstanceUID`, and `LossyImageCompression`. An item without
158
+ `SOPClassUID` or `SOPInstanceUID` throws an error that names the absent
159
+ keyword.
160
+ - **IMG-USR-5** The default `ImageType` `ORIGINAL\PRIMARY` is a base value.
161
+ A custom base, the derivation, an inherited value, and an override each
162
+ replace it, in the order of CORE-USR-6. The default `ConversionType`
163
+ `WSD` is also a base value of `secondaryCaptureImageBase`. An override
164
+ replaces it, and an `undefined` override removes it (CORE-USR-8). A
165
+ custom base without `secondaryCaptureImageBase` gives no
166
+ `ConversionType`.
167
+ - **IMG-USR-6** The result never gets the `SOPInstanceUID` of
168
+ `derivedFrom`. With the default levels, the result does not get the
169
+ `SOPInstanceUID` of `instance` (CORE-USR-4). `overrides.SOPInstanceUID`
170
+ always wins.
171
+ - **IMG-USR-7** A caller can add `derivedImageBase(derivedFrom, { lossy })`
172
+ to a custom `baseDicom` (CORE-USR-11). The result is the same as with the
173
+ `derivedFrom` option. `derivedImageBase` and `derivedImageAttributes`
174
+ need at least one instance: an empty `derivedFrom` throws an error.
175
+ - **IMG-USR-8** `lossy` without `derivedFrom`, or with an empty
176
+ `derivedFrom`, has no effect.
177
+ - **IMG-USR-9** The functions throw an error for these input values
178
+ (CORE-IMP-11). `buildImageDataset` uses the effective values: the
179
+ decoded value, else the value of the merged dataset.
180
+
181
+ - `decodedImage.pixels` and `options.encapsulated` together.
182
+ - An `encapsulated` without `transferSyntaxUID`, or without frames.
183
+ - `Rows` or `Columns` that is not a positive integer. The decoded
184
+ input or the merged dataset must give them.
185
+ - `MONOCHROME1` or `MONOCHROME2` with a `SamplesPerPixel` that is not
186
+ 1.
187
+ - `RGB` or `YBR_*` with a `SamplesPerPixel` that is not 3.
188
+ - A `pixels` that is a `Float32Array` or a `Float64Array`. DICOM
189
+ integer pixel data needs an integer typed array.
190
+ - A `bitsAllocated` that is not the typed-array width of `pixels`.
191
+ - A `numberOfFrames` that is not `encapsulated.frames.length`.
192
+ - A byte length of `pixels` that is not `Rows` x `Columns` x
193
+ `SamplesPerPixel` x `NumberOfFrames` x `BitsAllocated` / 8.
194
+ - `parseJpegInfo`: bytes without the JPEG SOI marker, a JPEG without
195
+ a frame header (SOF), or a truncated SOF segment.
196
+
197
+ When a value that a check needs is absent from the decoded input and
198
+ from the merged dataset, the check uses a default. An absent
199
+ `SamplesPerPixel` is 1, and an absent `NumberOfFrames` is 1. The builder
200
+ does not write these defaults. Without a `PhotometricInterpretation`,
201
+ the builder skips the photometric check. IMG-USR-4 and IMG-USR-7 give
202
+ the errors of `derivedFrom`. The input type of `pixels` is a typed array
203
+ (CORE-USR-7).
204
+
205
+ - **IMG-USR-10** `imageBase` does not include `predecessorBase`
206
+ (CORE-USR-9). With the default base, `predecessor: true` has no effect:
207
+ the result has no `PredecessorDocumentsSequence`, and the builder throws
208
+ no predecessor error. For a predecessor, give
209
+ `baseDicom: combineBases(imageBase, predecessorBase)`, with
210
+ `predecessorBase` from `@dcmjs-org/core`.
211
+ - **IMG-USR-11** `parseJpegInfo` gives DICOM values that go directly into
212
+ the `decodedImage` of `buildImageDataset`:
213
+ - `bitsAllocated` is 8 for a sample precision of 8 or less, else 16.
214
+ `bitsStored` is the sample precision. (Before this rule,
215
+ `bitsAllocated` was the sample precision.)
216
+ - `photometricInterpretation` follows PS3.5 8.2.1: `MONOCHROME2` for
217
+ 1 component; for 3 components `RGB` when the data has no colour
218
+ transform (Adobe APP14 transform 0, the component IDs R, G, B, or a
219
+ lossless process), else `YBR_FULL` without chroma subsampling and
220
+ `YBR_FULL_422` with it. Another component count gives `null`.
221
+ - `transferSyntaxUID` is the baseline (SOF0), extended (SOF1), or
222
+ lossless (SOF3) transfer syntax, else `null`.
223
+
224
+ ## § Implementation requirements
225
+
226
+ - **IMG-IMP-1** `buildImageDataset` calls `createInstance`. For a non-empty
227
+ `derivedFrom`, the base is
228
+ `combineBases(baseDicom, derivedImageBase(derivedFrom, { lossy }))`, so
229
+ the merge stays base < inherited < overrides (CORE-IMP-4).
230
+ `buildImageDataset` removes its control keys `derivedFrom`, `lossy`, and
231
+ `encapsulated` before it calls `createInstance` (CORE-IMP-9), and passes
232
+ `overrides` and `postProcess` through without a change. Then
233
+ `buildImageDataset` checks the effective geometry, writes only the
234
+ decoded geometry of IMG-USR-2, and sets the pixel encoding. It removes
235
+ no geometry attribute.
236
+ - **IMG-IMP-2** `derivedImageAttributes` is the plain function under
237
+ `derivedImageBase`. The block calls it for each context, so each result
238
+ gets its own `SourceImageSequence`.
239
+ - **IMG-IMP-3** `imageBase` is `defaultInstanceBase`,
240
+ `secondaryCaptureImageBase` (SOP class, Modality `OT`, `ConversionType`
241
+ `WSD`, `ImageType`, `ContentDate`, `ContentTime`). `imageBase` has no
242
+ `predecessorBase` (IMG-USR-10). The builder writes no default after
243
+ `createInstance`.
244
+ - **IMG-IMP-4** NumberOfFrames: a single-frame IOD, for example Secondary
245
+ Capture, has no `NumberOfFrames`. For this reason a count of 1 from
246
+ `encapsulated.frames.length` alone is not written. A count that
247
+ `decodedImage` states is written, because the caller asks for it.
248
+
249
+ ## Dependencies
250
+
251
+ Builds only on `@dcmjs-org/core` (`createInstance`). The datasets it
252
+ produces are naturalized and serialize through the event-stream writers
253
+ (`@dcmjs-org/generator`) like any other.
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "@dcmjs-org/imaging",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-beta.4",
4
+ "description": "Lightweight, codec-free image building for dcmjs: turn already-decoded pixels into a conformant DICOM image instance, and inspect JPEG/H.264 headers without decoding. The heavy MP4/video processing lives in @dcmjs-org/video",
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/imaging"
15
+ },
16
+ "dependencies": {
17
+ "@dcmjs-org/core": "1.0.0-beta.4"
18
+ }
6
19
  }
@@ -0,0 +1,371 @@
1
+ // packages/imaging/src/buildImageDataset.js
2
+ //
3
+ // Build a full DICOM image instance from already-decoded pixels — the
4
+ // codec-free image primitive of dcmjs. dcmjs deliberately ships no PNG/JPEG
5
+ // codecs (browser + node compatible); callers decode with whatever fits
6
+ // their environment (Canvas, pngjs, ...) and hand over pixels plus
7
+ // geometry. Like encapsulate, this builds on createInstance and takes
8
+ // the same options (attributes in `overrides`, a naturalized DICOM
9
+ // provider), and returns a naturalized dataset ready for
10
+ // datasetToDict()/datasetToBuffer().
11
+
12
+ import {
13
+ combineBases,
14
+ createInstance,
15
+ defaultInstanceBase,
16
+ EXPLICIT_LITTLE_ENDIAN
17
+ } from "@dcmjs-org/core";
18
+ import { derivedImageBase } from "./derivedImageAttributes.js";
19
+
20
+ const SECONDARY_CAPTURE_SOP_CLASS_UID = "1.2.840.10008.5.1.4.1.1.7";
21
+
22
+ /**
23
+ * Secondary Capture identity, the default `ImageType` (ORIGINAL\PRIMARY),
24
+ * the SC Equipment `ConversionType` (WSD, workstation), and the Image module
25
+ * content date and time.
26
+ */
27
+ function secondaryCaptureImageBase(context) {
28
+ return {
29
+ SOPClassUID: SECONDARY_CAPTURE_SOP_CLASS_UID,
30
+ Modality: "OT",
31
+ ConversionType: "WSD",
32
+ ImageType: ["ORIGINAL", "PRIMARY"],
33
+ ContentDate: context.date,
34
+ ContentTime: context.time
35
+ };
36
+ }
37
+
38
+ /**
39
+ * The default base of `buildImageDataset`: core instance defaults and the
40
+ * Secondary Capture block. It has no `predecessorBase`, so
41
+ * `predecessor: true` has no effect; use
42
+ * `combineBases(imageBase, predecessorBase)` for a predecessor
43
+ * (CORE-USR-9). Use `.items` to build a variant.
44
+ */
45
+ const imageBase = combineBases(defaultInstanceBase, secondaryCaptureImageBase);
46
+
47
+ // The decodedImage field of each geometry keyword (IMG-USR-2).
48
+ const GEOMETRY_FIELDS = {
49
+ Rows: "rows",
50
+ Columns: "columns",
51
+ SamplesPerPixel: "samplesPerPixel",
52
+ PhotometricInterpretation: "photometricInterpretation",
53
+ BitsAllocated: "bitsAllocated",
54
+ BitsStored: "bitsStored",
55
+ HighBit: "highBit",
56
+ PixelRepresentation: "pixelRepresentation",
57
+ PlanarConfiguration: "planarConfiguration",
58
+ NumberOfFrames: "numberOfFrames"
59
+ };
60
+
61
+ const isPresent = value =>
62
+ value !== undefined && value !== null && value !== "";
63
+
64
+ /** The single value of a naturalized attribute, or undefined when empty. */
65
+ function singleValue(value) {
66
+ const single = Array.isArray(value) ? value[0] : value;
67
+ return isPresent(single) ? single : undefined;
68
+ }
69
+
70
+ /**
71
+ * Normalize a typed-array view to an exact ArrayBuffer. Another value is
72
+ * returned as it is; the function does not check the type (CORE-IMP-11).
73
+ */
74
+ function toExactArrayBuffer(bytes) {
75
+ if (ArrayBuffer.isView(bytes)) {
76
+ return bytes.buffer.slice(
77
+ bytes.byteOffset,
78
+ bytes.byteOffset + bytes.byteLength
79
+ );
80
+ }
81
+ return bytes;
82
+ }
83
+
84
+ /**
85
+ * The geometry that the decoded input gives (IMG-USR-2): each explicit
86
+ * `decodedImage` field, plus the values that the payload determines.
87
+ * `BitsAllocated` comes from the typed-array width of `pixels`,
88
+ * `PixelRepresentation` 1 from a signed typed array, and `NumberOfFrames`
89
+ * from `encapsulated.frames.length`. Without `decodedImage.highBit`, a
90
+ * decoded `bitsStored` gives `HighBit` = `bitsStored` - 1. The result has no
91
+ * key for a value that the decoded input does not give: the builder
92
+ * calculates no other value.
93
+ */
94
+ function decodedGeometry(decodedImage, encapsulated) {
95
+ const geometry = {};
96
+ for (const [keyword, field] of Object.entries(GEOMETRY_FIELDS)) {
97
+ if (isPresent(decodedImage[field])) {
98
+ geometry[keyword] = decodedImage[field];
99
+ }
100
+ }
101
+ if (geometry.HighBit === undefined && geometry.BitsStored !== undefined) {
102
+ geometry.HighBit = geometry.BitsStored - 1;
103
+ }
104
+ const { pixels } = decodedImage;
105
+ if (!encapsulated) {
106
+ // The typed array gives BitsAllocated and PixelRepresentation, so
107
+ // a float array would write integer pixels (IMG-USR-9).
108
+ if (pixels instanceof Float32Array || pixels instanceof Float64Array) {
109
+ throw new Error(
110
+ `buildImageDataset: decodedImage.pixels is a ` +
111
+ `${pixels.constructor.name}; DICOM integer pixel data ` +
112
+ `needs an integer typed array`
113
+ );
114
+ }
115
+ const elementBits = pixels.BYTES_PER_ELEMENT * 8;
116
+ if (
117
+ geometry.BitsAllocated !== undefined &&
118
+ geometry.BitsAllocated !== elementBits
119
+ ) {
120
+ throw new Error(
121
+ `buildImageDataset: bitsAllocated ${geometry.BitsAllocated} ` +
122
+ `does not match the ${elementBits}-bit typed array provided`
123
+ );
124
+ }
125
+ geometry.BitsAllocated = elementBits;
126
+ if (
127
+ geometry.PixelRepresentation === undefined &&
128
+ (pixels instanceof Int8Array ||
129
+ pixels instanceof Int16Array ||
130
+ pixels instanceof Int32Array)
131
+ ) {
132
+ geometry.PixelRepresentation = 1;
133
+ }
134
+ } else {
135
+ // The fragment list is the ground truth for the frame count. An
136
+ // explicit count that disagrees hides frames (review finding 10).
137
+ const frameCount = encapsulated.frames.length;
138
+ if (
139
+ geometry.NumberOfFrames !== undefined &&
140
+ geometry.NumberOfFrames !== frameCount
141
+ ) {
142
+ throw new Error(
143
+ `buildImageDataset: decodedImage.numberOfFrames ` +
144
+ `(${geometry.NumberOfFrames}) does not match ` +
145
+ `options.encapsulated.frames.length (${frameCount})`
146
+ );
147
+ }
148
+ geometry.NumberOfFrames = frameCount;
149
+ }
150
+ return geometry;
151
+ }
152
+
153
+ /**
154
+ * The requirement checks of IMG-USR-9 on the effective values: the decoded
155
+ * value, else the value of `dataset` (base, inherited, or override).
156
+ * `Rows` and `Columns` must be positive integers, so one of the two sources
157
+ * must give them. For another absent value, the check uses the old default
158
+ * only inside the computation, and does not write it: `SamplesPerPixel` 1
159
+ * and `NumberOfFrames` 1. The photometric check needs a
160
+ * `PhotometricInterpretation`.
161
+ */
162
+ function checkGeometry(geometry, dataset, pixels) {
163
+ const effective = keyword =>
164
+ geometry[keyword] !== undefined
165
+ ? geometry[keyword]
166
+ : singleValue(dataset[keyword]);
167
+ for (const keyword of ["Rows", "Columns"]) {
168
+ const value = effective(keyword);
169
+ if (!Number.isInteger(value) || value <= 0) {
170
+ throw new Error(
171
+ `buildImageDataset: ${keyword} must be a positive integer ` +
172
+ `(decodedImage.${GEOMETRY_FIELDS[keyword]}, or the ` +
173
+ `merged dataset), got ${value}`
174
+ );
175
+ }
176
+ }
177
+ const samplesPerPixel = effective("SamplesPerPixel") ?? 1;
178
+ const photometricInterpretation = effective("PhotometricInterpretation");
179
+
180
+ if (photometricInterpretation !== undefined) {
181
+ const monochrome = /^MONOCHROME[12]$/.test(photometricInterpretation);
182
+ const color = /^(RGB|YBR_)/.test(photometricInterpretation);
183
+ if (monochrome && samplesPerPixel !== 1) {
184
+ throw new Error(
185
+ `buildImageDataset: ${photometricInterpretation} requires ` +
186
+ `samplesPerPixel 1, got ${samplesPerPixel}`
187
+ );
188
+ }
189
+ if (color && samplesPerPixel !== 3) {
190
+ throw new Error(
191
+ `buildImageDataset: ${photometricInterpretation} requires ` +
192
+ `samplesPerPixel 3, got ${samplesPerPixel}`
193
+ );
194
+ }
195
+ }
196
+
197
+ if (!pixels) {
198
+ return;
199
+ }
200
+ const rows = effective("Rows");
201
+ const columns = effective("Columns");
202
+ const numberOfFrames = effective("NumberOfFrames") ?? 1;
203
+ // Native pixels always give BitsAllocated (decodedGeometry).
204
+ const bitsAllocated = geometry.BitsAllocated;
205
+ const expected =
206
+ rows * columns * samplesPerPixel * numberOfFrames * (bitsAllocated / 8);
207
+ if (pixels.byteLength !== expected) {
208
+ throw new Error(
209
+ `buildImageDataset: pixel buffer is ${pixels.byteLength} ` +
210
+ `bytes but ${rows}x${columns}x${samplesPerPixel}` +
211
+ `${numberOfFrames > 1 ? `x${numberOfFrames} frames` : ""} at ` +
212
+ `${bitsAllocated} bits needs ${expected} — fix the geometry ` +
213
+ `or the decode`
214
+ );
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Build a naturalized DICOM image dataset from decoded pixels with
220
+ * {@link createInstance}, then set the pixel data.
221
+ *
222
+ * The options follow CORE-USR-1 (`packages/core/README.md`); the image rules
223
+ * are IMG-USR-n in `packages/imaging/README.md`. The options object holds
224
+ * the controls; the DICOM attributes go in `options.overrides`, a
225
+ * naturalized DICOM provider with the forms of `baseDicom`. An extra option
226
+ * key has no effect (CORE-USR-7). With `dataLevel: "series"`, `instance` is
227
+ * the sample instance in the series (CORE-USR-5).
228
+ *
229
+ * For a non-empty `derivedFrom`, the base is
230
+ * `combineBases(baseDicom, derivedImageBase(derivedFrom, { lossy }))`
231
+ * (IMG-IMP-1). The builder removes its control keys `derivedFrom`, `lossy`,
232
+ * and `encapsulated` before the call (CORE-IMP-9). After the call, it
233
+ * checks the effective geometry (IMG-USR-9), writes only the geometry that
234
+ * the decoded input gives (IMG-USR-2), and sets the pixel encoding and
235
+ * `PixelData`.
236
+ *
237
+ * @example
238
+ * buildImageDataset(decodedImage, {
239
+ * instance,
240
+ * derivedFrom: source,
241
+ * overrides: { SeriesDescription: "Thumbnail" }
242
+ * });
243
+ *
244
+ * @param {Object} decodedImage - the decoded pixels and geometry. Each
245
+ * geometry field has no default. A field that is not given writes
246
+ * nothing, and the value of the base, `instance`, or `overrides` stays.
247
+ * @param {Uint8Array|Int8Array|Uint16Array|Int16Array} [decodedImage.pixels]
248
+ * interleaved decoded samples in an integer typed array; required unless
249
+ * options.encapsulated
250
+ * @param {number} [decodedImage.rows] else the merged `Rows`
251
+ * @param {number} [decodedImage.columns] else the merged `Columns`
252
+ * @param {number} [decodedImage.samplesPerPixel]
253
+ * @param {string} [decodedImage.photometricInterpretation]
254
+ * @param {number} [decodedImage.bitsAllocated] must match the typed-array
255
+ * width of `pixels`, which always gives `BitsAllocated`
256
+ * @param {number} [decodedImage.bitsStored]
257
+ * @param {number} [decodedImage.highBit] else `bitsStored` - 1 when
258
+ * `decodedImage.bitsStored` is given
259
+ * @param {number} [decodedImage.pixelRepresentation] else 1 for a signed
260
+ * typed array
261
+ * @param {number} [decodedImage.planarConfiguration] written only when the
262
+ * effective `SamplesPerPixel` is more than 1
263
+ * @param {number} [decodedImage.numberOfFrames] must match
264
+ * `encapsulated.frames.length`, which always gives `NumberOfFrames`
265
+ * @param {Object} [options] - the {@link createInstance} options
266
+ * (`instance`, `dataLevel`, `levels`, `predecessor`, `postProcess`,
267
+ * `overrides`), plus:
268
+ * @param {*} [options.baseDicom=imageBase] - base blocks
269
+ * @param {Object|Object[]} [options.derivedFrom] - the naturalized
270
+ * instance(s) that the image is derived from; each needs SOPClassUID and
271
+ * SOPInstanceUID. An empty array is the same as no `derivedFrom`.
272
+ * @param {boolean|{method: string, ratio: number}} [options.lossy=true] -
273
+ * the lossy compression of a derivation; no effect without `derivedFrom`
274
+ * @param {{transferSyntaxUID: string, frames: Array}} [options.encapsulated]
275
+ * - pre-encoded frames and their transfer syntax, in place of pixels
276
+ * @returns {Object} naturalized dataset with _meta and _vrMap
277
+ */
278
+ function buildImageDataset(decodedImage = {}, options = {}) {
279
+ const {
280
+ baseDicom = imageBase,
281
+ derivedFrom,
282
+ lossy,
283
+ encapsulated,
284
+ ...rest
285
+ } = options;
286
+ if (decodedImage.pixels && encapsulated) {
287
+ throw new Error(
288
+ "buildImageDataset: pass either decodedImage.pixels or " +
289
+ "options.encapsulated, not both"
290
+ );
291
+ }
292
+
293
+ // The transfer syntax and the frames are used below (IMG-USR-9).
294
+ if (
295
+ encapsulated &&
296
+ (!encapsulated.transferSyntaxUID || !encapsulated.frames?.length)
297
+ ) {
298
+ throw new Error(
299
+ "buildImageDataset: options.encapsulated needs " +
300
+ "{ transferSyntaxUID, frames: [bytes, ...] }"
301
+ );
302
+ }
303
+
304
+ const geometry = decodedGeometry(decodedImage, encapsulated);
305
+
306
+ const sources = [].concat(derivedFrom ?? []);
307
+ const dataset = createInstance({
308
+ ...rest,
309
+ baseDicom: sources.length
310
+ ? combineBases(baseDicom, derivedImageBase(sources, { lossy }))
311
+ : baseDicom
312
+ });
313
+ checkGeometry(geometry, dataset, !encapsulated && decodedImage.pixels);
314
+
315
+ // A decoded value replaces the base, inherited, or override value. A
316
+ // value that the decoded input does not give stays (IMG-USR-2).
317
+ const { PlanarConfiguration, NumberOfFrames, ...always } = geometry;
318
+ Object.assign(dataset, always);
319
+ if (
320
+ PlanarConfiguration !== undefined &&
321
+ singleValue(dataset.SamplesPerPixel) > 1
322
+ ) {
323
+ dataset.PlanarConfiguration = PlanarConfiguration;
324
+ }
325
+ // A single-frame IOD has no NumberOfFrames, so a frame count of 1 from
326
+ // frames.length is written only to replace an existing value.
327
+ if (
328
+ NumberOfFrames !== undefined &&
329
+ (NumberOfFrames > 1 ||
330
+ isPresent(decodedImage.numberOfFrames) ||
331
+ isPresent(dataset.NumberOfFrames))
332
+ ) {
333
+ dataset.NumberOfFrames = NumberOfFrames;
334
+ }
335
+ // Encapsulated pixel data is always OB (PS3.5 A.4).
336
+ dataset._vrMap = {
337
+ ...(dataset._vrMap || {}),
338
+ PixelData:
339
+ !encapsulated && singleValue(dataset.BitsAllocated) === 16
340
+ ? "OW"
341
+ : "OB"
342
+ };
343
+ // instanceBase supplies Explicit VR Little Endian; set the transfer
344
+ // syntax only for encapsulated frames, or when the merged _meta has no
345
+ // transfer syntax. The copy keeps overrides._meta of the caller
346
+ // unchanged (CORE-USR-13).
347
+ const hasTransferSyntax = Boolean(dataset._meta?.TransferSyntaxUID);
348
+ dataset._meta = { ...(dataset._meta || {}) };
349
+ if (encapsulated || !hasTransferSyntax) {
350
+ dataset._meta.TransferSyntaxUID = {
351
+ Value: [
352
+ encapsulated
353
+ ? encapsulated.transferSyntaxUID
354
+ : EXPLICIT_LITTLE_ENDIAN
355
+ ]
356
+ };
357
+ }
358
+
359
+ dataset.PixelData = encapsulated
360
+ ? encapsulated.frames.map(frame => toExactArrayBuffer(frame))
361
+ : toExactArrayBuffer(decodedImage.pixels);
362
+
363
+ return dataset;
364
+ }
365
+
366
+ export {
367
+ buildImageDataset,
368
+ imageBase,
369
+ secondaryCaptureImageBase,
370
+ SECONDARY_CAPTURE_SOP_CLASS_UID
371
+ };
@@ -0,0 +1,126 @@
1
+ // packages/imaging/src/derivedImageAttributes.js
2
+ //
3
+ // The attributes that mark an image as derived from other images, and the
4
+ // base block that adds them to a composition.
5
+
6
+ import { log } from "@dcmjs-org/core";
7
+
8
+ const REQUIRED_KEYS = ["SOPClassUID", "SOPInstanceUID"];
9
+
10
+ /** True when a source says that it was lossy compressed ("01"). */
11
+ function isLossySource(source) {
12
+ return [].concat(source.LossyImageCompression).includes("01");
13
+ }
14
+
15
+ /** The derivedFrom list; an empty list throws. */
16
+ function sourceList(derivedFrom, caller) {
17
+ const sources = [].concat(derivedFrom ?? []);
18
+ if (!sources.length) {
19
+ throw new Error(`${caller}: derivedFrom needs at least one instance`);
20
+ }
21
+ return sources;
22
+ }
23
+
24
+ /** The values of a multi-valued attribute as a list, without empty values. */
25
+ function valueList(value) {
26
+ return [].concat(value ?? []).filter(item => item !== "" && item !== null);
27
+ }
28
+
29
+ /** One value as itself, several values as an array, none as undefined. */
30
+ function multiValue(values) {
31
+ return values.length > 1 ? values : values[0];
32
+ }
33
+
34
+ /**
35
+ * The attributes of an image that is derived from other images. The function
36
+ * returns only these attributes; it does not change any input.
37
+ *
38
+ * - `ImageType`: `["DERIVED", "SECONDARY"]`.
39
+ * - `SourceImageSequence`: one item for each `derivedFrom` instance, in
40
+ * order, with `ReferencedSOPClassUID` and `ReferencedSOPInstanceUID`.
41
+ * - `LossyImageCompression`: `"01"` by default, `"00"` for `lossy: false`.
42
+ * When a source has `"01"`, the result is `"01"` also for `lossy: false`,
43
+ * because a lossy image stays lossy (PS3.3 C.7.6.1.1.5).
44
+ * - `LossyImageCompressionMethod` and `LossyImageCompressionRatio`: the
45
+ * values of each lossy source, in `derivedFrom` order, then `method` and
46
+ * `ratio` of a `lossy` object (PS3.3 C.7.6.1.1.5 keeps every lossy step).
47
+ * One value is a plain value; more values are an array. When the
48
+ * number of ratios differs from the number of methods, the result has no
49
+ * ratio, and the function logs a warning.
50
+ *
51
+ * Each `derivedFrom` item is a naturalized instance, full or partial. It must
52
+ * have `SOPClassUID` and `SOPInstanceUID`; the function throws an error that
53
+ * names a missing keyword. An empty `derivedFrom` throws.
54
+ *
55
+ * @param {Object|Object[]} derivedFrom - the source instance(s), at least one
56
+ * @param {Object} [options]
57
+ * @param {boolean|{method: string, ratio: number}} [options.lossy=true]
58
+ * @returns {Object} the derived-image attributes
59
+ */
60
+ export function derivedImageAttributes(derivedFrom, { lossy } = {}) {
61
+ const sources = sourceList(derivedFrom, "derivedImageAttributes");
62
+ const SourceImageSequence = sources.map((source, index) => {
63
+ const missing = REQUIRED_KEYS.filter(key => !source?.[key]);
64
+ if (missing.length) {
65
+ throw new Error(
66
+ `derivedImageAttributes: derivedFrom[${index}] is missing ` +
67
+ `${missing.join(" and ")}; each derivedFrom instance ` +
68
+ `needs SOPClassUID and SOPInstanceUID`
69
+ );
70
+ }
71
+ return {
72
+ ReferencedSOPClassUID: source.SOPClassUID,
73
+ ReferencedSOPInstanceUID: source.SOPInstanceUID
74
+ };
75
+ });
76
+
77
+ const lossySources = sources.filter(isLossySource);
78
+ const lossless = lossy === false && !lossySources.length;
79
+ const attributes = {
80
+ ImageType: ["DERIVED", "SECONDARY"],
81
+ SourceImageSequence,
82
+ LossyImageCompression: lossless ? "00" : "01"
83
+ };
84
+ const detail = lossy && typeof lossy === "object" ? lossy : {};
85
+ const methods = lossySources.flatMap(source =>
86
+ valueList(source.LossyImageCompressionMethod)
87
+ );
88
+ const ratios = lossySources.flatMap(source =>
89
+ valueList(source.LossyImageCompressionRatio)
90
+ );
91
+ methods.push(...valueList(detail.method));
92
+ ratios.push(...valueList(detail.ratio));
93
+ if (methods.length) {
94
+ attributes.LossyImageCompressionMethod = multiValue(methods);
95
+ }
96
+ if (ratios.length === methods.length) {
97
+ if (ratios.length) {
98
+ attributes.LossyImageCompressionRatio = multiValue(ratios);
99
+ }
100
+ } else if (ratios.length) {
101
+ log.warn(
102
+ `derivedImageAttributes: ${methods.length} lossy method(s) and ` +
103
+ `${ratios.length} ratio(s) do not pair; the result has no ` +
104
+ `LossyImageCompressionRatio`
105
+ );
106
+ }
107
+ return attributes;
108
+ }
109
+
110
+ /**
111
+ * A base block that adds {@link derivedImageAttributes} to a composition, in
112
+ * the same shape as `nextSeriesNumberBase`. Put it after the block that sets
113
+ * the default `ImageType` (`secondaryCaptureImageBase`), so that the derived
114
+ * `ImageType` replaces the default. `buildImageDataset` adds it for
115
+ * `derivedFrom`; a caller can also add it to a custom `baseDicom`. An empty
116
+ * `derivedFrom` throws when the block is made.
117
+ *
118
+ * @param {Object|Object[]} derivedFrom - the source instance(s), at least one
119
+ * @param {Object} [options]
120
+ * @param {boolean|{method: string, ratio: number}} [options.lossy=true]
121
+ * @returns {Function} a base block
122
+ */
123
+ export function derivedImageBase(derivedFrom, { lossy } = {}) {
124
+ const sources = sourceList(derivedFrom, "derivedImageBase");
125
+ return () => derivedImageAttributes(sources, { lossy });
126
+ }
package/src/h264.js ADDED
@@ -0,0 +1,39 @@
1
+ // packages/imaging/src/h264.js
2
+ //
3
+ // H.264 profile/level → DICOM transfer syntax mapping. Pure lookup, no codec
4
+ // and no MP4 container knowledge — just the rule that says which encapsulated
5
+ // transfer syntax can carry a given AVC stream (Supplement 225). Lives in
6
+ // imaging because it's shared: video's MP4 header inspection uses it to label
7
+ // a stream, and image builders can use it too.
8
+
9
+ // Fragmentable MPEG-4 AVC/H.264 High Profile transfer syntaxes (Sup 225).
10
+ // The fragmentable ".1" family is always chosen because the encapsulation
11
+ // writer emits the stream as N >= 1 fragments.
12
+ const H264_HIGH_41_FRAGMENTABLE = "1.2.840.10008.1.2.4.102.1";
13
+ const H264_HIGH_42_FRAGMENTABLE = "1.2.840.10008.1.2.4.104.1";
14
+
15
+ // AVC profile_idc values that fit inside the "High Profile" transfer
16
+ // syntaxes: Baseline (66) and Main (77) are strict subsets of High (100).
17
+ const H264_SUPPORTED_PROFILES = new Set([66, 77, 100]);
18
+
19
+ /**
20
+ * Map an AVC profile/level pair to the DICOM transfer syntax that carries it,
21
+ * or null when no defined syntax fits (High-10/422/444 profiles, levels above
22
+ * 4.2, HEVC, ...). level_idc is the H.264 level times ten (41 = Level 4.1).
23
+ *
24
+ * @param {number} profileIdc
25
+ * @param {number} levelIdc
26
+ * @returns {string|null}
27
+ */
28
+ export function h264TransferSyntaxUID(profileIdc, levelIdc) {
29
+ if (!H264_SUPPORTED_PROFILES.has(profileIdc)) {
30
+ return null;
31
+ }
32
+ if (levelIdc <= 41) {
33
+ return H264_HIGH_41_FRAGMENTABLE;
34
+ }
35
+ if (levelIdc === 42) {
36
+ return H264_HIGH_42_FRAGMENTABLE;
37
+ }
38
+ return null;
39
+ }
package/src/index.js ADDED
@@ -0,0 +1,18 @@
1
+ // The public surface of @dcmjs-org/imaging: lightweight, codec-free image
2
+ // building and header inspection. buildImageDataset turns already-decoded
3
+ // pixels into a conformant image instance; parseJpegInfo recovers geometry
4
+ // from JPEG bytes without decoding; h264TransferSyntaxUID maps an AVC
5
+ // profile/level to its DICOM transfer syntax. Depends only on
6
+ // @dcmjs-org/core — the heavy MP4/video processing lives in @dcmjs-org/video.
7
+ export {
8
+ buildImageDataset,
9
+ imageBase,
10
+ secondaryCaptureImageBase,
11
+ SECONDARY_CAPTURE_SOP_CLASS_UID
12
+ } from "./buildImageDataset.js";
13
+ export {
14
+ derivedImageAttributes,
15
+ derivedImageBase
16
+ } from "./derivedImageAttributes.js";
17
+ export { parseJpegInfo } from "./jpegInfo.js";
18
+ export { h264TransferSyntaxUID } from "./h264.js";
@@ -0,0 +1,154 @@
1
+ // src/image/jpegInfo.js
2
+ //
3
+ // Minimal JPEG header inspection: read the SOF (start-of-frame) segment to
4
+ // recover the geometry DICOM needs (Rows/Columns/SamplesPerPixel/precision)
5
+ // and identify the matching transfer syntax — WITHOUT decoding any pixels.
6
+ // JPEG is a legal DICOM transfer syntax, so JPEG bytes can be carried as
7
+ // encapsulated PixelData verbatim; only the frame header must be understood.
8
+
9
+ const JPEG_BASELINE_TS = "1.2.840.10008.1.2.4.50"; // SOF0, process 1
10
+ const JPEG_EXTENDED_TS = "1.2.840.10008.1.2.4.51"; // SOF1, processes 2 & 4
11
+ const JPEG_LOSSLESS_TS = "1.2.840.10008.1.2.4.57"; // SOF3, process 14
12
+
13
+ const LOSSLESS_SOF_MARKERS = new Set([0xc3, 0xc7, 0xcb, 0xcf]);
14
+ const RGB_COMPONENT_IDS = [0x52, 0x47, 0x42]; // "R", "G", "B"
15
+
16
+ /**
17
+ * The PhotometricInterpretation of the compressed data (PS3.5 8.2.1), or
18
+ * null when DICOM has no value for it (for example 4-component CMYK).
19
+ *
20
+ * - 1 component: MONOCHROME2.
21
+ * - 3 components: RGB when the data has no colour transform, that is an
22
+ * Adobe APP14 transform of 0, the component IDs "R", "G", "B", or a
23
+ * lossless process. Otherwise YBR_FULL when no component is subsampled,
24
+ * and YBR_FULL_422 when the chroma is subsampled.
25
+ */
26
+ function photometricInterpretation(sofMarker, components, adobeTransform) {
27
+ if (components.length === 1) {
28
+ return "MONOCHROME2";
29
+ }
30
+ if (components.length !== 3) {
31
+ return null;
32
+ }
33
+ const isRgb =
34
+ adobeTransform === 0 ||
35
+ (adobeTransform === undefined &&
36
+ components.every((c, i) => c.id === RGB_COMPONENT_IDS[i])) ||
37
+ (adobeTransform === undefined && LOSSLESS_SOF_MARKERS.has(sofMarker));
38
+ if (isRgb) {
39
+ return "RGB";
40
+ }
41
+ const subsampled = components.some(
42
+ c => c.sampling !== components[0].sampling
43
+ );
44
+ return subsampled ? "YBR_FULL_422" : "YBR_FULL";
45
+ }
46
+
47
+ /**
48
+ * Read the JPEG frame header. The DICOM values are ready for
49
+ * buildImageDataset: `bitsAllocated` is 8 or 16, `bitsStored` is the sample
50
+ * precision, and `photometricInterpretation` follows PS3.5 8.2.1.
51
+ *
52
+ * @param {Uint8Array} bytes - JPEG file bytes (SOI onward)
53
+ * @returns {{ rows, columns, samplesPerPixel, bitsAllocated, bitsStored,
54
+ * photometricInterpretation: string|null,
55
+ * transferSyntaxUID: string|null, sofMarker: number }}
56
+ * @throws on non-JPEG input or a missing frame header
57
+ */
58
+ export function parseJpegInfo(bytes) {
59
+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) {
60
+ throw new Error("parseJpegInfo: input is not JPEG (missing SOI)");
61
+ }
62
+
63
+ let adobeTransform;
64
+ let offset = 2;
65
+ while (offset + 4 <= bytes.length) {
66
+ if (bytes[offset] !== 0xff) {
67
+ offset++;
68
+ continue;
69
+ }
70
+ const marker = bytes[offset + 1];
71
+ // standalone markers without a length field
72
+ if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
73
+ offset += 2;
74
+ continue;
75
+ }
76
+ if (marker === 0xd9 || marker === 0xda) {
77
+ break; // EOI or start-of-scan: no SOF was seen
78
+ }
79
+ const length = (bytes[offset + 2] << 8) | bytes[offset + 3];
80
+
81
+ // APP14 "Adobe": the transform byte follows "Adobe", the version,
82
+ // and two flag words.
83
+ if (
84
+ marker === 0xee &&
85
+ length >= 14 &&
86
+ offset + 2 + length <= bytes.length &&
87
+ String.fromCharCode(...bytes.subarray(offset + 4, offset + 9)) ===
88
+ "Adobe"
89
+ ) {
90
+ adobeTransform = bytes[offset + 15];
91
+ }
92
+
93
+ // SOF0-SOF15, excluding DHT (C4), JPG (C8), DAC (CC)
94
+ const isSof =
95
+ marker >= 0xc0 &&
96
+ marker <= 0xcf &&
97
+ marker !== 0xc4 &&
98
+ marker !== 0xc8 &&
99
+ marker !== 0xcc;
100
+ if (isSof) {
101
+ // The six SOF fields span bytes[offset+4 .. offset+9], and the
102
+ // declared segment must fit inside the input. Out-of-range reads
103
+ // coerce to 0 in the bitwise math below, so a truncated JPEG
104
+ // would silently return wrong geometry (review finding 9).
105
+ const p = offset + 4;
106
+ const samplesPerPixel = bytes[p + 5];
107
+ if (
108
+ length < 8 + 3 * (samplesPerPixel || 0) ||
109
+ offset + 2 + length > bytes.length
110
+ ) {
111
+ throw new Error(
112
+ "parseJpegInfo: truncated SOF segment — the frame header does not fit in the input"
113
+ );
114
+ }
115
+ const components = [];
116
+ for (let i = 0; i < samplesPerPixel; i++) {
117
+ components.push({
118
+ id: bytes[p + 6 + 3 * i],
119
+ sampling: bytes[p + 7 + 3 * i]
120
+ });
121
+ }
122
+ const precision = bytes[p];
123
+ const info = {
124
+ sofMarker: marker,
125
+ bitsAllocated: precision > 8 ? 16 : 8,
126
+ bitsStored: precision,
127
+ rows: (bytes[p + 1] << 8) | bytes[p + 2],
128
+ columns: (bytes[p + 3] << 8) | bytes[p + 4],
129
+ samplesPerPixel,
130
+ photometricInterpretation: photometricInterpretation(
131
+ marker,
132
+ components,
133
+ adobeTransform
134
+ ),
135
+ transferSyntaxUID: null
136
+ };
137
+ if (marker === 0xc0) {
138
+ info.transferSyntaxUID = JPEG_BASELINE_TS;
139
+ } else if (marker === 0xc1) {
140
+ info.transferSyntaxUID = JPEG_EXTENDED_TS;
141
+ } else if (marker === 0xc3) {
142
+ info.transferSyntaxUID = JPEG_LOSSLESS_TS;
143
+ }
144
+ // other SOFs (progressive C2, arithmetic, hierarchical) have no
145
+ // DICOM transfer syntax — transferSyntaxUID stays null and the
146
+ // caller decides how loudly to complain.
147
+ return info;
148
+ }
149
+ offset += 2 + length;
150
+ }
151
+ throw new Error(
152
+ "parseJpegInfo: no frame header (SOF) found — truncated or invalid JPEG"
153
+ );
154
+ }