All files / dicomImageLoader/src/shared/decoders decodeJPEGLossless.ts

4.34% Statements 1/23
0% Branches 0/10
0% Functions 0/4
4.34% Lines 1/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67        428x                                                                                                                            
import type { ByteArray } from 'dicom-parser';
import type { Types } from '@cornerstonejs/core';
import type { WebWorkerDecodeConfig } from '../../types';
 
const local = {
  DecoderClass: undefined,
  decodeConfig: {} as WebWorkerDecodeConfig,
};
 
export function initialize(
  decodeConfig?: WebWorkerDecodeConfig
): Promise<void> {
  local.decodeConfig = decodeConfig;
 
  if (local.DecoderClass) {
    return Promise.resolve();
  }
 
  return new Promise((resolve, reject) => {
    import('jpeg-lossless-decoder-js').then(({ Decoder }) => {
      local.DecoderClass = Decoder;
      resolve();
    }, reject);
  });
}
 
async function decodeJPEGLossless(
  imageFrame: Types.IImageFrame,
  pixelData: ByteArray
): Promise<Types.IImageFrame> {
  await initialize();
 
  // check to make sure codec is loaded
  if (typeof local.DecoderClass === 'undefined') {
    throw new Error('No JPEG Lossless decoder loaded');
  }
 
  // Create a new decoder instance for each decode operation to ensure thread safety
  const decoder = new local.DecoderClass();
 
  const byteOutput = imageFrame.bitsAllocated <= 8 ? 1 : 2;
  const buffer = pixelData.buffer;
  const decompressedData = decoder.decode(
    buffer,
    pixelData.byteOffset,
    pixelData.length,
    byteOutput
  );
 
  if (imageFrame.pixelRepresentation === 0) {
    if (imageFrame.bitsAllocated === 16) {
      imageFrame.pixelData = new Uint16Array(decompressedData.buffer);
 
      return imageFrame;
    }
    // untested!
    imageFrame.pixelData = new Uint8Array(decompressedData.buffer);
 
    return imageFrame;
  }
  imageFrame.pixelData = new Int16Array(decompressedData.buffer);
 
  return imageFrame;
}
 
export default decodeJPEGLossless;