Skip to content

fix: byte order of binary value fields in Explicit VR Big Endian - #622

Merged
wayfarer3130 merged 5 commits into
masterfrom
big-endian-binary-value-fields
Nov 24, 2026
Merged

wayfarer3130 merged 5 commits into
masterfrom
big-endian-binary-value-fields

Conversation

@pieper

@pieper pieper commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

What

Explicit VR Big Endian (1.2.840.10008.1.2.2) stores the words of a value field with the most significant byte first (PS3.5 §7.3). dcmjs already read and wrote the scalar VRs and the string VRs correctly in this transfer syntax. The binary VRs were not correct:

  • dcmjs gave the OW, OF, OD, and OL value fields to the caller in the byte order of the file.
  • The caller views these value fields as Uint16Array, Float32Array, Float64Array, or Uint32Array.
  • Thus pixel data, LUT data, point coordinates, and point indexes had the wrong byte order, and dcmjs gave no warning.

How

A new file, src/utilities/byteSwap.js, has two functions: swapBytes swaps in place, and swappedCopy swaps a copy for a write. dcmjs applies the swap per word width of the VR:

VR Word width (bytes)
OW 2
OF 4
OL 4
OD 8

OB is a byte stream, and dcmjs never swaps it. dcmjs also does not swap UN, because PS3.5 §6.2.2 says to interpret UN as OB.

The in-memory form of a value is little endian. Typed arrays are little endian on all JavaScript platforms that dcmjs supports. Thus dcmjs swaps a big endian value to little endian on read, and swaps the value back to big endian on write.

Items for a careful review:

  • Read. getBuffer() already returns a copy. Thus the swap is in place, and the swap does not change the buffer that dcmjs reads from.

  • Write. The swap operates on a copy. Thus dcmjs does not change a value field that the caller gives. A test checks this behaviour.

  • AsyncDicomReader. The reader rounds the fragment size down to a whole number of words. Thus a word is never split across two fragments. A later swap cannot repair a split word.

  • asBytes() does not use instanceof ArrayBuffer. Buffers often come from a different realm, for example a worker, an iframe, or jsdom. In a different realm, instanceof ArrayBuffer is false for a valid buffer.

  • The second commit fixes a path that the first commit does not fix. A UN element with a better VR in the dictionary goes through ParsedUnknownValue. ParsedUnknownValue reads the raw bytes again as the dictionary VR, from a stream that is always little endian. In big endian, a BitsAllocated of 16 gave 4096. The byte order of the second read depends on the first read. The first read swaps only for a VR with multi-byte words:

    Dictionary VR Word width Raw read The second read must
    US, UL, FL, and other scalar VRs 1 no swap swap (this was the bug)
    OW, OF, OD, OL 2, 4, 8, 4 swaps not swap
    "ox" → OW 1 no swap swap

The PR also fixes BufferStream.readUint16Array:

  • while (i++ < sixlen) did not write element 0, and wrote one element past the end of the array. The typed array ignored that write, and gave no error.
  • length / 2 gave a fractional size to new Uint16Array for an odd byte count.
  • The method has no callers. Its only call site was the block of commented-out code in BinaryRepresentation.read, and this PR removes that block. But the method is part of the public API.

Tests

test/big-endian.test.js has 14 tests, and each test runs for both transfer syntaxes. The test builds the expected bytes with its own explicit VR encoder and parser, which are independent of the library. Thus the expected bytes on each side of a read or a write do not come from the code under test.

The tests cover these items:

  • write
  • sync read
  • async read
  • lossless round trips
  • the value of the caller does not change on write
  • the UN cases of the second read (see the table above)
  • transcode from big endian to little endian, and from little endian to big endian

The fixture has one element of each word width: OW, OF, OD, and OL (0066,0040).

Full test suite at the time of the first commits: 26 suites and 368 tests pass, on Node 22 and on Node 24.

Related PRs

Three PRs changed the handling of unknown VRs, all in DicomMessage.js: #600 (interpretUnknownVRInExplicit, closed), #492 (closed), and #496 (UN-encoded sequences per PS3.5 §6.2.2, merged to master).

  • Those PRs decide if dcmjs interprets a UN element as its dictionary VR.
  • The second commit of this PR fixes the byte order when dcmjs interprets a UN element as its dictionary VR, in ValueRepresentation.js.
  • The changes complement each other, and the text of the changes does not overlap.

#605 makes BufferStream.readUint8Array more robust. This PR changes readUint16Array, so the two PRs do not overlap.

Disclosure

This PR is AI-assisted, per the process in #517. I wrote the big endian work with Claude. I reviewed the work, and the second commit came from that review. See the comment below about the rebase and the interaction with GHSA-xwvm-687g-rm36. That part needs the most careful human review.

Maintainer edits

@netlify

netlify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for dcmjs2 ready!

Name Link
🔨 Latest commit 17a07b0
🔍 Latest deploy log https://app.netlify.com/projects/dcmjs2/deploys/6b061887c9667f8b67cba3e4
😎 Deploy Preview https://deploy-preview-622--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.

pieper and others added 2 commits October 28, 2026 15:27
Explicit VR Big Endian (1.2.840.10008.1.2.2) stores the words of a value
field most significant byte first (PS3.5 Section 7.3). Scalar and string
VRs were already handled, but the binary VRs were not: OW, OF and OD
value fields were handed to callers in the file's byte order while those
callers view them as Uint16Array/Float32Array/Float64Array, so pixel
data, LUT data and point coordinates silently came out byte swapped.

Add utilities/byteSwap.js and swap binary value fields on the way in and
out, per VR word width (OW 2, OF 4, OD 8; OB is a byte stream and is
never swapped, and neither is UN, which PS3.5 Section 6.2.2 says to
interpret as OB).

- read: getBuffer() already returns a copy, so the swap is in place and
  does not touch the buffer being read from.
- write: swap a copy, so a value field passed in by the caller is not
  modified on their behalf.
- AsyncDicomReader: fragment sizes are rounded down to a whole number of
  words, so a word is never split across two fragments, where no later
  swap could put it back together.
- asBytes() deliberately does not use `instanceof ArrayBuffer`: buffers
  regularly arrive from another realm - a worker, an iframe, jsdom -
  where that test is false for a perfectly good buffer.

Also fix BufferStream.readUint16Array, which `while (i++ < sixlen)` left
element 0 unwritten while running one element past the end of the array
(silently dropped, as it is a typed array), and which passed a
fractional length to `new Uint16Array` for an odd byte count. It has no
callers - its only call site was the commented-out block in
BinaryRepresentation.read that this commit removes - but it is public.

test/big-endian.test.js builds the expected bytes with its own explicit
VR encoder and parser, written independently of the library, so the
fixtures on either side of a read or a write do not come from the code
under test. It covers writing, reading, async reading, lossless round
trips, leaving the caller's value untouched, and transcoding between the
two syntaxes in both directions.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
A UN element whose dictionary entry gives a better VR is read by
ParsedUnknownValue, which reads the raw value field and then re-reads it
as that VR from a stream over those bytes. That stream was always
created little endian, so in Explicit VR Big Endian a UN element the
dictionary knows to be US, UL, SS, SL, FL, FD or AT came back byte
swapped - a BitsAllocated of 16 read as 4096.

Which byte order the second pass should use depends on whether the first
one already swapped, which it does only for a VR with multi-byte words:

  dictionary VR  word width  raw read   re-read must
  US, UL, FL...  1           no swap    swap (the bug)
  OW, OF, OD     2, 4, 8     swaps      not swap
  "ox" -> OW     1           no swap    swap

so the stream is little endian when the stream being read from was, or
when the raw read has already put the words in the host's order.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@pieper
pieper force-pushed the big-endian-binary-value-fields branch from 7fbad6a to d3f074b Compare October 28, 2026 19:28
@pieper

pieper commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto current master. The earlier Node 24 CI failure was not from this change — the branch was based on a five-month-old master and the six failing PersonName tests are fixed by commits it was missing.

The rebase did produce one conflict worth flagging for review, in the same BinaryRepresentation.read block this PR touches: master has since added the length clamp for GHSA-xwvm-687g-rm36, which reads only the bytes actually available rather than allocating a declared length the file controls. Both are kept — the clamp runs first and the swap operates on the clamped read:

const available = stream.endOffset - stream.offset;
if (length > available) {
    validationLog.warn(...);
    length = available;
}
const bytes = stream.getBuffer(stream.offset, stream.offset + length);
stream.increment(length);
if (!stream.isLittleEndian) {
    swapBytes(bytes, this.wordWidth);
}

That ordering matters: swapping before the clamp would have swapped past the end of the real data.

Full suite now passes on both Node 22 and Node 24: 26 suites / 368 tests.

wayfarer3130 pushed a commit that referenced this pull request Nov 11, 2026
OL was missing entirely. VRinstances held only OB, OD, OF and OW, so
createByTypeString("OL") fell through to the "Invalid vr type" path and
returned UN - an OL element could not be written at all, and reading one
gave back an element whose VR was wrong on the wire.

It is a stream of 32 bit words, so it behaves exactly like its siblings: a
32 bit length, a single value, no multiplicity. The implementation is the
same BinaryRepresentation subclass with "OL" added to length32VRs and
singleVRs.

What needs it: the large mesh attributes of Surface Segmentation. Triangle
Point Index List (0066,0023) is OW, and 16 bit indices cap a surface at
65535 points; Long Triangle Point Index List (0066,0041) is the OL form
that lifts the cap, along with its Edge (0066,0042) and Vertex (0066,0043)
counterparts. Surfaces of a few million vertices are ordinary output from a
marching-cubes or surface-nets pipeline, so this is not an edge case.

Two things a reviewer should know, neither of them fixed here:

- The dictionary that ships with dcmjs still lists (0066,0041) as UL with
  VM 3-3n. That is the definition CP-1365 left behind and CP-1499 ("Fix CP
  1365 setback with Long xxx Index List VR") corrected to OL/1. Writing by
  TAG is unaffected; writing by KEYWORD needs _vrMap to say which VR is
  meant, which already works and now has a test. Regenerating the
  dictionary is a separate change.
- OV (Other Very Long) is the same gap and is deliberately not included, to
  keep this to one topic. It would be the same three lines.

#622 adds a binaryVRWordWidths table for byte swapping in Explicit VR Big
Endian; when both land, OL needs an entry of 4 there, since PS3.5 requires
swapping within each 32 bit word. The two branches do not otherwise touch
the same lines.

All seven tests fail without the change.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
wayfarer3130 and others added 3 commits November 24, 2026 15:49
Add OL (4 byte words) to binaryVRWordWidths so OL values are swapped on
sync read, async read and write, and cover (0066,0040) in the big endian
test fixture. Say in the comments that the in-memory form is little
endian, rather than the host's byte order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflict in ParsedUnknownValue.read(): the re-read stream
keeps the byte order fix of this branch (bufferIsLittleEndian) and also
gets the decoder of the outer stream (from #609).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wayfarer3130
wayfarer3130 merged commit 3798ba3 into master Nov 24, 2026
20 checks passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 0.53.5 🎉

The release is available on:

Your semantic-release bot 📦🚀

wayfarer3130 added a commit that referenced this pull request Nov 25, 2026
Record master (d236313) as a parent with -s ours; the tree stays the 1.0-beta tree. Master fixes #657, #622, #510, #625 and #632 are not in 1.x and need ports.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
wayfarer3130 added a commit that referenced this pull request Nov 25, 2026
…t of #622) (#663)

* fix: byte order of binary value fields in Explicit VR Big Endian (port of #622)

Explicit VR Big Endian stores the words of OW, OF and OD (and OL / OV)
value fields most significant byte first. dcmjs 1.0 gave them to the
caller, and wrote them, in the order of the caller's memory.

- core: swapBytes / swappedCopy (utilities/byteSwap.js, exported);
  BinaryRepresentation.wordWidth; swap on read, swap a copy on write;
  ParsedUnknownValue re-reads in the right byte order;
  BufferStream.readUint16Array off-by-one.
- legacy: AsyncDicomReader cuts fragments to whole words and swaps them,
  also on the bit-packed path; a UN "ox" pixel data uses the OW width.
- The event-stream parser and StreamingPart10Writer go through core.
- test/big-endian.test.js: independent encoder; every reader and the
  writer, plus the CT1_UNC big endian / little endian fixture pair.
- bundle-size ceilings 1.085 / 1.068.

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

* fix(async): swap Big Endian OW pixel data before it is cut into frames

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.

The big endian test now runs for Explicit VR Big Endian only, with one
little endian write test as a control, and checks the odd frame case on
DicomMessage, AsyncDicomReader, fromPart10 and fromPart10Stream.

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

* docs: little endian binary values in memory for every transfer syntax; bundle-size ceilings

Add NAT-U-BIN-7 and NAT-I-BIN-4 to the naturalized dataset spec, a
MIGRATION.md note for callers that swapped the bytes themselves, and the
raw byte order and maxFragmentSize rounding to the AsyncDicomReader doc.
Set the bundle-size ceilings to the measured ratios (x1.08949, x1.07200).

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

* fix(async): swap expectsRaw OW/OF/OD words to little endian in Big Endian

AsyncDicomReader.readRawBinary now passes the word width of the VR to
_emitSplitValues, so a listener that returns expectsRaw gets OW, OF, OL,
OD and OV words as little endian, the same as on the other read paths.
OB, UN and other VRs keep the byte order of the file.

Use one VR list in NAT-U-BIN-7, MIGRATION.md and the AsyncDicomReader
skill doc: OW, OF and OD, and OL and OV where the VR is supported.

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

* test(bundle-size): raise the ceilings to 1.091 and 1.073 after the merge of 1.0-beta

dcmjs.js is 1,509,340 bytes (ratio 1.09022) and dcmjs.es.js is
1,456,286 bytes (ratio 1.07284) after the merge of #654, #656 and #647.

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

* fix(VR): give a VR with no registered class a word width of 1

A UN element whose dictionary VR is OV (or OL) with no registered VR
class, for example (7FE0,0001), now reads the same with DicomMessage,
fromPart10 and AsyncDicomReader: BinaryRepresentation.wordWidth is 1
for a type that Vrs does not hold, so no reader swaps it.

Docs: NAT-I-BIN-4 states this rule; NAT-U-BIN-7, MIGRATION.md and the
AsyncDicomReader skill say that a UN element whose dictionary VR is
OW, OF or OD reads as that VR and gets the swap. Fix the readRawBinary
doc comment (fragments of maxFragmentSize, not 64KB chunks) and rewrap
a long MIGRATION.md line.

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

* test(big-endian): read explicit OL and OV, and UN with dictionary VR OV, the same with every reader

With the OL and OV VR classes of #653, DicomMessage, fromPart10 and
AsyncDicomReader (normal and expectsRaw) give little endian words for
an explicit OL or OV value and for a UN value whose dictionary VR is
OV. Drop the stale "no OL VR class" sentence of the dataset comment.

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

* fix(VR): drop the Vrs check from wordWidth; name OL and OV in the swap docs

After #653, every key of WORD_WIDTHS has a built-in VR class, so the
Vrs check in BinaryRepresentation.wordWidth had no effect. NAT-I-BIN-4 now
says that a code not in WORD_WIDTHS, also one that registerVr adds, has a
width of 1. NAT-U-BIN-7, MIGRATION.md and the AsyncDicomReader skill doc
name OW, OF, OD, OL and OV for the swap and for the UN rule, and item 7 of
the skill doc lists SV and UV.

Tests: UN rows for OW (0028,1201) and OF (0066,0016), fromPart10Stream
in the every-reader check, SV in LENGTH_32_VRS, and a corrected comment
for (0066,0040).

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants