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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,683 @@
1
+ import { log, combineBases, defaultInstanceBase, createInstance, EXPLICIT_LITTLE_ENDIAN } from '@dcmjs-org/core';
2
+
3
+ // packages/imaging/src/derivedImageAttributes.js
4
+ //
5
+ // The attributes that mark an image as derived from other images, and the
6
+ // base block that adds them to a composition.
7
+
8
+
9
+ const REQUIRED_KEYS = ["SOPClassUID", "SOPInstanceUID"];
10
+
11
+ /** True when a source says that it was lossy compressed ("01"). */
12
+ function isLossySource(source) {
13
+ return [].concat(source.LossyImageCompression).includes("01");
14
+ }
15
+
16
+ /** The derivedFrom list; an empty list throws. */
17
+ function sourceList(derivedFrom, caller) {
18
+ const sources = [].concat(derivedFrom ?? []);
19
+ if (!sources.length) {
20
+ throw new Error(`${caller}: derivedFrom needs at least one instance`);
21
+ }
22
+ return sources;
23
+ }
24
+
25
+ /** The values of a multi-valued attribute as a list, without empty values. */
26
+ function valueList(value) {
27
+ return [].concat(value ?? []).filter(item => item !== "" && item !== null);
28
+ }
29
+
30
+ /** One value as itself, several values as an array, none as undefined. */
31
+ function multiValue(values) {
32
+ return values.length > 1 ? values : values[0];
33
+ }
34
+
35
+ /**
36
+ * The attributes of an image that is derived from other images. The function
37
+ * returns only these attributes; it does not change any input.
38
+ *
39
+ * - `ImageType`: `["DERIVED", "SECONDARY"]`.
40
+ * - `SourceImageSequence`: one item for each `derivedFrom` instance, in
41
+ * order, with `ReferencedSOPClassUID` and `ReferencedSOPInstanceUID`.
42
+ * - `LossyImageCompression`: `"01"` by default, `"00"` for `lossy: false`.
43
+ * When a source has `"01"`, the result is `"01"` also for `lossy: false`,
44
+ * because a lossy image stays lossy (PS3.3 C.7.6.1.1.5).
45
+ * - `LossyImageCompressionMethod` and `LossyImageCompressionRatio`: the
46
+ * values of each lossy source, in `derivedFrom` order, then `method` and
47
+ * `ratio` of a `lossy` object (PS3.3 C.7.6.1.1.5 keeps every lossy step).
48
+ * One value is a plain value; more values are an array. When the
49
+ * number of ratios differs from the number of methods, the result has no
50
+ * ratio, and the function logs a warning.
51
+ *
52
+ * Each `derivedFrom` item is a naturalized instance, full or partial. It must
53
+ * have `SOPClassUID` and `SOPInstanceUID`; the function throws an error that
54
+ * names a missing keyword. An empty `derivedFrom` throws.
55
+ *
56
+ * @param {Object|Object[]} derivedFrom - the source instance(s), at least one
57
+ * @param {Object} [options]
58
+ * @param {boolean|{method: string, ratio: number}} [options.lossy=true]
59
+ * @returns {Object} the derived-image attributes
60
+ */
61
+ function derivedImageAttributes(derivedFrom, { lossy } = {}) {
62
+ const sources = sourceList(derivedFrom, "derivedImageAttributes");
63
+ const SourceImageSequence = sources.map((source, index) => {
64
+ const missing = REQUIRED_KEYS.filter(key => !source?.[key]);
65
+ if (missing.length) {
66
+ throw new Error(
67
+ `derivedImageAttributes: derivedFrom[${index}] is missing ` +
68
+ `${missing.join(" and ")}; each derivedFrom instance ` +
69
+ `needs SOPClassUID and SOPInstanceUID`
70
+ );
71
+ }
72
+ return {
73
+ ReferencedSOPClassUID: source.SOPClassUID,
74
+ ReferencedSOPInstanceUID: source.SOPInstanceUID
75
+ };
76
+ });
77
+
78
+ const lossySources = sources.filter(isLossySource);
79
+ const lossless = lossy === false && !lossySources.length;
80
+ const attributes = {
81
+ ImageType: ["DERIVED", "SECONDARY"],
82
+ SourceImageSequence,
83
+ LossyImageCompression: lossless ? "00" : "01"
84
+ };
85
+ const detail = lossy && typeof lossy === "object" ? lossy : {};
86
+ const methods = lossySources.flatMap(source =>
87
+ valueList(source.LossyImageCompressionMethod)
88
+ );
89
+ const ratios = lossySources.flatMap(source =>
90
+ valueList(source.LossyImageCompressionRatio)
91
+ );
92
+ methods.push(...valueList(detail.method));
93
+ ratios.push(...valueList(detail.ratio));
94
+ if (methods.length) {
95
+ attributes.LossyImageCompressionMethod = multiValue(methods);
96
+ }
97
+ if (ratios.length === methods.length) {
98
+ if (ratios.length) {
99
+ attributes.LossyImageCompressionRatio = multiValue(ratios);
100
+ }
101
+ } else if (ratios.length) {
102
+ log.warn(
103
+ `derivedImageAttributes: ${methods.length} lossy method(s) and ` +
104
+ `${ratios.length} ratio(s) do not pair; the result has no ` +
105
+ `LossyImageCompressionRatio`
106
+ );
107
+ }
108
+ return attributes;
109
+ }
110
+
111
+ /**
112
+ * A base block that adds {@link derivedImageAttributes} to a composition, in
113
+ * the same shape as `nextSeriesNumberBase`. Put it after the block that sets
114
+ * the default `ImageType` (`secondaryCaptureImageBase`), so that the derived
115
+ * `ImageType` replaces the default. `buildImageDataset` adds it for
116
+ * `derivedFrom`; a caller can also add it to a custom `baseDicom`. An empty
117
+ * `derivedFrom` throws when the block is made.
118
+ *
119
+ * @param {Object|Object[]} derivedFrom - the source instance(s), at least one
120
+ * @param {Object} [options]
121
+ * @param {boolean|{method: string, ratio: number}} [options.lossy=true]
122
+ * @returns {Function} a base block
123
+ */
124
+ function derivedImageBase(derivedFrom, { lossy } = {}) {
125
+ const sources = sourceList(derivedFrom, "derivedImageBase");
126
+ return () => derivedImageAttributes(sources, { lossy });
127
+ }
128
+
129
+ // packages/imaging/src/buildImageDataset.js
130
+ //
131
+ // Build a full DICOM image instance from already-decoded pixels — the
132
+ // codec-free image primitive of dcmjs. dcmjs deliberately ships no PNG/JPEG
133
+ // codecs (browser + node compatible); callers decode with whatever fits
134
+ // their environment (Canvas, pngjs, ...) and hand over pixels plus
135
+ // geometry. Like encapsulate, this builds on createInstance and takes
136
+ // the same options (attributes in `overrides`, a naturalized DICOM
137
+ // provider), and returns a naturalized dataset ready for
138
+ // datasetToDict()/datasetToBuffer().
139
+
140
+
141
+ const SECONDARY_CAPTURE_SOP_CLASS_UID = "1.2.840.10008.5.1.4.1.1.7";
142
+
143
+ /**
144
+ * Secondary Capture identity, the default `ImageType` (ORIGINAL\PRIMARY),
145
+ * the SC Equipment `ConversionType` (WSD, workstation), and the Image module
146
+ * content date and time.
147
+ */
148
+ function secondaryCaptureImageBase(context) {
149
+ return {
150
+ SOPClassUID: SECONDARY_CAPTURE_SOP_CLASS_UID,
151
+ Modality: "OT",
152
+ ConversionType: "WSD",
153
+ ImageType: ["ORIGINAL", "PRIMARY"],
154
+ ContentDate: context.date,
155
+ ContentTime: context.time
156
+ };
157
+ }
158
+
159
+ /**
160
+ * The default base of `buildImageDataset`: core instance defaults and the
161
+ * Secondary Capture block. It has no `predecessorBase`, so
162
+ * `predecessor: true` has no effect; use
163
+ * `combineBases(imageBase, predecessorBase)` for a predecessor
164
+ * (CORE-USR-9). Use `.items` to build a variant.
165
+ */
166
+ const imageBase = combineBases(defaultInstanceBase, secondaryCaptureImageBase);
167
+
168
+ // The decodedImage field of each geometry keyword (IMG-USR-2).
169
+ const GEOMETRY_FIELDS = {
170
+ Rows: "rows",
171
+ Columns: "columns",
172
+ SamplesPerPixel: "samplesPerPixel",
173
+ PhotometricInterpretation: "photometricInterpretation",
174
+ BitsAllocated: "bitsAllocated",
175
+ BitsStored: "bitsStored",
176
+ HighBit: "highBit",
177
+ PixelRepresentation: "pixelRepresentation",
178
+ PlanarConfiguration: "planarConfiguration",
179
+ NumberOfFrames: "numberOfFrames"
180
+ };
181
+
182
+ const isPresent = value =>
183
+ value !== undefined && value !== null && value !== "";
184
+
185
+ /** The single value of a naturalized attribute, or undefined when empty. */
186
+ function singleValue(value) {
187
+ const single = Array.isArray(value) ? value[0] : value;
188
+ return isPresent(single) ? single : undefined;
189
+ }
190
+
191
+ /**
192
+ * Normalize a typed-array view to an exact ArrayBuffer. Another value is
193
+ * returned as it is; the function does not check the type (CORE-IMP-11).
194
+ */
195
+ function toExactArrayBuffer(bytes) {
196
+ if (ArrayBuffer.isView(bytes)) {
197
+ return bytes.buffer.slice(
198
+ bytes.byteOffset,
199
+ bytes.byteOffset + bytes.byteLength
200
+ );
201
+ }
202
+ return bytes;
203
+ }
204
+
205
+ /**
206
+ * The geometry that the decoded input gives (IMG-USR-2): each explicit
207
+ * `decodedImage` field, plus the values that the payload determines.
208
+ * `BitsAllocated` comes from the typed-array width of `pixels`,
209
+ * `PixelRepresentation` 1 from a signed typed array, and `NumberOfFrames`
210
+ * from `encapsulated.frames.length`. Without `decodedImage.highBit`, a
211
+ * decoded `bitsStored` gives `HighBit` = `bitsStored` - 1. The result has no
212
+ * key for a value that the decoded input does not give: the builder
213
+ * calculates no other value.
214
+ */
215
+ function decodedGeometry(decodedImage, encapsulated) {
216
+ const geometry = {};
217
+ for (const [keyword, field] of Object.entries(GEOMETRY_FIELDS)) {
218
+ if (isPresent(decodedImage[field])) {
219
+ geometry[keyword] = decodedImage[field];
220
+ }
221
+ }
222
+ if (geometry.HighBit === undefined && geometry.BitsStored !== undefined) {
223
+ geometry.HighBit = geometry.BitsStored - 1;
224
+ }
225
+ const { pixels } = decodedImage;
226
+ if (!encapsulated) {
227
+ // The typed array gives BitsAllocated and PixelRepresentation, so
228
+ // a float array would write integer pixels (IMG-USR-9).
229
+ if (pixels instanceof Float32Array || pixels instanceof Float64Array) {
230
+ throw new Error(
231
+ `buildImageDataset: decodedImage.pixels is a ` +
232
+ `${pixels.constructor.name}; DICOM integer pixel data ` +
233
+ `needs an integer typed array`
234
+ );
235
+ }
236
+ const elementBits = pixels.BYTES_PER_ELEMENT * 8;
237
+ if (
238
+ geometry.BitsAllocated !== undefined &&
239
+ geometry.BitsAllocated !== elementBits
240
+ ) {
241
+ throw new Error(
242
+ `buildImageDataset: bitsAllocated ${geometry.BitsAllocated} ` +
243
+ `does not match the ${elementBits}-bit typed array provided`
244
+ );
245
+ }
246
+ geometry.BitsAllocated = elementBits;
247
+ if (
248
+ geometry.PixelRepresentation === undefined &&
249
+ (pixels instanceof Int8Array ||
250
+ pixels instanceof Int16Array ||
251
+ pixels instanceof Int32Array)
252
+ ) {
253
+ geometry.PixelRepresentation = 1;
254
+ }
255
+ } else {
256
+ // The fragment list is the ground truth for the frame count. An
257
+ // explicit count that disagrees hides frames (review finding 10).
258
+ const frameCount = encapsulated.frames.length;
259
+ if (
260
+ geometry.NumberOfFrames !== undefined &&
261
+ geometry.NumberOfFrames !== frameCount
262
+ ) {
263
+ throw new Error(
264
+ `buildImageDataset: decodedImage.numberOfFrames ` +
265
+ `(${geometry.NumberOfFrames}) does not match ` +
266
+ `options.encapsulated.frames.length (${frameCount})`
267
+ );
268
+ }
269
+ geometry.NumberOfFrames = frameCount;
270
+ }
271
+ return geometry;
272
+ }
273
+
274
+ /**
275
+ * The requirement checks of IMG-USR-9 on the effective values: the decoded
276
+ * value, else the value of `dataset` (base, inherited, or override).
277
+ * `Rows` and `Columns` must be positive integers, so one of the two sources
278
+ * must give them. For another absent value, the check uses the old default
279
+ * only inside the computation, and does not write it: `SamplesPerPixel` 1
280
+ * and `NumberOfFrames` 1. The photometric check needs a
281
+ * `PhotometricInterpretation`.
282
+ */
283
+ function checkGeometry(geometry, dataset, pixels) {
284
+ const effective = keyword =>
285
+ geometry[keyword] !== undefined
286
+ ? geometry[keyword]
287
+ : singleValue(dataset[keyword]);
288
+ for (const keyword of ["Rows", "Columns"]) {
289
+ const value = effective(keyword);
290
+ if (!Number.isInteger(value) || value <= 0) {
291
+ throw new Error(
292
+ `buildImageDataset: ${keyword} must be a positive integer ` +
293
+ `(decodedImage.${GEOMETRY_FIELDS[keyword]}, or the ` +
294
+ `merged dataset), got ${value}`
295
+ );
296
+ }
297
+ }
298
+ const samplesPerPixel = effective("SamplesPerPixel") ?? 1;
299
+ const photometricInterpretation = effective("PhotometricInterpretation");
300
+
301
+ if (photometricInterpretation !== undefined) {
302
+ const monochrome = /^MONOCHROME[12]$/.test(photometricInterpretation);
303
+ const color = /^(RGB|YBR_)/.test(photometricInterpretation);
304
+ if (monochrome && samplesPerPixel !== 1) {
305
+ throw new Error(
306
+ `buildImageDataset: ${photometricInterpretation} requires ` +
307
+ `samplesPerPixel 1, got ${samplesPerPixel}`
308
+ );
309
+ }
310
+ if (color && samplesPerPixel !== 3) {
311
+ throw new Error(
312
+ `buildImageDataset: ${photometricInterpretation} requires ` +
313
+ `samplesPerPixel 3, got ${samplesPerPixel}`
314
+ );
315
+ }
316
+ }
317
+
318
+ if (!pixels) {
319
+ return;
320
+ }
321
+ const rows = effective("Rows");
322
+ const columns = effective("Columns");
323
+ const numberOfFrames = effective("NumberOfFrames") ?? 1;
324
+ // Native pixels always give BitsAllocated (decodedGeometry).
325
+ const bitsAllocated = geometry.BitsAllocated;
326
+ const expected =
327
+ rows * columns * samplesPerPixel * numberOfFrames * (bitsAllocated / 8);
328
+ if (pixels.byteLength !== expected) {
329
+ throw new Error(
330
+ `buildImageDataset: pixel buffer is ${pixels.byteLength} ` +
331
+ `bytes but ${rows}x${columns}x${samplesPerPixel}` +
332
+ `${numberOfFrames > 1 ? `x${numberOfFrames} frames` : ""} at ` +
333
+ `${bitsAllocated} bits needs ${expected} — fix the geometry ` +
334
+ `or the decode`
335
+ );
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Build a naturalized DICOM image dataset from decoded pixels with
341
+ * {@link createInstance}, then set the pixel data.
342
+ *
343
+ * The options follow CORE-USR-1 (`packages/core/README.md`); the image rules
344
+ * are IMG-USR-n in `packages/imaging/README.md`. The options object holds
345
+ * the controls; the DICOM attributes go in `options.overrides`, a
346
+ * naturalized DICOM provider with the forms of `baseDicom`. An extra option
347
+ * key has no effect (CORE-USR-7). With `dataLevel: "series"`, `instance` is
348
+ * the sample instance in the series (CORE-USR-5).
349
+ *
350
+ * For a non-empty `derivedFrom`, the base is
351
+ * `combineBases(baseDicom, derivedImageBase(derivedFrom, { lossy }))`
352
+ * (IMG-IMP-1). The builder removes its control keys `derivedFrom`, `lossy`,
353
+ * and `encapsulated` before the call (CORE-IMP-9). After the call, it
354
+ * checks the effective geometry (IMG-USR-9), writes only the geometry that
355
+ * the decoded input gives (IMG-USR-2), and sets the pixel encoding and
356
+ * `PixelData`.
357
+ *
358
+ * @example
359
+ * buildImageDataset(decodedImage, {
360
+ * instance,
361
+ * derivedFrom: source,
362
+ * overrides: { SeriesDescription: "Thumbnail" }
363
+ * });
364
+ *
365
+ * @param {Object} decodedImage - the decoded pixels and geometry. Each
366
+ * geometry field has no default. A field that is not given writes
367
+ * nothing, and the value of the base, `instance`, or `overrides` stays.
368
+ * @param {Uint8Array|Int8Array|Uint16Array|Int16Array} [decodedImage.pixels]
369
+ * interleaved decoded samples in an integer typed array; required unless
370
+ * options.encapsulated
371
+ * @param {number} [decodedImage.rows] else the merged `Rows`
372
+ * @param {number} [decodedImage.columns] else the merged `Columns`
373
+ * @param {number} [decodedImage.samplesPerPixel]
374
+ * @param {string} [decodedImage.photometricInterpretation]
375
+ * @param {number} [decodedImage.bitsAllocated] must match the typed-array
376
+ * width of `pixels`, which always gives `BitsAllocated`
377
+ * @param {number} [decodedImage.bitsStored]
378
+ * @param {number} [decodedImage.highBit] else `bitsStored` - 1 when
379
+ * `decodedImage.bitsStored` is given
380
+ * @param {number} [decodedImage.pixelRepresentation] else 1 for a signed
381
+ * typed array
382
+ * @param {number} [decodedImage.planarConfiguration] written only when the
383
+ * effective `SamplesPerPixel` is more than 1
384
+ * @param {number} [decodedImage.numberOfFrames] must match
385
+ * `encapsulated.frames.length`, which always gives `NumberOfFrames`
386
+ * @param {Object} [options] - the {@link createInstance} options
387
+ * (`instance`, `dataLevel`, `levels`, `predecessor`, `postProcess`,
388
+ * `overrides`), plus:
389
+ * @param {*} [options.baseDicom=imageBase] - base blocks
390
+ * @param {Object|Object[]} [options.derivedFrom] - the naturalized
391
+ * instance(s) that the image is derived from; each needs SOPClassUID and
392
+ * SOPInstanceUID. An empty array is the same as no `derivedFrom`.
393
+ * @param {boolean|{method: string, ratio: number}} [options.lossy=true] -
394
+ * the lossy compression of a derivation; no effect without `derivedFrom`
395
+ * @param {{transferSyntaxUID: string, frames: Array}} [options.encapsulated]
396
+ * - pre-encoded frames and their transfer syntax, in place of pixels
397
+ * @returns {Object} naturalized dataset with _meta and _vrMap
398
+ */
399
+ function buildImageDataset(decodedImage = {}, options = {}) {
400
+ const {
401
+ baseDicom = imageBase,
402
+ derivedFrom,
403
+ lossy,
404
+ encapsulated,
405
+ ...rest
406
+ } = options;
407
+ if (decodedImage.pixels && encapsulated) {
408
+ throw new Error(
409
+ "buildImageDataset: pass either decodedImage.pixels or " +
410
+ "options.encapsulated, not both"
411
+ );
412
+ }
413
+
414
+ // The transfer syntax and the frames are used below (IMG-USR-9).
415
+ if (
416
+ encapsulated &&
417
+ (!encapsulated.transferSyntaxUID || !encapsulated.frames?.length)
418
+ ) {
419
+ throw new Error(
420
+ "buildImageDataset: options.encapsulated needs " +
421
+ "{ transferSyntaxUID, frames: [bytes, ...] }"
422
+ );
423
+ }
424
+
425
+ const geometry = decodedGeometry(decodedImage, encapsulated);
426
+
427
+ const sources = [].concat(derivedFrom ?? []);
428
+ const dataset = createInstance({
429
+ ...rest,
430
+ baseDicom: sources.length
431
+ ? combineBases(baseDicom, derivedImageBase(sources, { lossy }))
432
+ : baseDicom
433
+ });
434
+ checkGeometry(geometry, dataset, !encapsulated && decodedImage.pixels);
435
+
436
+ // A decoded value replaces the base, inherited, or override value. A
437
+ // value that the decoded input does not give stays (IMG-USR-2).
438
+ const { PlanarConfiguration, NumberOfFrames, ...always } = geometry;
439
+ Object.assign(dataset, always);
440
+ if (
441
+ PlanarConfiguration !== undefined &&
442
+ singleValue(dataset.SamplesPerPixel) > 1
443
+ ) {
444
+ dataset.PlanarConfiguration = PlanarConfiguration;
445
+ }
446
+ // A single-frame IOD has no NumberOfFrames, so a frame count of 1 from
447
+ // frames.length is written only to replace an existing value.
448
+ if (
449
+ NumberOfFrames !== undefined &&
450
+ (NumberOfFrames > 1 ||
451
+ isPresent(decodedImage.numberOfFrames) ||
452
+ isPresent(dataset.NumberOfFrames))
453
+ ) {
454
+ dataset.NumberOfFrames = NumberOfFrames;
455
+ }
456
+ // Encapsulated pixel data is always OB (PS3.5 A.4).
457
+ dataset._vrMap = {
458
+ ...(dataset._vrMap || {}),
459
+ PixelData:
460
+ !encapsulated && singleValue(dataset.BitsAllocated) === 16
461
+ ? "OW"
462
+ : "OB"
463
+ };
464
+ // instanceBase supplies Explicit VR Little Endian; set the transfer
465
+ // syntax only for encapsulated frames, or when the merged _meta has no
466
+ // transfer syntax. The copy keeps overrides._meta of the caller
467
+ // unchanged (CORE-USR-13).
468
+ const hasTransferSyntax = Boolean(dataset._meta?.TransferSyntaxUID);
469
+ dataset._meta = { ...(dataset._meta || {}) };
470
+ if (encapsulated || !hasTransferSyntax) {
471
+ dataset._meta.TransferSyntaxUID = {
472
+ Value: [
473
+ encapsulated
474
+ ? encapsulated.transferSyntaxUID
475
+ : EXPLICIT_LITTLE_ENDIAN
476
+ ]
477
+ };
478
+ }
479
+
480
+ dataset.PixelData = encapsulated
481
+ ? encapsulated.frames.map(frame => toExactArrayBuffer(frame))
482
+ : toExactArrayBuffer(decodedImage.pixels);
483
+
484
+ return dataset;
485
+ }
486
+
487
+ // src/image/jpegInfo.js
488
+ //
489
+ // Minimal JPEG header inspection: read the SOF (start-of-frame) segment to
490
+ // recover the geometry DICOM needs (Rows/Columns/SamplesPerPixel/precision)
491
+ // and identify the matching transfer syntax — WITHOUT decoding any pixels.
492
+ // JPEG is a legal DICOM transfer syntax, so JPEG bytes can be carried as
493
+ // encapsulated PixelData verbatim; only the frame header must be understood.
494
+
495
+ const JPEG_BASELINE_TS = "1.2.840.10008.1.2.4.50"; // SOF0, process 1
496
+ const JPEG_EXTENDED_TS = "1.2.840.10008.1.2.4.51"; // SOF1, processes 2 & 4
497
+ const JPEG_LOSSLESS_TS = "1.2.840.10008.1.2.4.57"; // SOF3, process 14
498
+
499
+ const LOSSLESS_SOF_MARKERS = new Set([0xc3, 0xc7, 0xcb, 0xcf]);
500
+ const RGB_COMPONENT_IDS = [0x52, 0x47, 0x42]; // "R", "G", "B"
501
+
502
+ /**
503
+ * The PhotometricInterpretation of the compressed data (PS3.5 8.2.1), or
504
+ * null when DICOM has no value for it (for example 4-component CMYK).
505
+ *
506
+ * - 1 component: MONOCHROME2.
507
+ * - 3 components: RGB when the data has no colour transform, that is an
508
+ * Adobe APP14 transform of 0, the component IDs "R", "G", "B", or a
509
+ * lossless process. Otherwise YBR_FULL when no component is subsampled,
510
+ * and YBR_FULL_422 when the chroma is subsampled.
511
+ */
512
+ function photometricInterpretation(sofMarker, components, adobeTransform) {
513
+ if (components.length === 1) {
514
+ return "MONOCHROME2";
515
+ }
516
+ if (components.length !== 3) {
517
+ return null;
518
+ }
519
+ const isRgb =
520
+ adobeTransform === 0 ||
521
+ (adobeTransform === undefined &&
522
+ components.every((c, i) => c.id === RGB_COMPONENT_IDS[i])) ||
523
+ (adobeTransform === undefined && LOSSLESS_SOF_MARKERS.has(sofMarker));
524
+ if (isRgb) {
525
+ return "RGB";
526
+ }
527
+ const subsampled = components.some(
528
+ c => c.sampling !== components[0].sampling
529
+ );
530
+ return subsampled ? "YBR_FULL_422" : "YBR_FULL";
531
+ }
532
+
533
+ /**
534
+ * Read the JPEG frame header. The DICOM values are ready for
535
+ * buildImageDataset: `bitsAllocated` is 8 or 16, `bitsStored` is the sample
536
+ * precision, and `photometricInterpretation` follows PS3.5 8.2.1.
537
+ *
538
+ * @param {Uint8Array} bytes - JPEG file bytes (SOI onward)
539
+ * @returns {{ rows, columns, samplesPerPixel, bitsAllocated, bitsStored,
540
+ * photometricInterpretation: string|null,
541
+ * transferSyntaxUID: string|null, sofMarker: number }}
542
+ * @throws on non-JPEG input or a missing frame header
543
+ */
544
+ function parseJpegInfo(bytes) {
545
+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) {
546
+ throw new Error("parseJpegInfo: input is not JPEG (missing SOI)");
547
+ }
548
+
549
+ let adobeTransform;
550
+ let offset = 2;
551
+ while (offset + 4 <= bytes.length) {
552
+ if (bytes[offset] !== 0xff) {
553
+ offset++;
554
+ continue;
555
+ }
556
+ const marker = bytes[offset + 1];
557
+ // standalone markers without a length field
558
+ if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
559
+ offset += 2;
560
+ continue;
561
+ }
562
+ if (marker === 0xd9 || marker === 0xda) {
563
+ break; // EOI or start-of-scan: no SOF was seen
564
+ }
565
+ const length = (bytes[offset + 2] << 8) | bytes[offset + 3];
566
+
567
+ // APP14 "Adobe": the transform byte follows "Adobe", the version,
568
+ // and two flag words.
569
+ if (
570
+ marker === 0xee &&
571
+ length >= 14 &&
572
+ offset + 2 + length <= bytes.length &&
573
+ String.fromCharCode(...bytes.subarray(offset + 4, offset + 9)) ===
574
+ "Adobe"
575
+ ) {
576
+ adobeTransform = bytes[offset + 15];
577
+ }
578
+
579
+ // SOF0-SOF15, excluding DHT (C4), JPG (C8), DAC (CC)
580
+ const isSof =
581
+ marker >= 0xc0 &&
582
+ marker <= 0xcf &&
583
+ marker !== 0xc4 &&
584
+ marker !== 0xc8 &&
585
+ marker !== 0xcc;
586
+ if (isSof) {
587
+ // The six SOF fields span bytes[offset+4 .. offset+9], and the
588
+ // declared segment must fit inside the input. Out-of-range reads
589
+ // coerce to 0 in the bitwise math below, so a truncated JPEG
590
+ // would silently return wrong geometry (review finding 9).
591
+ const p = offset + 4;
592
+ const samplesPerPixel = bytes[p + 5];
593
+ if (
594
+ length < 8 + 3 * (samplesPerPixel || 0) ||
595
+ offset + 2 + length > bytes.length
596
+ ) {
597
+ throw new Error(
598
+ "parseJpegInfo: truncated SOF segment — the frame header does not fit in the input"
599
+ );
600
+ }
601
+ const components = [];
602
+ for (let i = 0; i < samplesPerPixel; i++) {
603
+ components.push({
604
+ id: bytes[p + 6 + 3 * i],
605
+ sampling: bytes[p + 7 + 3 * i]
606
+ });
607
+ }
608
+ const precision = bytes[p];
609
+ const info = {
610
+ sofMarker: marker,
611
+ bitsAllocated: precision > 8 ? 16 : 8,
612
+ bitsStored: precision,
613
+ rows: (bytes[p + 1] << 8) | bytes[p + 2],
614
+ columns: (bytes[p + 3] << 8) | bytes[p + 4],
615
+ samplesPerPixel,
616
+ photometricInterpretation: photometricInterpretation(
617
+ marker,
618
+ components,
619
+ adobeTransform
620
+ ),
621
+ transferSyntaxUID: null
622
+ };
623
+ if (marker === 0xc0) {
624
+ info.transferSyntaxUID = JPEG_BASELINE_TS;
625
+ } else if (marker === 0xc1) {
626
+ info.transferSyntaxUID = JPEG_EXTENDED_TS;
627
+ } else if (marker === 0xc3) {
628
+ info.transferSyntaxUID = JPEG_LOSSLESS_TS;
629
+ }
630
+ // other SOFs (progressive C2, arithmetic, hierarchical) have no
631
+ // DICOM transfer syntax — transferSyntaxUID stays null and the
632
+ // caller decides how loudly to complain.
633
+ return info;
634
+ }
635
+ offset += 2 + length;
636
+ }
637
+ throw new Error(
638
+ "parseJpegInfo: no frame header (SOF) found — truncated or invalid JPEG"
639
+ );
640
+ }
641
+
642
+ // packages/imaging/src/h264.js
643
+ //
644
+ // H.264 profile/level → DICOM transfer syntax mapping. Pure lookup, no codec
645
+ // and no MP4 container knowledge — just the rule that says which encapsulated
646
+ // transfer syntax can carry a given AVC stream (Supplement 225). Lives in
647
+ // imaging because it's shared: video's MP4 header inspection uses it to label
648
+ // a stream, and image builders can use it too.
649
+
650
+ // Fragmentable MPEG-4 AVC/H.264 High Profile transfer syntaxes (Sup 225).
651
+ // The fragmentable ".1" family is always chosen because the encapsulation
652
+ // writer emits the stream as N >= 1 fragments.
653
+ const H264_HIGH_41_FRAGMENTABLE = "1.2.840.10008.1.2.4.102.1";
654
+ const H264_HIGH_42_FRAGMENTABLE = "1.2.840.10008.1.2.4.104.1";
655
+
656
+ // AVC profile_idc values that fit inside the "High Profile" transfer
657
+ // syntaxes: Baseline (66) and Main (77) are strict subsets of High (100).
658
+ const H264_SUPPORTED_PROFILES = new Set([66, 77, 100]);
659
+
660
+ /**
661
+ * Map an AVC profile/level pair to the DICOM transfer syntax that carries it,
662
+ * or null when no defined syntax fits (High-10/422/444 profiles, levels above
663
+ * 4.2, HEVC, ...). level_idc is the H.264 level times ten (41 = Level 4.1).
664
+ *
665
+ * @param {number} profileIdc
666
+ * @param {number} levelIdc
667
+ * @returns {string|null}
668
+ */
669
+ function h264TransferSyntaxUID(profileIdc, levelIdc) {
670
+ if (!H264_SUPPORTED_PROFILES.has(profileIdc)) {
671
+ return null;
672
+ }
673
+ if (levelIdc <= 41) {
674
+ return H264_HIGH_41_FRAGMENTABLE;
675
+ }
676
+ if (levelIdc === 42) {
677
+ return H264_HIGH_42_FRAGMENTABLE;
678
+ }
679
+ return null;
680
+ }
681
+
682
+ export { SECONDARY_CAPTURE_SOP_CLASS_UID, buildImageDataset, derivedImageAttributes, derivedImageBase, h264TransferSyntaxUID, imageBase, parseJpegInfo, secondaryCaptureImageBase };
683
+ //# sourceMappingURL=index.mjs.map