All files / packages/streaming-image-volume-loader/src cornerstoneStreamingImageVolumeLoader.ts

56.7% Statements 55/97
33.33% Branches 20/60
50% Functions 7/14
56.79% Lines 46/81

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                                        1x                                                   1x           1x 1x 1x   10x               2x                                                             1x   1x               1x 1x 1x 1x         1x                 1x         1x           1x   1x             1x     1x 1x 1x         1x 1x 1x 1x 1x 1x     1x 1x     1x   2x         1x 1x 1x   1x                                                                                 1x                     1x                                               1x   1x 1x   1x   1x     1x 1x 1x                        
import {
  cache,
  utilities,
  Enums,
  imageLoader,
  imageLoadPoolManager,
  getShouldUseSharedArrayBuffer,
  getConfiguration,
  utilities as csUtils,
} from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { vec3 } from 'gl-matrix';
import { makeVolumeMetadata, sortImageIdsAndGetSpacing } from './helpers';
import StreamingImageVolume from './StreamingImageVolume';
 
const {
  createUint8SharedArray,
  createFloat32SharedArray,
  createUint16SharedArray,
  createInt16SharedArray,
} = utilities;
 
interface IVolumeLoader {
  promise: Promise<StreamingImageVolume>;
  cancel: () => void;
  decache: () => void;
}
 
/**
 * It handles loading of a image by streaming in its imageIds. It will be the
 * volume loader if the schema for the volumeID is `cornerstoneStreamingImageVolume`.
 * This function returns a promise that resolves to the StreamingImageVolume instance.
 *
 * In order to use the cornerstoneStreamingImageVolumeLoader you should use
 * createAndCacheVolume helper from the cornerstone-core volumeLoader module.
 *
 * @param volumeId - The ID of the volume
 * @param options - options for loading, imageIds
 * @returns a promise that resolves to a StreamingImageVolume
 */
function cornerstoneStreamingImageVolumeLoader(
  volumeId: string,
  options: {
    imageIds: string[];
  }
): IVolumeLoader {
  Iif (!options || !options.imageIds || !options.imageIds.length) {
    throw new Error(
      'ImageIds must be provided to create a streaming image volume'
    );
  }
 
  const { useNorm16Texture, preferSizeOverAccuracy } =
    getConfiguration().rendering;
  const use16BitDataType = useNorm16Texture || preferSizeOverAccuracy;
 
  Easync function getStreamingImageVolume() {
    /**
     * Check if we are using the `wadouri:` scheme, and if so, preload first,
     * middle, and last image metadata as these are the images the current
     * streaming image loader may explicitly request metadata from. The last image
     * metadata would only be specifically requested if the imageId array order is
     * reversed in the `sortImageIdsAndGetSpacing.ts` file.
     */
    if (options.imageIds[0].split(':')[0] === 'wadouri') {
      const [middleImageIndex, lastImageIndex] = [
        Math.floor(options.imageIds.length / 2),
        options.imageIds.length - 1,
      ];
      const indexesToPrefetch = [0, middleImageIndex, lastImageIndex];
      await Promise.all(
        indexesToPrefetch.map((index) => {
          return new Promise((resolve, reject) => {
            const imageId = options.imageIds[index];
            imageLoadPoolManager.addRequest(
              async () => {
                imageLoader
                  .loadImage(imageId)
                  .then(() => {
                    console.log(`Prefetched imageId: ${imageId}`);
                    resolve(true);
                  })
                  .catch((err) => {
                    reject(err);
                  });
              },
              Enums.RequestType.Prefetch,
              { volumeId },
              1 // priority
            );
          });
        })
      ).catch(console.error);
    }
 
    const { imageIds } = options;
 
    const volumeMetadata = makeVolumeMetadata(imageIds);
 
    // For a streaming volume, the data type cannot rely on cswil to load
    // the proper array buffer type. This is because the target buffer container
    // must be decided ahead of time.
    // TODO: move this logic into CSWIL to avoid logic duplication.
    // We check if scaling parameters are negative we choose Int16 instead of
    // Uint16 for cases where BitsAllocated is 16.
    const imageIdIndex = Math.floor(imageIds.length / 2);
    const imageId = imageIds[imageIdIndex];
    const scalingParameters = csUtils.getScalingParameters(imageId);
    const hasNegativeRescale =
      scalingParameters.rescaleIntercept < 0 ||
      scalingParameters.rescaleSlope < 0;
 
    const {
      BitsAllocated,
      PixelRepresentation,
      PhotometricInterpretation,
      ImageOrientationPatient,
      PixelSpacing,
      Columns,
      Rows,
    } = volumeMetadata;
 
    const rowCosineVec = vec3.fromValues(
      ImageOrientationPatient[0],
      ImageOrientationPatient[1],
      ImageOrientationPatient[2]
    );
    const colCosineVec = vec3.fromValues(
      ImageOrientationPatient[3],
      ImageOrientationPatient[4],
      ImageOrientationPatient[5]
    );
 
    const scanAxisNormal = vec3.create();
 
    vec3.cross(scanAxisNormal, rowCosineVec, colCosineVec);
 
    const { zSpacing, origin, sortedImageIds } = sortImageIdsAndGetSpacing(
      imageIds,
      scanAxisNormal
    );
 
    const numFrames = imageIds.length;
 
    // Spacing goes [1] then [0], as [1] is column spacing (x) and [0] is row spacing (y)
    const spacing = <Types.Point3>[PixelSpacing[1], PixelSpacing[0], zSpacing];
    const dimensions = <Types.Point3>[Columns, Rows, numFrames];
    const direction = [
      ...rowCosineVec,
      ...colCosineVec,
      ...scanAxisNormal,
    ] as Types.Mat3;
    const signed = PixelRepresentation === 1;
    const numComponents = PhotometricInterpretation === 'RGB' ? 3 : 1;
    const useSharedArrayBuffer = getShouldUseSharedArrayBuffer();
    const length = dimensions[0] * dimensions[1] * dimensions[2];
    const handleCache = (sizeInBytes) => {
      Iif (!cache.isCacheable(sizeInBytes)) {
        throw new Error(Enums.Events.CACHE_SIZE_EXCEEDED);
      }
      cache.decacheIfNecessaryUntilBytesAvailable(sizeInBytes);
    };
 
    let scalarData, sizeInBytes;
    switch (BitsAllocated) {
      case 8:
        if (signed) {
          throw new Error(
            '8 Bit signed images are not yet supported by this plugin.'
          );
        }
        sizeInBytes = length;
        handleCache(sizeInBytes);
        scalarData = useSharedArrayBuffer
          ? createUint8SharedArray(length)
          : new Uint8Array(length);
        break;
 
      case 16:
        // Temporary fix for 16 bit images to use Float32
        // until the new dicom image loader handler the conversion
        // correctly
        if (!use16BitDataType) {
          sizeInBytes = length * 4;
          scalarData = useSharedArrayBuffer
            ? createFloat32SharedArray(length)
            : new Float32Array(length);
 
          break;
        }
 
        sizeInBytes = length * 2;
        if (signed || hasNegativeRescale) {
          handleCache(sizeInBytes);
          scalarData = useSharedArrayBuffer
            ? createInt16SharedArray(length)
            : new Int16Array(length);
          break;
        }
 
        if (!signed && !hasNegativeRescale) {
          handleCache(sizeInBytes);
          scalarData = useSharedArrayBuffer
            ? createUint16SharedArray(length)
            : new Uint16Array(length);
          break;
        }
 
        // Default to Float32 again
        sizeInBytes = length * 4;
        handleCache(sizeInBytes);
        scalarData = useSharedArrayBuffer
          ? createFloat32SharedArray(length)
          : new Float32Array(length);
        break;
 
      case 24E:
        sizeInBytes = length * numComponents;
        handleCache(sizeInBytes);
 
        // hacky because we don't support alpha channel in dicom
        scalarData = useSharedArrayBuffer
          ? createUint8SharedArray(length * numComponents)
          : new Uint8Array(length * numComponents);
        break;
    }
 
    const streamingImageVolume = new StreamingImageVolume(
      // ImageVolume properties
      {
        volumeId,
        metadata: volumeMetadata,
        dimensions,
        spacing,
        origin,
        direction,
        scalarData,
        sizeInBytes,
      },
      // Streaming properties
      {
        imageIds: sortedImageIds,
        loadStatus: {
          // todo: loading and loaded should be on ImageVolume
          loaded: false,
          loading: false,
          cancelled: false,
          cachedFrames: [],
          callbacks: [],
        },
      }
    );
 
    return streamingImageVolume;
  }
 
  const streamingImageVolumePromise = getStreamingImageVolume();
 
  return {
    promise: streamingImageVolumePromise,
    decache: () => {
      streamingImageVolumePromise.then((streamingImageVolume) => {
        streamingImageVolume.destroy();
        streamingImageVolume = null;
      });
    },
    cancel: () => {
      streamingImageVolumePromise.then((streamingImageVolume) => {
        streamingImageVolume.cancelLoading();
      });
    },
  };
}
 
export default cornerstoneStreamingImageVolumeLoader;