Skip to content

fix: narrow the UN sequence detection and keep Big Endian items (follow-up to #496) - #664

Open
wayfarer3130 wants to merge 10 commits into
0.xfrom
fix/un-sequence-detection-followup
Open

wayfarer3130 wants to merge 10 commits into
0.xfrom
fix/un-sequence-detection-followup

Conversation

@wayfarer3130

@wayfarer3130 wayfarer3130 commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

This PR is a follow-up to #496, #603 and #622. The reviews of the 1.x ports #658, #662 and #663 found these bugs. This PR is also the single 0.x PR for the fixes from the 1.0-beta work. B4, B5 and B6 are ports of #665 and #663 from 1.0-beta.

Summary

Behavior changes

This PR changes these public behaviors:

  • An explicit OV element now reads as vr: "OV", not as vr: "UN". The change applies to all three readers. The writer now writes the VR OV for a dict entry with vr: "OV". dcmjs 0.53.6 wrote UN. The naturalized _vrMap no longer has ExtendedOffsetTable: "UN". The value shape ([ArrayBuffer]) does not change.
  • ImageNormalizer.framesInPixelData is deprecated. The method stays, with the same signature and the same result as in 0.53.6. The normalizer does not call the method.
  • A SharedFunctionalGroupsSequence with 2 or more items now keeps only item 0.

B1. Explicit VR Big Endian loses the sequence items

  • Cause: DicomMessage._readTag set readSyntax to Implicit VR LE, but the stream stayed big endian. The SQ reader read the item tag as (FEFF,E000), found no item, and returned Value: []. The async reader was correct, because readTagHeader sets the endian from readSyntax.
  • Reproduction: write a dataset with TS 1.2.840.10008.1.2.2 and "00091010": { vr: "UN", Value: [<PS3.5 6.2.2 item bytes>] }. Then read the file with DicomMessage.readFile. The result is { vr: "SQ", Value: [] }.
  • Fix: _readTag calls stream.setEndian(true) for the sequence. The existing stream.setEndian(oldEndian) restores the endian after the value.

S1. A UN that starts with the item tag, but is not a sequence, fails to read

  • Cause: isUnSequenceValue looked at the first 4 bytes only. It did not look at the dictionary VR, and it did not check the item length.
  • Reproduction:
    • A private (0009,1010) UN with the 16 bytes FE FF 00 E0 00 00 01 00 01..08. The sync reader throws Request more than currently allocated buffer.
    • A standard (0042,0011) (dictionary VR OB) as wire UN with the bytes FE FF 00 E0 04 00 00 00 09 09 09 09. The read throws.
  • Fix: isUnSequenceValue(stream, length, tag) returns true only when these conditions are all true:
    • The value starts with the item tag. The compare uses the SEQUENCE_ITEM_TAG constant.
    • The dictionary VR is SQ, or the tag has no dictionary entry.
    • The first item length is 0xFFFFFFFF, or the first item length is not more than length - 8.
  • The sync reader and the async reader use the same function. In other cases, the value stays as bytes.

S2. The writer writes { InlineBinary } as SQ

  • Cause: isItemList in src/Tag.js accepted each object that is not binary data. { InlineBinary } and { BulkDataURI } are such objects.
  • Reproduction: write "00091010": { vr: "UN", Value: [{ InlineBinary: "AAECAw==" }] }. The writer writes an SQ with a junk item.
  • Fix: isItemList also requires that each key of each value has 8 hex digits, as isItemDictLike does in the 1.x parser.
  • Note: the 0.x UN writer does not support InlineBinary. After this fix, the write throws a TypeError, as it did before fix/bill un sq implicit vr ps35622 #496. The test checks the error type, not the V8 error text. Before this fix, the writer wrote an invalid SQ and gave no error. Support for InlineBinary in a UN write is a separate issue.

B2. The normalizer lowers NumberOfFrames (#603)

  • Cause: fix(normalizers): normalize multiframe datasets missing functional group sequences #603 added framesInPixelData to src/normalizers.js. When SharedFunctionalGroupsSequence was missing, normalizeMultiframe lowered NumberOfFrames to the number of whole uncompressed frames in PixelData. Encapsulated PixelData can have more fragments than frames, or fewer fragments than frames (for example, the video transfer syntaxes). The byte count does not give the frame count.
  • Rule (from the maintainer, in the review of fix(normalizers): normalize multiframe datasets missing functional groups (port of #603) #662): an empty or missing per-frame sequence must not reduce the number of frames.
  • Reproduction:
    • Normalize an Enhanced MR dataset with NumberOfFrames 4, 2x2 16-bit PixelData of 1 frame, and no functional groups. The normalizer gave NumberOfFrames 1 and 1 per-frame item.
    • Normalize the same dataset with NumberOfFrames 8 and encapsulated PixelData of 2 fragments of 10 bytes. The normalizer gave NumberOfFrames 2.
  • Fix: the normalizer keeps the declared NumberOfFrames. The normalizer does not call framesInPixelData now. ImageNormalizer.framesInPixelData stays as a public static method with the @deprecated tag, because a caller outside dcmjs can use it. When PerFrameFunctionalGroupsSequence is missing, the normalizer makes one per-frame item for each declared frame. Each item has PlanePositionSequence from the top-level ImagePositionPatient, and its own FrameContentSequence. The 1.x port fix(normalizers): normalize multiframe datasets missing functional groups (port of #603) #662 has the same change.
  • An empty PerFrameFunctionalGroupsSequence ([]) gets the same result as a missing sequence: one per-frame item for each declared frame. Each item has its own copy of ImagePositionPatient.

B3. The async reader mixes the frames of Big Endian OW pixel data (#622)

  • Cause: AsyncDicomReader.readUncompressed cut the value into frames first, and swapped the bytes of each frame alone. The words of OW run across the whole value. When a frame is not a whole number of words, one word spans two frames. The sync reader (DicomMessage) swaps the whole value, so its result was correct.
  • Reproduction: write a TS 1.2.840.10008.1.2.2 file with Rows 3, Columns 3, BitsAllocated 8, NumberOfFrames 2, and PixelData OW with the bytes 1..18. Read the file.
    • DicomMessage gives [1..9] and [10..18].
    • AsyncDicomReader gave [1,2,3,4,5,6,7,8,10] and [12,9,14,11,16,13,18,15,17].
  • Fix: when the syntax is Explicit VR Big Endian and the frame length is not a multiple of the word width, the async reader reads the whole value, swaps the bytes, and then cuts the value into frames. The 1-bit path (readUncompressedBitFrame) already does this.

B4. The normalizer does not complete the functional groups (port of #665)

  • Cause: normalizeMultiframe in src/normalizers.js used if (!ds.SharedFunctionalGroupsSequence), so an empty array [] counted as present. The normalizer then set PixelValueTransformationSequence on the array, and the write lost it.
  • Cause: the normalizer added per-frame items only when the per-frame sequence was missing or empty. A short sequence kept fewer items than NumberOfFrames.
  • Cause: the normalizer replaced the FrameContentSequence of each existing item. The dimension index values, the temporal position and the stack ID of the file were lost.
  • Fix: these changes are in normalizeMultiframe:
    • An empty SharedFunctionalGroupsSequence array counts as missing.
    • A one-item array gets the list accessors (addAccessors). Thus SharedFunctionalGroupsSequence.X and SharedFunctionalGroupsSequence[0].X both work. A plain object stays a plain object.
    • A shared array with 2 or more items keeps only item 0. The standard permits one item. The doc comment of normalizeMultiframe states this rule.
    • The normalizer keeps the declared NumberOfFrames, and fills the per-frame sequence up to NumberOfFrames.
    • When the fill adds items, the normalizer first copies the per-frame sequence to a plain array. A sequence that needs no fill keeps its list accessors, as in 0.53.6. On 0.x, naturalizeDataset wraps a one-item sequence in an addAccessors Proxy. A push on that Proxy wrote the new items into item 0 as the keys "1" and "2", and denaturalizeDataset then threw a TypeError.
    • Existing items keep their content. The normalizer adds a FrameContentSequence only to an item that has none.
    • A null item up to NumberOfFrames becomes an empty item (||= {}). An item after NumberOfFrames stays unchanged. The window guess uses functionalGroup?.FrameVOILUT, so a null item does not throw.
    • Each new item gets its own copy of the ImagePositionPatient array. A non-array value goes through unchanged.
  • Note: 0.x has addAccessors, and naturalizeDataset uses addAccessors for a one-item sequence. Thus the 1.0 addAccessors change applies to 0.x. On 0.x, addAccessors gives a Proxy of a one-item array, and not the item itself as in 1.0. The tests check shared[0].X, and not shared[0] === shared.

B5. The raw binary path does not swap Big Endian words (port of #663)

  • Cause: AsyncDicomReader.readRawBinary called _emitSplitValues(length) with no word width. A listener that returns { expectsRaw: true } got the OW, OF, OD and OL words in big endian order.
  • Fix: a new method wordWidth(tagInfo) gives the word width of the resolved VR. readRawBinary passes the word width to _emitSplitValues.
  • The rule is the same as on 1.0-beta:
    • OW has 2 bytes for each word. OF and OL have 4 bytes. OD and OV have 8 bytes.
    • OB and a UN with no dictionary VR do not swap.
    • A UN element with the dictionary VR OW, OF, OD, OL or OV swaps as that VR.
  • The pixel data paths also use wordWidth(tagInfo). Thus a UN Pixel Data with the dictionary VR ox swaps as OW, as on 1.0-beta.
  • _emitSplitValues (raw binary path) and readUncompressed (pixel data path) decide the swap from the byte order of the stream, not from the transfer syntax of the file. The items of a UN sequence are Implicit VR Little Endian, also in a Big Endian file. Before this change, an expectsRaw listener got the words of (0028,1201) 1,2,3,4 in such an item as 2,1,4,3. readSingle and the sync reader already use the byte order of the stream. 1.0-beta gets the same change in a follow-up PR.

B6. 0.x has no OV VR (port of #663)

  • Cause: ValueRepresentation.createByTypeString("OV") gave UN. An explicit OV value and a UN value with the dictionary VR OV (Extended Offset Table (7FE0,0001)) got no byte swap in Explicit VR Big Endian. All three readers gave the bytes in file order.
  • Check of OL: a UN with the dictionary VR OL already resolved to OL with a word width of 4. Only the raw binary path (B5) did not swap the bytes.
  • Fix: add the OV VR (OtherVeryLongString). OV has a 32-bit length, a single value and 8 bytes for each word, as on 1.0-beta.

Verified

I added the new tests to the #496 test block in test/sync-async-parser-equivalency.test.js. I ran each new test on the master source before the fix:

Test Result on master Result with this PR
Explicit VR Big Endian: a private UN sequence keeps its item (also an element after the sequence) Fails: the sync reader returned 0 items, expected 1 Passes
A private UN with the item tag and a bad item length keeps its bytes Fails: Request more than currently allocated buffer Passes
A standard OB tag sent as UN that starts with the item tag keeps its bytes Fails: the read throws Passes
A UN with an InlineBinary reference is not written as SQ Fails: the write did not throw, and the writer wrote an SQ Passes

I ran the tests of B2 and B3 on this branch before each fix:

Test Result before the fix Result with the fix
test/segIncompleteMultiframe.test.js: SEG derivation from a dataset with NumberOfFrames 4 and no functional groups (includeSliceSpacing true and false) keeps 4 frames and gets 4 per-frame items Fails: NumberOfFrames 1, expected 4 Passes
test/segIncompleteMultiframe.test.js: NumberOfFrames 8 stays for encapsulated PixelData with 2 fragments and with 10 fragments Fails: NumberOfFrames 2 (2 fragments); 1 per-frame item, expected 8 (10 fragments) Passes
test/big-endian.test.js: the sync reader and the async reader read OW frames that are not a whole number of words (LE and BE) Fails for BE: the async reader gave [1,2,3,4,5,6,7,8,10] for frame 1 Passes

I ran the tests of B4, B5 and B6 on this branch before each fix:

Test Result before the fix Result with the fix
test/segIncompleteMultiframe.test.js: new tests from 1.0-beta (empty shared sequence, existing FrameContentSequence, short per-frame sequence and [null, {}], null item after NumberOfFrames, one-item shared array) Fail Pass
test/big-endian.test.js: a Big Endian OW, OF or OL value (also as UN) read as expectsRaw raw binary Fails: the bytes stay in file order Passes
test/big-endian.test.js: a Big Endian OV value, and a UN value with the dictionary VR OV, with all three readers Fails: the bytes stay in file order Passes

I ran the tests of the review fixes on this branch before each fix:

Test Result before the fix Result with the fix
test/segIncompleteMultiframe.test.js: a one-item per-frame sequence from naturalizeDataset with NumberOfFrames 3 gets 3 items, and denaturalizeDataset writes the dataset Fails: item 0 has the keys "1" and "2" Passes
test/big-endian.test.js: an OW value 1,2,3,4 in a UN sequence of a Big Endian file, read with an expectsRaw listener Fails: 2,1,4,3 Passes

I merged origin/master into this branch before the ports.

  • npm test: 33 test suites and 459 tests pass.
  • eslint, prettier --check and npm run build pass. The 0.x line has no bundle-size test.

PR #658 gets the same fixes for 1.x.

🤖 Generated with Claude Code

…ow-up to #496)

- Sync reader: set the stream little endian while it reads a UN sequence
  in Explicit VR Big Endian (the items were lost).
- isUnSequenceValue: apply PS3.5 6.2.2 only when the dictionary VR is SQ
  or the tag has no dictionary entry, and when the first item length is
  undefined or fits in the value. Both readers use the check.
- Writer: a UN value is a sequence only when each value is an item with
  tag-shaped keys, so { InlineBinary } / { BulkDataURI } stay UN.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@netlify

netlify Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for dcmjs2 ready!

Name Link
🔨 Latest commit 93af75f
🔍 Latest deploy log https://app.netlify.com/projects/dcmjs2/deploys/6b0797dcc59d1b17b284551b
😎 Deploy Preview https://deploy-preview-664--dcmjs2.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

wayfarer3130 and others added 4 commits November 25, 2026 09:11
…oups are missing

The normalizer no longer lowers NumberOfFrames to the frames that PixelData
appears to hold. Encapsulated PixelData can have more or fewer fragments than
frames, so a byte count says nothing about the frame count. framesInPixelData
is removed.

A dataset with no PerFrameFunctionalGroupsSequence now gets one per-frame item
for each declared frame, each with PlanePositionSequence from the top-level
ImagePositionPatient and its own FrameContentSequence. Same change as the
1.x port #662.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When a frame of OW pixel data is not a whole number of words (8-bit data
stored as OW, odd samples per frame), a word spans two frames. The async
reader cut the value into frames first and swapped each frame alone, so it
mixed the bytes of the two frames. It now reads and swaps the whole value
first and then cuts it into frames, as the 1-bit path already does.
DicomMessage was already correct.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- isUnSequenceValue compares the first 4 bytes with SEQUENCE_ITEM_TAG, and
  its doc comment ends with a full sentence.
- The InlineBinary write test expects a TypeError, not the V8 error text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An empty PerFrameFunctionalGroupsSequence no longer reduces the number
of frames: the normalizer builds one item per declared frame, as for a
missing sequence. Each generated item gets its own ImagePositionPatient
copy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
wayfarer3130 added a commit that referenced this pull request Nov 26, 2026
…magePositionPatient array per frame (#665)

* fix(normalizers): treat an empty per-frame sequence as missing; one ImagePositionPatient array per frame

An empty PerFrameFunctionalGroupsSequence no longer reduces the number
of frames: the normalizer builds one item per declared frame, as for a
missing sequence. Each generated item gets its own ImagePositionPatient
copy. Port of the 0.x fix in #664 (follow-up to #662).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(normalizers): treat an empty shared sequence as missing; complete the per-frame sequence

- An empty SharedFunctionalGroupsSequence array counts as missing, and a
  one-item array is used as its item, so the shared groups the normalizer
  sets (PixelValueTransformationSequence and the others) are written.
- The per-frame sequence is filled up to NumberOfFrames, and each item
  gets its FrameContentSequence, not only the first item.
- planePositionGroup passes a non-array ImagePositionPatient through.
- Raise the dcmjs.js bundle ceiling to x1.091 (measured x1.09014).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(normalizers): keep an existing FrameContentSequence; replace a null per-frame item

- The normalizer adds a FrameContentSequence only to a per-frame item
  that has none; an existing item keeps its own (dimension index values,
  temporal position, stack ID).
- A null or missing per-frame item becomes an empty item again, so
  [null, {}] no longer throws a TypeError.
- Tests: an existing item keeps its FrameContentSequence, and the shared
  groups survive a denaturalize/naturalize round trip.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(normalizers): keep the shared group accessors and skip null items after NumberOfFrames

- Call addAccessors on the SharedFunctionalGroupsSequence item, so that
  both SharedFunctionalGroupsSequence.X and SharedFunctionalGroupsSequence[0].X
  work, also for a hand-built one-item array.
- The window guess skips a null per-frame item after NumberOfFrames and
  does not throw.
- Tests: a [null, {}] case in the completes-a-per-frame-sequence it.each,
  a null item after NumberOfFrames, a one-item shared array. The test
  "keeps a complete multiframe dataset unchanged" now uses NumberOfFrames 1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
wayfarer3130 and others added 5 commits November 25, 2026 20:33
…t of #665)

- An empty SharedFunctionalGroupsSequence array counts as missing. A
  one-item array gets the list accessors (addAccessors), so the shared
  groups the normalizer sets are written. A plain object stays as is.
- The per-frame sequence is filled up to NumberOfFrames. Existing items
  keep their content, and only an item without a FrameContentSequence
  gets one.
- A null per-frame item becomes an empty item; a null item after
  NumberOfFrames is kept and the window guess does not throw.
- planePositionGroup copies an array ImagePositionPatient per frame and
  passes a non-array value through.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…VR (port of #663)

- readRawBinary passes the word width of the resolved VR to
  _emitSplitValues, so an expectsRaw OW/OF/OD/OL/OV value (also a UN
  element with that dictionary VR) is read as little endian words.
  OB and an unresolved UN do not swap.
- A new wordWidth(tagInfo) helper gives the width from tagInfo.vr; the
  pixel data paths use it too, so a UN "ox" Pixel Data is OW.
- Add OV (Other 64-bit Very Long, 8 byte words, 32-bit length). 0.x read
  OV as UN, so an OV value and a UN value with dictionary VR OV (Extended
  Offset Table) were not swapped in Explicit VR Big Endian.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…byte order

- normalizers: copy PerFrameFunctionalGroupsSequence to a plain array before
  the fill, so that push never goes through the addAccessors Proxy of a
  naturalized one-item sequence (item 0 got keys "1", "2" and the write threw).
- normalizers: restore ImageNormalizer.framesInPixelData as a deprecated
  static method; the normalizer does not call it.
- normalizers: the doc comment says that a shared sequence with 2 or more
  items keeps only item 0.
- AsyncDicomReader: _emitSplitValues and readUncompressed decide the Big
  Endian swap from the stream byte order, so that the Little Endian items of a
  UN sequence in a Big Endian file are not swapped.
- AsyncDicomReader: fix the stale readRawBinary doc comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… items

A one-frame per-frame sequence from naturalizeDataset keeps its list
accessors, as in 0.53.6. Comment why the 1-bit pixel path can use the
file syntax for the swap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wayfarer3130
wayfarer3130 marked this pull request as ready for review November 26, 2026 02:23
@wayfarer3130

Copy link
Copy Markdown
Contributor Author

This PR is ready for your review.

The changes in this PR come from the 1.0-beta work. During the review of the 1.0-beta ports, we found "should fix" issues that also apply to 0.x. This PR is the single 0.x PR for those fixes:

A clean review checked each change. The reviews found one blocker and some smaller items, and this PR fixes them. The section "Behavior changes" of the PR description lists the changes that a user can see. ImageNormalizer.framesInPixelData stays as a deprecated method.

CI passes on 93af75f. npm test passes 459 tests.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants