Skip to content

fix: decode text in sequence items with the dataset's SpecificCharacterSet - #520

Closed
namespaceMarcello wants to merge 5 commits into
dcmjs-org:masterfrom
namespaceMarcello:fix/nested-sequence-charset
Closed

namespaceMarcello wants to merge 5 commits into
dcmjs-org:masterfrom
namespaceMarcello:fix/nested-sequence-charset

Conversation

@namespaceMarcello

@namespaceMarcello namespaceMarcello commented Sep 25, 2026 •

Copy link
Copy Markdown

Fixes #503
Fixes #508

Summary

With SpecificCharacterSet = ISO_IR 192, text at the top level of a dataset reads back correctly, but text inside a sequence item does not. "lesione – café 肝" comes back as "lesione â café è". This hits Structured Reports (ContentSequence), SEG segment labels and RTSTRUCT ROI names. Writing the dataset back makes the damage permanent.

@hromsdahl (#503) and @rkikinis (#508) both traced this, and @pieper agreed on #503 that it should be fixed. This PR follows the approach suggested in #503: the sub-stream gets the parent stream's decoder. To answer the question in #508: the character set is threaded down through sequence parsing, not resolved per item at naturalize time.

Cause

ReadBufferStream starts with new TextDecoder("latin1"). DicomMessage._read switches the decoder when it reads SpecificCharacterSet, but only on the stream it is reading. SequenceOfItems reads every item from a new stream made by BufferStream.more(), and that stream started again with the default decoder.

In the WHATWG Encoding standard, "latin1" is a label for windows-1252. That is why #508 sees cp1252 characters (€, “) and #503 sees Latin-1. It is the same bug.

Changes

  • ReadBufferStream accepts a decoder option and falls back to latin1 as before.
  • BufferStream.more() passes its decoder to the new stream. Items nested at any depth inherit it.
  • ParsedUnknownValue.read() had the same problem: a UN element whose tag has a known VR is re-read from a new stream, so a UN-encoded LO came back as mojibake too. It now passes the decoder as well.
  • _read still calls setDecoder on the stream it is reading. An item that declares its own SpecificCharacterSet changes the decoder for that item and the items inside it, not for its parent or the items after it, as PS3.5 7.5.3 requires. A test covers this now (see below).

AsyncDicomReader reads items in place on the same stream, so it already decoded inherited character sets correctly, and with this change the sync reader gives the same result for them. For a character set declared inside an item the two readers differ: AsyncDicomReader keeps it on after the item ends. That bug predates this PR and is fixed separately in #609.

Verified

  • Tests in test/data-encoding.test.js, all under ISO_IR 192:
    • Text in sequence items at depth 1 and 2, and a UN-encoded LO. On master both tests fail on the value (Received: "lesione â café è"). With the fix they pass.
    • A worklist-shaped data set whose first ScheduledProcedureStepSequence item declares ISO_IR 144, with that item's text written as ISO 8859-5 bytes (added in review). One comparison checks the patient name before the sequence, the first item's physician name and its nested CodeMeaning (Cyrillic), the second item's physician name and an element after the sequence (UTF-8). Without the fix the nested value comes back as ÀÕÝâÓÕÝ instead of Рентген. If an item could not switch its own decoder, the first item's name would come back as replacement characters. The second-item and after-sequence checks fail on AsyncDicomReader before fix: decode text in sequence items with the right SpecificCharacterSet (sync and async readers) #609.
    • The depth and worklist tests read their data four ways: in Explicit and Implicit VR Little Endian, each with the undefined lengths dcmjs writes and with every sequence and item rewritten to a defined length (added in review). Both kinds of item reach the same more() call in SequenceOfItems.readBytes.
  • Each new assertion was seen failing on its own. Passing the decoder only one level down fails only the depth-2 assertion. Not passing it in more() fails the depth and worklist tests in all four encodings, and not the UN test. Not passing it for UN fails only the UN test. Reading defined-length items two bytes short fails only the four defined-length cases, so the rewritten data does take that path.
  • The script from Sequence-nested string content decoded with Latin-1 instead of SpecificCharacterSet (UTF-8 mojibake) #503, run on the built bundle (pnpm run build): 0.52.0 from npm gives mojibake at depth 1, depth 2 and for UN. This branch gives the original text everywhere, the same as AsyncDicomReader.
  • With the tests above: the full jest suite on Node 24.13 and Node 22.23 (365 passed on each), pnpm run build, eslint and prettier --check on src/ and test/.

Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.

🤖 Generated with Claude Code

…erSet

ReadBufferStream starts with TextDecoder("latin1"), and more() creates a new
ReadBufferStream for every sequence item without passing the parent's decoder.
Text inside sequences (SR ContentSequence, SEG segment labels, RTSTRUCT ROI
names) was therefore decoded as windows-1252, which is what "latin1" means for
TextDecoder, even when SpecificCharacterSet is ISO_IR 192. Writing the dataset
back made the damage permanent.

more() now passes its decoder to the new stream. ParsedUnknownValue had the
same problem for UN elements re-read with their dictionary VR, and now passes
the decoder too.

Fixes dcmjs-org#503
Fixes dcmjs-org#508

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWHfLbjyVsKtycUjne5QSs
@netlify

netlify Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for dcmjs2 ready!

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

it("decodes text in sequence items at every depth", () => {
const dataset = writeAndRead(
DicomMetaDictionary.denaturalizeDataset({
SpecificCharacterSet: "ISO_IR 192",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DICOM allows the specific character set tag to be encoded in a sequence item, which dictates the decoding for that sequence item and datasets under it (overriding the root dataset specific character set). I would suggest creating an additional test for this specific case just to ensure you have the decoding right.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I've avoided the Specific Character Set implementations because it's complex, somewhat rare in practice, and highly variable in terms of implementation correctness (i.e. I understand there are at least some incorrect implementations in the wild).

So anything we do here should be accompanied by tests with either real data or synthetically generated data that mirrors real-world uses of this feature.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will note we had a problem testing dcmjs trying to process ISO_IR 192 results from a modality worklist server where all of the names were in sequence attributes and they were parsed wrong (and hence my interest and reason for the comment). In any case, at least testing to make sure the "correct" dicom encoding scenarios work would be a good first step.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@namespaceMarcello can you comment on the nested character set issue @stevewranovsky raised?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @pieper , I can't check this right now. As this PR has been open for three weeks and feedback was provided only three days ago, I need a little time to catch up on the details and review the issue raised by @stevewranovsky . I will update you soon.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @stevewranovsky for raising this, and @pieper for keeping it moving.

The standard says what you describe (PS3.5 7.5.3): a Specific Character Set in an item applies only to that item, and an item without one uses the character set of the data set that contains it. With this PR DicomMessage.readFile follows it. Each item is read from its own sub-stream, which starts with the parent's decoder, and an item's own (0008,0005) switches only that sub-stream, so it reaches the items nested in it and nothing else.

c00d644 adds the test you suggested, shaped like a worklist since that is where you hit it. It is an ISO_IR 192 data set whose first ScheduledProcedureStepSequence item declares ISO_IR 144, with that item's text written as ISO 8859-5 bytes. It checks five values in one comparison: the patient name before the sequence, the first item's physician name and the CodeMeaning in its nested code sequence (Cyrillic), then the second item's physician name and an element after the sequence (UTF-8). Without the fix in this PR, the nested item comes back as ÀÕÝâÓÕÝ instead of Рентген.

On real data, @pieper: the public files I know of with a character set inside an item, pydicom's chrSQEncoding.dcm and chrSQEncoding1.dcm, declare two ISO 2022 Japanese character sets, which dcmjs rejects as multiple character sets. So the test builds its data. If you have a real file with this shape, I can add it.

@stevewranovsky, on your worklist: if those items inherited ISO_IR 192 from the top level, this PR fixes that case. Master reads every item as windows-1252.

The same test, run on AsyncDicomReader, found a bug that predates this PR. That reader reads items on the parent's stream, so a character set declared in an item stays on after the item ends. The next item and the rest of the data set are decoded with it (Dupré^Anaïs comes back as DuprУЉ^AnaУЏs). It's fixed separately in #609, so this PR stays about the sync reader. That also corrects what the description here said: the two readers agreed only on inherited character sets. I've updated the description.

I also merged master in. It brings the Node 24 test fix (readFileAsArrayBuffer in test/testUtils.js), which should clear the test (24) failure here. The new runs are waiting for approval.

Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @namespaceMarcello - these are looking good. Let's see what @stevewranovsky has to say.

While we are on it, what do you think about Code Extensions? I shied away in the past because I never run into it and it seems a bit complex, but maybe we should handle it now that we can have Claude handle the details.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @pieper. Yes, I think Code Extensions are worth doing, in a separate PR so this one stays about sequence items.

Today a multi-valued (0008,0005) such as \ISO 2022 IR 149 makes DicomMessage.readFile throw "Using multiple character sets is not supported". With ignoreErrors, or in AsyncDicomReader, everything is decoded with the first value, so the text after an escape sequence comes out garbled. That is #373.

What I would do:

  • on read, split each text value (SH, LO, ST, LT, UC, UT, PN) at the ISO 2022 escape sequences and decode each run with the character set its escape selects, going back to the first value where PS3.5 6.1.2.5 requires it (at \, and at ^ and = in PN);
  • keep the output as it is now: UTF-8 strings, with (0008,0005) rewritten to ISO_IR 192, so only reading changes;
  • do it in both DicomMessage and AsyncDicomReader.

There is real data to test against: the files attached to #373, and the Japanese and Korean examples from PS3.5 Annexes H and I, which pydicom ships as test files (chrH31, chrH32, chrI2, chrJapMulti, chrKoreanMulti).

If that direction works for you, I'll write the plan on #373 and open the PR from there.

Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, having a tested implementation will be great.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests look good to me, thanks for doing the effort to fix this.

Also thanks for investigating the code extensions under #373, this is another one I would have eventually asked about fixing too.

namespaceMarcello and others added 2 commits October 17, 2026 20:33
PS3.5 7.5.3: a Specific Character Set in an item applies only to that item
and the items nested in it. The new test reads a worklist-shaped data set in
ISO_IR 192 whose first scheduled step declares ISO_IR 144, with that item's
text in ISO 8859-5 bytes, and checks the five values that tell the cases
apart: the item itself and its nested item in Cyrillic, the next item and the
element after the sequence still in UTF-8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The sub-stream and worklist tests now read their data four ways: in
Explicit and Implicit VR Little Endian, each with the undefined lengths
dcmjs writes and with every sequence and item rewritten to a defined
length. Both kinds of item reach the same more() call in
SequenceOfItems.readBytes.

Without the decoder in more() all eight cases fail; reading
defined-length items two bytes short fails only the four
defined-length cases.

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

Copy link
Copy Markdown
Author

I pushed 08eb339, which only touches the tests. The depth and worklist tests now read their data in Explicit and Implicit VR, each with the undefined lengths dcmjs writes and with every sequence and item rewritten to a defined length, so both kinds of item that reach more() are covered in both transfer syntaxes. The fix in src/ is unchanged; the description is updated to match.


Written by Claude Code (AI assistant) on behalf of @namespaceMarcello, who directs this work.

wayfarer3130 added a commit to namespaceMarcello/dcmjs that referenced this pull request Nov 24, 2026
…x nested charsets together

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

Copy link
Copy Markdown
Contributor

This PR is now part of #609. The sync fix (this PR) and the async fix (#609) must merge together, because each fix alone gives different results from the two readers. #609 contains the commits of this PR and the full description. Thank you for the fix.

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

Labels

None yet

Projects

None yet

4 participants