All files / packages/core/src/loaders imageLoader.ts

32.8% Statements 41/125
28.98% Branches 20/69
41.37% Functions 12/29
33.6% Lines 41/122

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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576                                                                                                                                    1x                                     127x 127x 127x 127x 1x 1x         126x   126x   125x     1x       1x     126x                                       133x         133x 133x 6x       127x 127x                         127x 127x           127x   127x                                   27x       27x                                 106x         106x     106x 100x         106x                           1x           1x 5x     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           105x                       3x 3x 3x               144x 103x   144x                                                                                
import cache from '../cache/cache';
import { ImageVolume } from '../cache';
import Events from '../enums/Events';
import eventTarget from '../eventTarget';
import {
  genericMetadataProvider,
  getBufferConfiguration,
  triggerEvent,
  uuidv4,
} from '../utilities';
import {
  IImage,
  ImageLoaderFn,
  IImageLoadObject,
  EventTypes,
  Point2,
  Point3,
  Mat3,
  PixelDataTypedArrayString,
  PixelDataTypedArray,
} from '../types';
import imageLoadPoolManager from '../requestPool/imageLoadPoolManager';
import { metaData } from '../';
 
export interface ImageLoaderOptions {
  priority: number;
  requestType: string;
  additionalDetails?: Record<string, unknown>;
  ignoreCache?: boolean;
}
 
interface DerivedImages {
  imageIds: Array<string>;
  promises: Array<Promise<IImage>>;
}
 
type LocalImageOptions = {
  scalarData?: PixelDataTypedArray;
  targetBufferType?: PixelDataTypedArrayString;
  dimensions?: Point2;
  spacing?: Point3;
  origin?: Point3;
  direction?: Mat3;
  /**
   * Skip creation of the actual buffer object.
   * In fact, this creates a very short buffer, as there are lots of places
   * assuming a buffer exists.
   * This can be used when there are alternative representations of the image data.
   */
  skipCreateBuffer?: boolean;
  /**
   * A method to call to update the image object when it gets added to the cache.
   * This can be used to create alternative representations of the image data,
   * such as a VoxelManager.
   */
  onCacheAdd?: (image: IImage) => void;
};
 
type DerivedImageOptions = LocalImageOptions & {
  imageId?: string;
  targetBufferType?: PixelDataTypedArrayString;
};
 
/**
 * This module deals with ImageLoaders, loading images and caching images
 */
const imageLoaders = {};
let unknownImageLoader;
 
/**
 * Loads an image using a registered Cornerstone Image Loader.
 *
 * The image loader that is used will be
 * determined by the image loader scheme matching against the imageId.
 *
 * @param imageId - A Cornerstone Image Object's imageId
 * @param Options - to be passed to the Image Loader
 *
 * @returns - An Object which can be used to act after an image is loaded or loading fails
 */
function loadImageFromImageLoader(
  imageId: string,
  options: ImageLoaderOptions
): IImageLoadObject {
  // Extract the image loader scheme: wadors:https://image1 => wadors
  const colonIndex = imageId.indexOf(':');
  const scheme = imageId.substring(0, colonIndex);
  const loader = imageLoaders[scheme];
  if (loader === undefined || loader === null) {
    Eif (unknownImageLoader !== undefined) {
      return unknownImageLoader(imageId);
    }
    throw new Error('loadImageFromImageLoader: no image loader for imageId');
  }
  // Load using the registered loader
  const imageLoadObject = loader(imageId, options);
  // Broadcast an image loaded event once the image is loaded
  imageLoadObject.promise.then(
    function (image) {
      triggerEvent(eventTarget, Events.IMAGE_LOADED, { image });
    },
    function (error) {
      const errorObject: EventTypes.ImageLoadedFailedEventDetail = {
        imageId,
        error,
      };
      triggerEvent(eventTarget, Events.IMAGE_LOAD_FAILED, errorObject);
    }
  );
  return imageLoadObject;
}
 
/**
 * Gets the imageLoadObject by 1) Looking in to the cache to see if the
 * imageLoadObject has already been cached, 2) Checks inside the volume cache
 * to see if there is a volume that contains the same imageURI for the requested
 * imageID 3) Checks inside the imageCache for similar imageURI that might have
 * been stored as a result of decaching a volume 4) Finally if none were found
 * it request it from the registered imageLoaders.
 *
 * @param imageId - A Cornerstone Image Object's imageId
 * @param options - Options to be passed to the Image Loader
 *
 * @returns An Object which can be used to act after an image is loaded or loading fails
 */
function loadImageFromCacheOrVolume(
  imageId: string,
  options: ImageLoaderOptions
): IImageLoadObject {
  Iif (options.ignoreCache) {
    return loadImageFromImageLoader(imageId, options);
  }
 
  // 1. Check inside the image cache for imageId
  let imageLoadObject = cache.getImageLoadObject(imageId);
  if (imageLoadObject !== undefined) {
    return imageLoadObject;
  }
  // 2. Check if there exists a volume in the cache containing the imageId,
  // we copy the pixelData over.
  const cachedVolumeInfo = cache.getVolumeContainingImageId(imageId);
  Iif (cachedVolumeInfo?.volume?.loadStatus?.loaded) {
    // 2.1 Convert the volume at the specific slice to a cornerstoneImage object.
    // this will copy the pixel data over.
    const { volume, imageIdIndex } = cachedVolumeInfo;
 
    if (volume instanceof ImageVolume) {
      imageLoadObject = volume.convertToCornerstoneImage(imageId, imageIdIndex);
    }
    return imageLoadObject;
  }
  // 3. If no volume found, we search inside the imageCache for the imageId
  // that has the same URI which had been cached if the volume was converted
  // to an image
  const cachedImage = cache.getCachedImageBasedOnImageURI(imageId);
  Iif (cachedImage) {
    imageLoadObject = cachedImage.imageLoadObject;
    return imageLoadObject;
  }
  // 4. if not in image cache nor inside the volume cache, we request the
  // image loaders to load it
  imageLoadObject = loadImageFromImageLoader(imageId, options);
 
  return imageLoadObject;
}
 
/**
 * Loads an image given an imageId and optional priority and returns a promise
 * which will resolve to the loaded image object or fail if an error occurred.
 * The loaded image is not stored in the cache.
 *
 *
 * @param imageId - A Cornerstone Image Object's imageId
 * @param options - Options to be passed to the Image Loader
 *
 * @returns An Object which can be used to act after an image is loaded or loading fails
 */
export function loadImage(
  imageId: string,
  options: ImageLoaderOptions = { priority: 0, requestType: 'prefetch' }
): Promise<IImage> {
  Iif (imageId === undefined) {
    throw new Error('loadImage: parameter imageId must not be undefined');
  }
 
  return loadImageFromCacheOrVolume(imageId, options).promise;
}
 
/**
 * Loads an image given an imageId and optional priority and returns a promise
 * which will resolve to the loaded image object or fail if an error occurred.
 * The image is stored in the cache.
 *
 * @param imageId -  A Cornerstone Image Object's imageId
 * @param options - Options to be passed to the Image Loader
 *
 * @returns Image Loader Object
 */
export function loadAndCacheImage(
  imageId: string,
  options: ImageLoaderOptions = { priority: 0, requestType: 'prefetch' }
): Promise<IImage> {
  Iif (imageId === undefined) {
    throw new Error(
      'loadAndCacheImage: parameter imageId must not be undefined'
    );
  }
  const imageLoadObject = loadImageFromCacheOrVolume(imageId, options);
 
  // if not inside cache, store it
  if (!cache.getImageLoadObject(imageId)) {
    cache.putImageLoadObject(imageId, imageLoadObject).catch((err) => {
      console.warn(err);
    });
  }
 
  return imageLoadObject.promise;
}
 
/**
 * Load and cache a list of imageIds
 *
 * @param imageIds - list of imageIds
 * @param options - options for loader
 *
 */
export function loadAndCacheImages(
  imageIds: Array<string>,
  options: ImageLoaderOptions = { priority: 0, requestType: 'prefetch' }
): Promise<IImage>[] {
  Iif (!imageIds || imageIds.length === 0) {
    throw new Error(
      'loadAndCacheImages: parameter imageIds must be list of image Ids'
    );
  }
 
  const allPromises = imageIds.map((imageId) => {
    return loadAndCacheImage(imageId, options);
  });
 
  return allPromises;
}
 
/**
 * Loads an image given an imageId and optional priority and returns a promise
 * which will resolve to the loaded image object or fail if an error occurred.
 * The image is stored in the cache.
 *
 * @param referencedImageId -  A Cornerstone Image Object's imageId
 * @param options - Options to be passed to the Image Loader
 *
 * @returns Image Loader Object
 */
export function createAndCacheDerivedImage(
  referencedImageId: string,
  options: DerivedImageOptions = {},
  preventCache = false
): Promise<IImage> {
  if (referencedImageId === undefined) {
    throw new Error(
      'createAndCacheDerivedImage: parameter imageId must not be undefined'
    );
  }
 
  if (options.imageId === undefined) {
    options.imageId = `derived:${uuidv4()}`;
  }
 
  const { imageId, skipCreateBuffer, onCacheAdd } = options;
 
  const imagePlaneModule = metaData.get('imagePlaneModule', referencedImageId);
 
  const length = imagePlaneModule.rows * imagePlaneModule.columns;
 
  const { TypedArrayConstructor } = getBufferConfiguration(
    options.targetBufferType,
    length
  );
 
  // Use a buffer of size 1 for no data
  const imageScalarData = new TypedArrayConstructor(
    skipCreateBuffer ? 1 : length
  );
  const derivedImageId = imageId;
 
  ['imagePixelModule', 'imagePlaneModule', 'generalSeriesModule'].forEach(
    (type) => {
      genericMetadataProvider.add(derivedImageId, {
        type,
        metadata: metaData.get(type, referencedImageId),
      });
    }
  );
 
  const localImage = createAndCacheLocalImage(
    { scalarData: imageScalarData, onCacheAdd, skipCreateBuffer },
    imageId,
    true
  );
 
  const imageLoadObject = {
    promise: Promise.resolve(localImage),
  };
 
  if (!preventCache) {
    cache.putImageLoadObject(derivedImageId, imageLoadObject);
  }
  return imageLoadObject.promise;
}
 
/**
 * Load and cache a list of imageIds
 *
 * @param referencedImageIds - list of imageIds
 * @param options
 * @param options.getDerivedImageId - function to get the derived imageId
 * @param options.targetBufferType - target buffer type
 * @param options.skipBufferCreate - avoid creating the buffer
 */
export function createAndCacheDerivedImages(
  referencedImageIds: Array<string>,
  options: DerivedImageOptions & {
    getDerivedImageId?: (referencedImageId: string) => string;
    targetBufferType?: PixelDataTypedArrayString;
  } = {}
): DerivedImages {
  if (referencedImageIds?.length === 0) {
    throw new Error(
      'createAndCacheDerivedImages: parameter imageIds must be list of image Ids'
    );
  }
 
  const derivedImageIds = [];
  const allPromises = referencedImageIds.map((referencedImageId) => {
    const newOptions: DerivedImageOptions = {
      imageId:
        options.getDerivedImageId?.(referencedImageId) || `derived:${uuidv4()}`,
      ...options,
    };
    derivedImageIds.push(newOptions.imageId);
    return createAndCacheDerivedImage(referencedImageId, newOptions);
  });
 
  return { imageIds: derivedImageIds, promises: allPromises };
}
 
export function createAndCacheLocalImage(
  options: LocalImageOptions,
  imageId: string,
  preventCache = false
): IImage {
  const imagePlaneModule = metaData.get('imagePlaneModule', imageId);
 
  const length = imagePlaneModule.rows * imagePlaneModule.columns;
 
  const image = {
    imageId: imageId,
    intercept: 0,
    windowCenter: 0,
    windowWidth: 0,
    color: false,
    numComps: 1,
    slope: 1,
    minPixelValue: 0,
    maxPixelValue: 255,
    voiLUTFunction: undefined,
    rows: imagePlaneModule.rows,
    columns: imagePlaneModule.columns,
    getCanvas: undefined, // todo: which canvas?
    height: imagePlaneModule.rows,
    width: imagePlaneModule.columns,
    rgba: undefined, // todo: how
    columnPixelSpacing: imagePlaneModule.columnPixelSpacing,
    rowPixelSpacing: imagePlaneModule.rowPixelSpacing,
    invert: false,
  } as IImage;
 
  if (options.scalarData) {
    const imageScalarData = options.scalarData;
 
    if (
      !(
        imageScalarData instanceof Uint8Array ||
        imageScalarData instanceof Float32Array ||
        imageScalarData instanceof Uint16Array ||
        imageScalarData instanceof Int16Array
      )
    ) {
      throw new Error(
        'To use createLocalVolume you should pass scalarData of type Uint8Array, Uint16Array, Int16Array or Float32Array'
      );
    }
 
    image.sizeInBytes = imageScalarData.byteLength;
    image.getPixelData = () => imageScalarData;
  } else if (options.skipCreateBuffer !== true) {
    const { numBytes, TypedArrayConstructor } = getBufferConfiguration(
      options.targetBufferType,
      length
    );
 
    const imageScalarData = new TypedArrayConstructor(length);
 
    image.sizeInBytes = numBytes;
    image.getPixelData = () => imageScalarData;
  }
 
  // The onCacheAdd may modify the size in bytes for this image, which is ok,
  // as this is used after resolution for cache storage.  It may also do
  // thinks like adding alternative representations such as VoxelManager
  options.onCacheAdd?.(image);
 
  const imageLoadObject = {
    promise: Promise.resolve(image),
  };
 
  if (!preventCache) {
    cache.putImageLoadObject(image.imageId, imageLoadObject);
  }
 
  return image;
}
 
/**
 * Removes the imageId from the request pool manager and executes the `cancel`
 * function if it exists.
 *
 * @param imageId - A Cornerstone Image Object's imageId
 *
 */
export function cancelLoadImage(imageId: string): void {
  const filterFunction = ({ additionalDetails }) => {
    if (additionalDetails.imageId) {
      return additionalDetails.imageId !== imageId;
    }
 
    // for volumes
    return true;
  };
 
  // Instruct the request pool manager to filter queued
  // requests to ensure requests we no longer need are
  // no longer sent.
  imageLoadPoolManager.filterRequests(filterFunction);
 
  // TODO: Cancel decoding and retrieval as well (somehow?)
 
  // cancel image loading if in progress
  const imageLoadObject = cache.getImageLoadObject(imageId);
 
  if (imageLoadObject) {
    imageLoadObject.cancelFn();
  }
}
 
/**
 * Removes the imageIds from the request pool manager and calls the `cancel`
 * function if it exists.
 *
 * @param imageIds - Array of Cornerstone Image Object's imageIds
 *
 */
export function cancelLoadImages(imageIds: Array<string>): void {
  imageIds.forEach((imageId) => cancelLoadImage(imageId));
}
 
/**
 * Removes all the ongoing image loads by calling the `cancel` method on each
 * imageLoadObject. If no `cancel` method is available, it will be ignored.
 *
 */
export function cancelLoadAll(): void {
  const requestPool = imageLoadPoolManager.getRequestPool();
 
  Object.keys(requestPool).forEach((type: string) => {
    const requests = requestPool[type];
 
    Object.keys(requests).forEach((priority) => {
      const requestDetails = requests[priority].pop();
      const additionalDetails = requestDetails.additionalDetails as any;
      const { imageId, volumeId } = additionalDetails;
 
      let loadObject;
 
      if (imageId) {
        loadObject = cache.getImageLoadObject(imageId);
      } else if (volumeId) {
        loadObject = cache.getVolumeLoadObject(volumeId);
      }
      if (loadObject) {
        loadObject.cancel();
      }
    });
    // resetting the pool types to be empty
    imageLoadPoolManager.clearRequestStack(type);
 
    // TODO: Clear retrieval and decoding queues as well
  });
}
 
/**
 * Registers an imageLoader plugin with cornerstone for the specified scheme
 *
 * @param scheme - The scheme to use for this image loader (e.g. 'dicomweb', 'wadouri', 'http')
 * @param imageLoader - A Cornerstone Image Loader function
 */
export function registerImageLoader(
  scheme: string,
  imageLoader: ImageLoaderFn
): void {
  imageLoaders[scheme] = imageLoader;
}
/**
 * Registers a new unknownImageLoader and returns the previous one
 *
 * @param imageLoader - A Cornerstone Image Loader
 *
 * @returns The previous Unknown Image Loader
 */
export function registerUnknownImageLoader(
  imageLoader: ImageLoaderFn
): ImageLoaderFn {
  const oldImageLoader = unknownImageLoader;
  unknownImageLoader = imageLoader;
  return oldImageLoader;
}
/**
 * Removes all registered and unknown image loaders. This should be called
 * when the application is unmounted to prevent memory leaks.
 *
 */
export function unregisterAllImageLoaders(): void {
  Object.keys(imageLoaders).forEach(
    (imageLoader) => delete imageLoaders[imageLoader]
  );
  unknownImageLoader = undefined;
}
 
/**
 * Creates and caches derived segmentation images based on the referenced imageIds, this
 * is a helper function, we don't have segmentation concept in the cornerstone core; however,
 * this helper would make it clear that the segmentation images SHOULD be Uint8Array type
 * always until we have a better solution.
 *
 * @param referencedImageIds - An array of referenced image IDs.
 * @param options - The options for creating the derived images (default: { targetBufferType: 'Uint8Array' }).
 * @returns The derived images.
 */
export function createAndCacheDerivedSegmentationImages(
  referencedImageIds: Array<string>,
  options: DerivedImageOptions = {
    targetBufferType: 'Uint8Array',
  }
): DerivedImages {
  return createAndCacheDerivedImages(referencedImageIds, options);
}
 
/**
 * Creates and caches a derived segmentation image based on the referenced image ID.
 * this is a helper function, we don't have segmentation concept in the cornerstone core; however,
 * this helper would make it clear that the segmentation images SHOULD be Uint8Array type
 * always until we have a better solution.
 *
 * @param referencedImageId The ID of the referenced image.
 * @param options The options for creating the derived image (default: { targetBufferType: 'Uint8Array' }).
 * @returns A promise that resolves to the created derived segmentation image.
 */
export function createAndCacheDerivedSegmentationImage(
  referencedImageId: string,
  options: DerivedImageOptions = {
    targetBufferType: 'Uint8Array',
  }
): Promise<IImage> {
  return createAndCacheDerivedImage(referencedImageId, options);
}