@dcmjs-org/imaging 0.0.0-bootstrap.0 → 1.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }