-
Notifications
You must be signed in to change notification settings - Fork 23
fix: Decode partial htj2k stream #68
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
wayfarer3130
wants to merge
2
commits into
main
Choose a base branch
from
fix/htj2k-partial
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Submodule openjph
updated
86 files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,103 +2,119 @@ | |
| // SPDX-License-Identifier: MIT | ||
|
|
||
| let openjphjs = require("../../dist/openjphjs.js") | ||
| const assert = require("assert") | ||
| const fs = require("fs") | ||
| const path = require("path") | ||
|
|
||
| function decode(openjph, encodedImagePath, iterations = 100) { | ||
| const encodedBitStream = fs.readFileSync(encodedImagePath) | ||
| const decoder = new openjph.HTJ2KDecoder() | ||
| const encodedBuffer = decoder.getEncodedBuffer(encodedBitStream.length) | ||
| encodedBuffer.set(encodedBitStream) | ||
| const rawPath = path.resolve(__dirname, "../fixtures/raw/CT1.RAW") | ||
| const frameInfo = { | ||
| width: 512, | ||
| height: 512, | ||
| bitsPerSample: 16, | ||
| componentCount: 1, | ||
| isSigned: true, | ||
| isUsingColorTransform: false, | ||
| } | ||
|
|
||
| function encodeFrame(openjph, rawBytes, imageFrame, options = {}) { | ||
| const encoder = new openjph.HTJ2KEncoder() | ||
| const decodedBytes = encoder.getDecodedBuffer(imageFrame) | ||
| decodedBytes.set(rawBytes) | ||
|
|
||
| // do the actual benchmark | ||
| const beginDecode = process.hrtime() | ||
| for (var i = 0; i < iterations; i++) { | ||
| decoder.decode() | ||
| if (typeof options.lossless === "boolean") { | ||
| encoder.setQuality(options.lossless, options.quantizationStep || 0) | ||
| } | ||
| const decodeDuration = process.hrtime(beginDecode) // hrtime returns seconds/nanoseconds tuple | ||
| const decodeDurationInSeconds = | ||
| decodeDuration[0] + decodeDuration[1] / 1000000000 | ||
|
|
||
| // Print out information about the decode | ||
| console.log( | ||
| "Decode of " + | ||
| encodedImagePath + | ||
| " took " + | ||
| (decodeDurationInSeconds / iterations) * 1000 + | ||
| " ms" | ||
| ) | ||
| const frameInfo = decoder.getFrameInfo() | ||
| console.log(" frameInfo = ", frameInfo) | ||
| console.log(" imageOffset = ", decoder.getImageOffset()) | ||
| var decoded = decoder.getDecodedBuffer() | ||
| console.log(" decoded length = ", decoded.length) | ||
| encoder.encode() | ||
| const encoded = Uint8Array.from(encoder.getEncodedBuffer()) | ||
| encoder.delete() | ||
| return encoded | ||
| } | ||
|
|
||
| function decodeFrame(openjph, encodedBytes) { | ||
| const decoder = new openjph.HTJ2KDecoder() | ||
| const encodedBuffer = decoder.getEncodedBuffer(encodedBytes.length) | ||
| encodedBuffer.set(encodedBytes) | ||
| decoder.decode() | ||
| const decoded = Uint8Array.from(decoder.getDecodedBuffer()) | ||
| const decodedFrameInfo = decoder.getFrameInfo() | ||
| decoder.delete() | ||
| return { decoded, decodedFrameInfo } | ||
| } | ||
|
|
||
| function encode( | ||
| openjph, | ||
| pathToUncompressedImageFrame, | ||
| imageFrame, | ||
| pathToJ2CFile, | ||
| iterations = 100 | ||
| ) { | ||
| const uncompressedImageFrame = fs.readFileSync(pathToUncompressedImageFrame) | ||
| console.log("uncompressedImageFrame.length:", uncompressedImageFrame.length) | ||
| const encoder = new openjph.HTJ2KEncoder() | ||
| const decodedBytes = encoder.getDecodedBuffer(imageFrame) | ||
| decodedBytes.set(uncompressedImageFrame) | ||
| //encoder.setQuality(false, 0.001); | ||
| function meanAbsoluteErrorI16(originalBytes, decodedBytes) { | ||
| assert.strictEqual( | ||
| decodedBytes.length, | ||
| originalBytes.length, | ||
| "Decoded byte length mismatch" | ||
| ) | ||
|
|
||
| const original = new Int16Array( | ||
| originalBytes.buffer, | ||
| originalBytes.byteOffset, | ||
| originalBytes.byteLength / Int16Array.BYTES_PER_ELEMENT | ||
| ) | ||
| const decoded = new Int16Array( | ||
| decodedBytes.buffer, | ||
| decodedBytes.byteOffset, | ||
| decodedBytes.byteLength / Int16Array.BYTES_PER_ELEMENT | ||
| ) | ||
|
|
||
| const encodeBegin = process.hrtime() | ||
| for (var i = 0; i < iterations; i++) { | ||
| encoder.encode() | ||
| let absoluteErrorSum = 0 | ||
| for (let i = 0; i < original.length; i++) { | ||
| absoluteErrorSum += Math.abs(original[i] - decoded[i]) | ||
| } | ||
| const encodeDuration = process.hrtime(encodeBegin) | ||
| const encodeDurationInSeconds = | ||
| encodeDuration[0] + encodeDuration[1] / 1000000000 | ||
|
|
||
| // print out information about the encode | ||
| console.log( | ||
| "Encode of " + | ||
| pathToUncompressedImageFrame + | ||
| " took " + | ||
| (encodeDurationInSeconds / iterations) * 1000 + | ||
| " ms" | ||
| return absoluteErrorSum / original.length | ||
| } | ||
|
|
||
| function runLossyRoundTripTest(openjph, rawBytes) { | ||
| const encodedLossy = encodeFrame(openjph, rawBytes, frameInfo, { | ||
| lossless: false, | ||
| quantizationStep: 8, | ||
| }) | ||
| const { decoded, decodedFrameInfo } = decodeFrame(openjph, encodedLossy) | ||
| const mae = meanAbsoluteErrorI16(rawBytes, decoded) | ||
|
|
||
| assert.strictEqual(decodedFrameInfo.width, frameInfo.width) | ||
| assert.strictEqual(decodedFrameInfo.height, frameInfo.height) | ||
| console.log(`Heavy lossy round-trip MAE: ${mae.toFixed(2)}`) | ||
| assert.ok(mae < 1500, `Heavy lossy MAE too large: ${mae}`) | ||
| } | ||
|
|
||
| function runTruncatedLosslessDecodeTest(openjph, rawBytes) { | ||
| const encodedLossless = encodeFrame(openjph, rawBytes, frameInfo, { | ||
| lossless: true, | ||
| quantizationStep: 0, | ||
| }) | ||
| const truncatedSize = Math.min(10 * 1024, encodedLossless.length) | ||
| const truncatedBitstream = encodedLossless.slice(0, truncatedSize) | ||
|
Comment on lines
+90
to
+91
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win Guarantee partial-stream coverage.
📍 Affects 2 files
🤖 Prompt for AI Agents |
||
| const { decoded, decodedFrameInfo } = decodeFrame(openjph, truncatedBitstream) | ||
| assert.ok( | ||
| decoded.length > 0, | ||
| `Expected a minimally decodable image from ${truncatedSize} bytes` | ||
| ) | ||
| const encodedBytes = encoder.getEncodedBuffer() | ||
| console.log(" encoded length=", encodedBytes.length) | ||
| const mae = meanAbsoluteErrorI16(rawBytes, decoded) | ||
|
|
||
| if (pathToJ2CFile) { | ||
| //fs.writeFileSync(pathToJ2CFile, encodedBytes); | ||
| } | ||
| // cleanup allocated memory | ||
| encoder.delete() | ||
| assert.strictEqual(decodedFrameInfo.width, frameInfo.width) | ||
| assert.strictEqual(decodedFrameInfo.height, frameInfo.height) | ||
| console.log( | ||
| `Truncated lossless decode MAE (${truncatedSize} bytes kept): ${mae.toFixed(2)}` | ||
| ) | ||
| assert.ok(mae > 10, `Expected degradation with truncated stream, MAE: ${mae}`) | ||
| assert.ok(mae < 300, `Truncated lossless MAE too large: ${mae}`) | ||
| } | ||
|
|
||
| function main(openjph) { | ||
| decode(openjph, "../fixtures/j2c/CT2.j2c") | ||
| decode(openjph, "../../extern/OpenJPH/subprojects/js/html/test.j2c") | ||
|
|
||
| encode( | ||
| openjph, | ||
| "../fixtures/raw/CT1.RAW", | ||
| { | ||
| width: 512, | ||
| height: 512, | ||
| bitsPerSample: 16, | ||
| componentCount: 1, | ||
| isSigned: true, | ||
| }, | ||
| "../fixtures/j2c/CT1.j2c" | ||
| ) | ||
| const rawBytes = fs.readFileSync(rawPath) | ||
| runLossyRoundTripTest(openjph, rawBytes) | ||
| runTruncatedLosslessDecodeTest(openjph, rawBytes) | ||
| console.log("openjphjs node tests passed") | ||
| } | ||
|
|
||
| if (typeof openjphjs !== "undefined") { | ||
| console.log("testing openjphjs...") | ||
| openjphjs().then(function (openjphwasm) { | ||
| main(openjphwasm) | ||
| }) | ||
| console.log("running openjphjs node tests...") | ||
| openjphjs().then(main) | ||
| } else { | ||
| console.warn("openjphjs isn't defined"); | ||
| console.warn("openjphjs isn't defined") | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
Repository: cornerstonejs/codecs
Length of output: 31773
🏁 Script executed:
Repository: cornerstonejs/codecs
Length of output: 16378
🌐 Web query:
C++ std::vector resize preserves elements unchanged when size stays same documentation💡 Result:
Yes, the C++ standard explicitly states that std::vector::resize does nothing if the requested size equals the current size of the vector [1][2][3]. Because the function performs no operations when the size remains the same, all existing elements are preserved unchanged, and no iterators, references, or pointers to the elements are invalidated [4]. The C++ standard defines the effects of resize as follows: if the new size is less than the current size, it erases the excess elements at the end; if it is greater, it appends additional default-inserted or specified elements [5]. When the new size is identical to the current size, no elements are erased or appended, resulting in no changes to the container's state [5][4].
Citations:
Reset decoder result state after incomplete decode.
decode()anddecodeSubResolution()catch failures and return normally, but they leaveframeInfo_, metadata, andpDecoded_from previous successful decodes unchanged or only resized. Reused decoders must clear result state before each decode attempt, initialize the destination buffer before line pulls, and report a failure/completion status so callers do not return partial pixels or stale metadata.This applies to:
packages/openjphjs/src/HTJ2KDecoder.hpp#L156-L170packages/openjphjs/src/HTJ2KDecoder.hpp#L178-L192📍 Affects 1 file
packages/openjphjs/src/HTJ2KDecoder.hpp#L163-L169(this comment)packages/openjphjs/src/HTJ2KDecoder.hpp#L185-L191🤖 Prompt for AI Agents