All files / dicomImageLoader/src decodeImageFrameWorker.js

2.75% Statements 4/145
0% Branches 0/107
0% Functions 0/12
2.77% Lines 4/144

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521                                              428x         428x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             428x                                       428x  
/* eslint-disable complexity */
import bilinear from './shared/scaling/bilinear';
import replicate from './shared/scaling/replicate';
import { expose } from 'comlink';
 
import decodeLittleEndian from './shared/decoders/decodeLittleEndian';
import decodeBigEndian from './shared/decoders/decodeBigEndian';
import decodeRLE from './shared/decoders/decodeRLE';
import decodeJPEGBaseline8Bit from './shared/decoders/decodeJPEGBaseline8Bit';
// import decodeJPEGBaseline12Bit from './shared/decoders/decodeJPEGBaseline12Bit';
import decodeJPEGBaseline12Bit from './shared/decoders/decodeJPEGBaseline12Bit-js';
import decodeJPEGLossless from './shared/decoders/decodeJPEGLossless';
import decodeJPEGLS from './shared/decoders/decodeJPEGLS';
import decodeJPEG2000 from './shared/decoders/decodeJPEG2000';
import decodeHTJ2K from './shared/decoders/decodeHTJ2K';
// Note that the scaling is pixel value scaling, which is applying a modality LUT
import applyModalityLUT from './shared/scaling/scaleArray';
import getMinMax from './shared/getMinMax';
import getPixelDataTypeFromMinMax, {
  validatePixelDataType,
} from './shared/getPixelDataTypeFromMinMax';
import isColorImage from './shared/isColorImage';
 
const imageUtils = {
  bilinear,
  replicate,
};
 
const typedArrayConstructors = {
  Uint8Array,
  Uint16Array,
  Int16Array,
  Float32Array,
  Uint32Array,
};
 
function postProcessDecodedPixels(imageFrame, options, start, decodeConfig) {
  const shouldShift =
    imageFrame.pixelRepresentation !== undefined &&
    imageFrame.pixelRepresentation === 1;
 
  const shift =
    shouldShift && imageFrame.bitsStored !== undefined
      ? 32 - imageFrame.bitsStored
      : undefined;
 
  if (shouldShift && shift !== undefined) {
    for (let i = 0; i < imageFrame.pixelData.length; i++) {
      imageFrame.pixelData[i] = (imageFrame.pixelData[i] << shift) >> shift;
    }
  }
 
  // Cache the pixelData reference quickly incase we want to set a targetBuffer _and_ scale.
  let pixelDataArray = imageFrame.pixelData;
  imageFrame.pixelDataLength = imageFrame.pixelData.length;
  const { min: minBeforeScale, max: maxBeforeScale } = getMinMax(
    imageFrame.pixelData
  );
 
  const canRenderFloat =
    typeof options.allowFloatRendering !== 'undefined'
      ? options.allowFloatRendering
      : true;
 
  // Sometimes the type is specified before the DICOM header data has been
  // read.  This is fine except for color data, where the wrong type gets
  // specified.  Don't use the target buffer in that case.
  let invalidType =
    isColorImage(imageFrame.photometricInterpretation) &&
    options.targetBuffer?.offset === undefined;
 
  const willScale = options.preScale?.enabled;
 
  const hasFloatRescale =
    willScale &&
    Object.values(options.preScale.scalingParameters).some(
      (v) => typeof v === 'number' && !Number.isInteger(v)
    );
 
  const disableScale =
    !options.preScale.enabled || (!canRenderFloat && hasFloatRescale);
 
  const type = options.targetBuffer?.type;
 
  // if there is a type, we need to check whether the min and max AFTER scale
  // are actually within the range of the type. If not, we need to convert the
  // pixel data to the correct type.
  if (type && options.preScale.enabled && !disableScale) {
    const scalingParameters = options.preScale.scalingParameters;
    const scaledValues = _calculateScaledMinMax(
      minBeforeScale,
      maxBeforeScale,
      scalingParameters
    );
    invalidType = !validatePixelDataType(
      scaledValues.min,
      scaledValues.max,
      typedArrayConstructors[type]
    );
  }
 
  if (type && !invalidType) {
    pixelDataArray = _handleTargetBuffer(
      options,
      imageFrame,
      typedArrayConstructors,
      pixelDataArray
    );
  } else if (options.preScale.enabled && !disableScale) {
    pixelDataArray = _handlePreScaleSetup(
      options,
      minBeforeScale,
      maxBeforeScale,
      imageFrame
    );
  } else {
    pixelDataArray = _getDefaultPixelDataArray(
      minBeforeScale,
      maxBeforeScale,
      imageFrame
    );
  }
 
  let minAfterScale = minBeforeScale;
  let maxAfterScale = maxBeforeScale;
 
  if (options.preScale.enabled && !disableScale) {
    const scalingParameters = options.preScale.scalingParameters;
    _validateScalingParameters(scalingParameters);
 
    const isRequiredScaling = _isRequiredScaling(scalingParameters);
 
    if (isRequiredScaling) {
      applyModalityLUT(pixelDataArray, scalingParameters);
      imageFrame.preScale = {
        ...options.preScale,
        scaled: true,
      };
 
      const scaledValues = _calculateScaledMinMax(
        minBeforeScale,
        maxBeforeScale,
        scalingParameters
      );
      minAfterScale = scaledValues.min;
      maxAfterScale = scaledValues.max;
    }
  } else if (disableScale) {
    imageFrame.preScale = {
      enabled: true,
      scaled: false,
    };
 
    minAfterScale = minBeforeScale;
    maxAfterScale = maxBeforeScale;
  }
 
  imageFrame.pixelData = pixelDataArray;
  imageFrame.smallestPixelValue = minAfterScale;
  imageFrame.largestPixelValue = maxAfterScale;
 
  const end = new Date().getTime();
  imageFrame.decodeTimeInMS = end - start;
 
  return imageFrame;
}
 
function _isRequiredScaling(scalingParameters) {
  const { rescaleSlope, rescaleIntercept, modality, doseGridScaling, suvbw } =
    scalingParameters;
 
  const hasRescaleValues =
    typeof rescaleSlope === 'number' && typeof rescaleIntercept === 'number';
  const isRTDOSEWithScaling =
    modality === 'RTDOSE' && typeof doseGridScaling === 'number';
  const isPTWithSUV = modality === 'PT' && typeof suvbw === 'number';
 
  return hasRescaleValues || isRTDOSEWithScaling || isPTWithSUV;
}
 
function _handleTargetBuffer(
  options,
  imageFrame,
  typedArrayConstructors,
  pixelDataArray
) {
  const {
    arrayBuffer,
    type,
    offset: rawOffset = 0,
    length: rawLength,
    rows,
  } = options.targetBuffer;
 
  const TypedArrayConstructor = typedArrayConstructors[type];
 
  if (!TypedArrayConstructor) {
    throw new Error(`target array ${type} is not supported, or doesn't exist.`);
  }
 
  if (rows && rows != imageFrame.rows) {
    scaleImageFrame(imageFrame, options.targetBuffer, TypedArrayConstructor);
  }
  const imageFrameLength = imageFrame.pixelDataLength;
 
  const offset = rawOffset;
  const length =
    rawLength !== null && rawLength !== undefined
      ? rawLength
      : imageFrameLength - offset;
 
  const imageFramePixelData = imageFrame.pixelData;
 
  if (length !== imageFramePixelData.length) {
    throw new Error(
      `target array for image does not have the same length (${length}) as the decoded image length (${imageFramePixelData.length}).`
    );
  }
 
  // TypedArray.Set is api level and ~50x faster than copying elements even for
  // Arrays of different types, which aren't simply memcpy ops.
  const typedArray = arrayBuffer
    ? new TypedArrayConstructor(arrayBuffer, offset, length)
    : new TypedArrayConstructor(length);
 
  typedArray.set(imageFramePixelData, 0);
 
  // If need to scale, need to scale correct array.
  pixelDataArray = typedArray;
  return pixelDataArray;
}
 
function _handlePreScaleSetup(
  options,
  minBeforeScale,
  maxBeforeScale,
  imageFrame
) {
  const scalingParameters = options.preScale.scalingParameters;
  _validateScalingParameters(scalingParameters);
 
  const scaledValues = _calculateScaledMinMax(
    minBeforeScale,
    maxBeforeScale,
    scalingParameters
  );
 
  return _getDefaultPixelDataArray(
    scaledValues.min,
    scaledValues.max,
    imageFrame
  );
}
 
function _getDefaultPixelDataArray(min, max, imageFrame) {
  const TypedArrayConstructor = getPixelDataTypeFromMinMax(min, max);
  // @ts-ignore
  const typedArray = new TypedArrayConstructor(imageFrame.pixelData.length);
  typedArray.set(imageFrame.pixelData, 0);
 
  return typedArray;
}
 
function _calculateScaledMinMax(minValue, maxValue, scalingParameters) {
  const { rescaleSlope, rescaleIntercept, modality, doseGridScaling, suvbw } =
    scalingParameters;
 
  if (modality === 'PT' && typeof suvbw === 'number' && !isNaN(suvbw)) {
    return {
      min: suvbw * (minValue * rescaleSlope + rescaleIntercept),
      max: suvbw * (maxValue * rescaleSlope + rescaleIntercept),
    };
  } else if (
    modality === 'RTDOSE' &&
    typeof doseGridScaling === 'number' &&
    !isNaN(doseGridScaling)
  ) {
    return {
      min: minValue * doseGridScaling,
      max: maxValue * doseGridScaling,
    };
  } else if (
    typeof rescaleSlope === 'number' &&
    typeof rescaleIntercept === 'number'
  ) {
    return {
      min: rescaleSlope * minValue + rescaleIntercept,
      max: rescaleSlope * maxValue + rescaleIntercept,
    };
  } else {
    return {
      min: minValue,
      max: maxValue,
    };
  }
}
 
function _validateScalingParameters(scalingParameters) {
  if (!scalingParameters) {
    throw new Error(
      'options.preScale.scalingParameters must be defined if preScale.enabled is true, and scalingParameters cannot be derived from the metadata providers.'
    );
  }
}
 
function createDestinationImage(
  imageFrame,
  targetBuffer,
  TypedArrayConstructor
) {
  const { samplesPerPixel } = imageFrame;
  const { rows, columns } = targetBuffer;
  const typedLength = rows * columns * samplesPerPixel;
  const pixelData = new TypedArrayConstructor(typedLength);
  const bytesPerPixel = pixelData.byteLength / typedLength;
  return {
    pixelData,
    rows,
    columns,
    frameInfo: {
      ...imageFrame.frameInfo,
      rows,
      columns,
    },
    imageInfo: {
      ...imageFrame.imageInfo,
      rows,
      columns,
      bytesPerPixel,
    },
  };
}
 
/** Scales the image frame, updating the frame in place with a new scaled
 * version of it (in place modification)
 */
function scaleImageFrame(imageFrame, targetBuffer, TypedArrayConstructor) {
  const dest = createDestinationImage(
    imageFrame,
    targetBuffer,
    TypedArrayConstructor
  );
  const { scalingType = 'replicate' } = targetBuffer;
  imageUtils[scalingType](imageFrame, dest);
  Object.assign(imageFrame, dest);
  imageFrame.pixelDataLength = imageFrame.pixelData.length;
  return imageFrame;
}
 
/**
 * Decodes the provided image frame.
 * This is an async function return the result, or you can provide an optional
 * callbackFn that is called with the results.
 */
export async function decodeImageFrame(
  imageFrame,
  transferSyntax,
  pixelData,
  decodeConfig,
  options,
  callbackFn
) {
  const start = new Date().getTime();
 
  let decodePromise = null;
 
  let opts;
 
  switch (transferSyntax) {
    case '1.2.840.10008.1.2':
    case '1.2.840.10008.1.2.1':
      // Implicit or Explicit VR Little Endian
      decodePromise = decodeLittleEndian(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.2':
      // Explicit VR Big Endian (retired)
      decodePromise = decodeBigEndian(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.1.99':
      // Deflate transfer syntax (deflated by dicomParser)
      decodePromise = decodeLittleEndian(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.5':
      // RLE Lossless
      decodePromise = decodeRLE(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.4.50':
      // JPEG Baseline lossy process 1 (8 bit)
      opts = {
        ...imageFrame,
      };
 
      decodePromise = decodeJPEGBaseline8Bit(pixelData, opts);
      break;
    case '1.2.840.10008.1.2.4.51':
      // JPEG Baseline lossy process 2 & 4 (12 bit)
      // opts = {
      //   ...imageFrame,
      // };
      // decodePromise = decodeJPEGBaseline12Bit(pixelData, opts);
      //throw new Error('Currently unsupported: 1.2.840.10008.1.2.4.51');
      decodePromise = decodeJPEGBaseline12Bit(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.4.57':
      // JPEG Lossless, Nonhierarchical (Processes 14)
      decodePromise = decodeJPEGLossless(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.4.70':
      // JPEG Lossless, Nonhierarchical (Processes 14 [Selection 1])
      decodePromise = decodeJPEGLossless(imageFrame, pixelData);
      break;
    case '1.2.840.10008.1.2.4.80':
      // JPEG-LS Lossless Image Compression
      opts = {
        signed: imageFrame.pixelRepresentation === 1, // imageFrame.signed,
        // shouldn't need...
        bytesPerPixel: imageFrame.bitsAllocated <= 8 ? 1 : 2,
        ...imageFrame,
      };
 
      decodePromise = decodeJPEGLS(pixelData, opts);
      break;
    case '1.2.840.10008.1.2.4.81':
      // JPEG-LS Lossy (Near-Lossless) Image Compression
      opts = {
        signed: imageFrame.pixelRepresentation === 1, // imageFrame.signed,
        // shouldn't need...
        bytesPerPixel: imageFrame.bitsAllocated <= 8 ? 1 : 2,
        ...imageFrame,
      };
 
      decodePromise = decodeJPEGLS(pixelData, opts);
      break;
    case '1.2.840.10008.1.2.4.90':
      opts = {
        ...imageFrame,
      };
 
      // JPEG 2000 Lossless
      // imageFrame, pixelData, decodeConfig, options
      decodePromise = decodeJPEG2000(pixelData, opts);
      break;
    case '1.2.840.10008.1.2.4.91':
      // JPEG 2000 Lossy
      opts = {
        ...imageFrame,
      };
 
      // JPEG 2000 Lossy
      // imageFrame, pixelData, decodeConfig, options
      decodePromise = decodeJPEG2000(pixelData, opts);
      break;
    case '3.2.840.10008.1.2.4.96':
    case '1.2.840.10008.1.2.4.201':
    case '1.2.840.10008.1.2.4.202':
    case '1.2.840.10008.1.2.4.203':
      // HTJ2K
      opts = {
        ...imageFrame,
      };
 
      decodePromise = decodeHTJ2K(pixelData, opts);
      break;
    default:
      throw new Error(`no decoder for transfer syntax ${transferSyntax}`);
  }
 
  /* Don't know if these work...
   // JPEG 2000 Part 2 Multicomponent Image Compression (Lossless Only)
   else if(transferSyntax === "1.2.840.10008.1.2.4.92")
   {
   return decodeJPEG2000(dataSet, frame);
   }
   // JPEG 2000 Part 2 Multicomponent Image Compression
   else if(transferSyntax === "1.2.840.10008.1.2.4.93")
   {
   return decodeJPEG2000(dataSet, frame);
   }
   */
 
  if (!decodePromise) {
    throw new Error('decodePromise not defined');
  }
 
  const decodedFrame = await decodePromise;
 
  const postProcessed = postProcessDecodedPixels(
    decodedFrame,
    options,
    start,
    decodeConfig
  );
 
  // Call the callbackFn to agree with older arguments
  callbackFn?.(postProcessed);
 
  return postProcessed;
}
 
const obj = {
  decodeTask({
    imageFrame,
    transferSyntax,
    decodeConfig,
    options,
    pixelData,
    callbackFn,
  }) {
    return decodeImageFrame(
      imageFrame,
      transferSyntax,
      pixelData,
      decodeConfig,
      options,
      callbackFn
    );
  },
};
 
expose(obj);