Repository navigation
fix: byte order of binary value fields in Explicit VR Big Endian - #622
Conversation
✅ Deploy Preview for dcmjs2 ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
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]>
7fbad6a to
d3f074b
Compare
|
Rebased onto current The rebase did produce one conflict worth flagging for review, in the same 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. |
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]>
…alue-fields Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
|
🎉 This PR is included in version 0.53.5 🎉 The release is available on: Your semantic-release bot 📦🚀 |
…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]>
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:OW,OF,OD, andOLvalue fields to the caller in the byte order of the file.Uint16Array,Float32Array,Float64Array, orUint32Array.How
A new file,
src/utilities/byteSwap.js, has two functions:swapBytesswaps in place, andswappedCopyswaps a copy for a write. dcmjs applies the swap per word width of the VR:OWOFOLODOBis a byte stream, and dcmjs never swaps it. dcmjs also does not swapUN, because PS3.5 §6.2.2 says to interpretUNasOB.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 useinstanceof ArrayBuffer. Buffers often come from a different realm, for example a worker, an iframe, or jsdom. In a different realm,instanceof ArrayBufferisfalsefor a valid buffer.The second commit fixes a path that the first commit does not fix. A
UNelement with a better VR in the dictionary goes throughParsedUnknownValue.ParsedUnknownValuereads the raw bytes again as the dictionary VR, from a stream that is always little endian. In big endian, aBitsAllocatedof 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:US,UL,FL, and other scalar VRsOW,OF,OD,OL"ox"→OWThe 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 / 2gave a fractional size tonew Uint16Arrayfor an odd byte count.BinaryRepresentation.read, and this PR removes that block. But the method is part of the public API.Tests
test/big-endian.test.jshas 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:
UNcases of the second read (see the table above)The fixture has one element of each word width:
OW,OF,OD, andOL(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 tomaster).ValueRepresentation.js.#605 makes
BufferStream.readUint8Arraymore robust. This PR changesreadUint16Array, 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
origin/masterinto the branch (75cafc9). The merge had no conflicts.origin/masterinto the branch again (17a07b0), after fix/bill un sq implicit vr ps35622 #496, fix(orientation): allocate matrix transform output with the input typed array type #602, fix: preserve empty sequence items when reading #608, fix: decode text in sequence items with the right SpecificCharacterSet (sync and async readers) #609, fix(dictionary): keep nameMap current when a tag is registered #625, and fix: use dictionary keywords for anonymizer tags #510. One conflict was inParsedUnknownValue.read(): the second read now gets the byte order from this PR and the decoder from fix: decode text in sequence items with the right SpecificCharacterSet (sync and async readers) #609.OL: 4tobinaryVRWordWidths(28268a0). Before this change, dcmjs did not swapOLvalues on read or on write.OLelement (0066,0040) with the values[0x01020304, 0xA0B0C0D0]to the fixture oftest/big-endian.test.js. The write test, the sync read test, and the async read test check the element. WithoutOL: 4, five tests fail.OL, changed the text about the byte order, and wrote the text in Simplified Technical English.28268a0:pnpm testpasses (28 suites, 383 tests),eslintgives no findings, andpnpm run format:checkpasses.