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

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