All files / metadata/src/utilities/metadataProvider ecgFromInstance.ts

9.39% Statements 14/149
1.94% Branches 2/103
27.27% Functions 3/11
8.82% Lines 12/136

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                                                                                                                                                                                                                                                                                    5074x                                                                                                                                                                                                                                                                                               128x           128x                   128x 128x           128x 5074x 5074x 5074x 5074x                                                     384x     384x        
/**
 * Builds the full ECG module (including waveformData.retrieveBulkData) from a
 * naturalized instance in NATURAL cache. Used by the typed provider so
 * ECGViewport can get data via metaData.get(MetadataModules.ECG, imageId)
 * without the legacy dicomImageLoader ECG provider.
 */
 
import { addTypedProvider } from '../../metaData';
import { MetadataModules } from '../../enums';
import type { TypedProvider } from '../../metaData';
 
export interface EcgModuleFull {
  numberOfWaveformChannels: number;
  numberOfWaveformSamples: number;
  samplingFrequency: number;
  waveformBitsAllocated: number;
  waveformSampleInterpretation: string;
  multiplexGroupLabel: string;
  channelDefinitionSequence: Array<{
    channelSourceSequence?: { codeMeaning?: string };
  }>;
  waveformData: {
    retrieveBulkData: () => Promise<Int16Array[]>;
  };
}
 
function base64ToUint8Array(base64: string): Uint8Array {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}
 
function convertBuffer(
  dataSrc: ArrayBuffer | Uint8Array,
  numberOfChannels: number,
  numberOfSamples: number,
  bits: number,
  type: string
): Int16Array[] {
  const data = new Uint8Array(dataSrc);
  if (bits === 16 && type === 'SS') {
    const ret: Int16Array[] = [];
    const bytesPerSample = 2;
    const totalBytes = bytesPerSample * numberOfChannels * numberOfSamples;
    const length = Math.min(data.length, totalBytes);
    for (let channel = 0; channel < numberOfChannels; channel++) {
      const buffer = new Int16Array(numberOfSamples);
      ret.push(buffer);
      let sampleI = 0;
      for (
        let sample = 2 * channel;
        sample < length;
        sample += 2 * numberOfChannels
      ) {
        const highByte = data[sample + 1];
        const lowByte = data[sample];
        const sign = highByte & 0x80;
        buffer[sampleI++] = sign
          ? 0xffff0000 | (highByte << 8) | lowByte
          : (highByte << 8) | lowByte;
      }
    }
    return ret;
  }
  return [];
}
 
function multipartDecode(response: ArrayBuffer): ArrayBuffer[] {
  const message = new Uint8Array(response);
  const separator = new TextEncoder().encode('\r\n\r\n');
  let offset = 0;
  const maxHeader = 1000;
  let headerEnd = -1;
  for (
    let i = 0;
    i < Math.min(message.length - separator.length, offset + maxHeader);
    i++
  ) {
    let found = true;
    for (let j = 0; j < separator.length; j++) {
      if (message[i + j] !== separator[j]) {
        found = false;
        break;
      }
    }
    if (found) {
      headerEnd = i;
      break;
    }
  }
  if (headerEnd === -1) return [response];
  const headerStr = new TextDecoder().decode(message.slice(0, headerEnd));
  const boundaryMatch = headerStr.match(/boundary=([^\s;]+)/i);
  const boundary = boundaryMatch
    ? new TextEncoder().encode(`--${boundaryMatch[1].replace(/"/g, '').trim()}`)
    : null;
  if (!boundary) return [response];
  const dataStart = headerEnd + separator.length;
  const components: ArrayBuffer[] = [];
  let idx = message.indexOf(boundary[0], dataStart);
  while (idx !== -1) {
    const nextSep = message.indexOf(separator[0], idx);
    if (nextSep === -1) break;
    const partStart = nextSep + separator.length;
    const nextBound = message.indexOf(boundary[0], partStart);
    const partEnd = nextBound === -1 ? message.length : nextBound - 2;
    if (partEnd > partStart) {
      components.push(response.slice(partStart, partEnd));
    }
    if (nextBound === -1) break;
    idx = message.indexOf(boundary[0], nextBound + boundary.length);
  }
  return components.length > 0 ? components : [response];
}
 
/**
 * Parse wadors: URL to get wadoRsRoot and studyUID for relative BulkDataURI.
 */
function parseWadoRsImageId(imageId: string): {
  wadoRsRoot?: string;
  studyUID?: string;
} {
  const uri = imageId.replace(/^wadors:/i, '');
  const studiesIndex = uri.indexOf('/studies/');
  if (studiesIndex === -1) return {};
  const wadoRsRoot = uri.substring(0, studiesIndex);
  const afterStudies = uri.substring(studiesIndex + 9);
  const nextSlash = afterStudies.indexOf('/');
  const studyUID =
    nextSlash !== -1 ? afterStudies.substring(0, nextSlash) : afterStudies;
  return { wadoRsRoot, studyUID };
}
 
/** Normalize sequence to array (handles makeArrayLike single-item and real arrays). */
function toArray<T>(seq: T[] | ArrayLike<T> | undefined): T[] {
  Eif (!seq) return [];
  if (Array.isArray(seq)) return seq;
  if (typeof (seq as ArrayLike<T>).length === 'number') {
    return Array.from(seq as ArrayLike<T>);
  }
  return [seq as T];
}
 
/**
 * Build full EcgModule from a naturalized instance (UpperCamelCase convention).
 */
export function buildEcgModuleFromInstance(
  instance: Record<string, unknown>,
  imageId?: string
): EcgModuleFull | null {
  const raw = instance.WaveformSequence as
    | ArrayLike<Record<string, unknown>>
    | undefined;
  const groups = toArray(raw);
  if (!groups.length) return null;
 
  const group = groups[0];
  const numberOfChannels = (group.NumberOfWaveformChannels as number) ?? 0;
  const numberOfSamples = (group.NumberOfWaveformSamples as number) ?? 0;
  const samplingFrequency = (group.SamplingFrequency as number) ?? 1;
  const bitsAllocated = (group.WaveformBitsAllocated as number) ?? 16;
  const sampleInterpretation =
    (group.WaveformSampleInterpretation as string) ?? 'SS';
  const multiplexGroupLabel = (group.MultiplexGroupLabel as string) ?? '';
 
  const channelDefSeq = toArray(
    group.ChannelDefinitionSequence as
      | ArrayLike<Record<string, unknown>>
      | undefined
  );
  const channelDefinitionSequence = channelDefSeq.map((ch) => {
    const srcSeqArr = toArray(
      ch.ChannelSourceSequence as ArrayLike<Record<string, unknown>> | undefined
    );
    const srcSeq = srcSeqArr[0];
    const codeMeaning = (srcSeq?.CodeMeaning as string) ?? '';
    return {
      channelSourceSequence: { codeMeaning },
    };
  });
 
  let waveformDataRaw = (group.WaveformData ?? group.waveformData) as
    | Record<string, unknown>
    | ArrayLike<Record<string, unknown>>
    | undefined;
  if (
    waveformDataRaw &&
    typeof (waveformDataRaw as ArrayLike<unknown>).length === 'number' &&
    (waveformDataRaw as ArrayLike<Record<string, unknown>>).length > 0
  ) {
    waveformDataRaw = (
      waveformDataRaw as ArrayLike<Record<string, unknown>>
    )[0];
  }
  const waveformData = (waveformDataRaw as Record<string, unknown>) ?? {};
  const { wadoRsRoot = undefined, studyUID = undefined } = imageId
    ? parseWadoRsImageId(imageId)
    : {};
 
  const retrieveBulkData = async (): Promise<Int16Array[]> => {
    // Binary file upload: AsyncDicomReader stores raw bytes as ArrayBuffer / TypedArray
    const wd = waveformData as unknown;
    if (
      wd instanceof ArrayBuffer ||
      (typeof ArrayBuffer !== 'undefined' &&
        ArrayBuffer.isView &&
        ArrayBuffer.isView(wd))
    ) {
      return convertBuffer(
        wd as ArrayBuffer | Uint8Array,
        numberOfChannels,
        numberOfSamples,
        bitsAllocated,
        sampleInterpretation
      );
    }
    if (waveformData.Value) return waveformData.Value as Int16Array[];
    if (waveformData.InlineBinary) {
      const raw = base64ToUint8Array(waveformData.InlineBinary as string);
      return convertBuffer(
        raw,
        numberOfChannels,
        numberOfSamples,
        bitsAllocated,
        sampleInterpretation
      );
    }
    if (
      typeof (
        waveformData as { retrieveBulkData?: () => Promise<Int16Array[]> }
      ).retrieveBulkData === 'function'
    ) {
      return (
        waveformData as { retrieveBulkData: () => Promise<Int16Array[]> }
      ).retrieveBulkData();
    }
    if (waveformData.BulkDataURI) {
      let url = waveformData.BulkDataURI as string;
      if (url.indexOf(':') === -1 && wadoRsRoot) {
        url = studyUID
          ? `${wadoRsRoot}/studies/${studyUID}/${url}`
          : `${wadoRsRoot}/${url}`;
      }
      const response = await fetch(url);
      const buffer = await response.arrayBuffer();
      const contentType = response.headers.get('content-type') || '';
      const decoded = contentType.includes('multipart')
        ? multipartDecode(buffer)[0]
        : buffer;
      return convertBuffer(
        decoded,
        numberOfChannels,
        numberOfSamples,
        bitsAllocated,
        sampleInterpretation
      );
    }
    console.warn(
      '[ecgFromInstance] No waveform data source found. group keys:',
      Object.keys(group),
      'waveformData keys:',
      Object.keys(waveformData)
    );
    throw new Error('[ecgFromInstance] No waveform data source found');
  };
 
  return {
    numberOfWaveformChannels: numberOfChannels,
    numberOfWaveformSamples: numberOfSamples,
    samplingFrequency,
    waveformBitsAllocated: bitsAllocated,
    waveformSampleInterpretation: sampleInterpretation,
    multiplexGroupLabel,
    channelDefinitionSequence,
    waveformData: { retrieveBulkData },
  };
}
 
/** Run after instanceLookup (INSTANCE_PRIORITY 5000) so we receive instance as data */
const ECG_FROM_INSTANCE_PRIORITY = 4_000;
 
/**
 * Typed provider: when data (instance from instanceLookup) has WaveformSequence,
 * return the full ECG module so ECGViewport gets waveformData.retrieveBulkData.
 */
const ecgFromInstanceProvider: TypedProvider = (next, query, data, options) => {
  const instance = data as Record<string, unknown> | undefined;
  const hasWaveform = instance && instance.WaveformSequence;
  if (!hasWaveform) {
    return next(query, data, options);
  }
  const result = buildEcgModuleFromInstance(instance, query);
  return result ?? next(query, data, options);
};
 
const ECG_AMPLITUDE_INDEX_SIZE = 65536;
const ECG_AMPLITUDE_OFFSET = 32768;
 
/**
 * CALIBRATION provider for ECG: when instance has WaveformSequence, return
 * sequenceOfUltrasoundRegions so measurement tools get physical units (time, mV).
 */
const ecgCalibrationProvider: TypedProvider = (next, query, data, options) => {
  const instance = data as Record<string, unknown> | undefined;
  const raw = instance?.WaveformSequence;
  const groups = toArray(raw as ArrayLike<Record<string, unknown>> | undefined);
  Eif (!groups.length) return next(query, data, options);
  const group = groups[0];
  const numberOfWaveformSamples =
    (group.NumberOfWaveformSamples as number) ?? 0;
  const samplingFrequency = (group.SamplingFrequency as number) ?? 1;
  const physicalDeltaX = 1 / (samplingFrequency || 1);
  const physicalDeltaY = 0.001;
  return {
    sequenceOfUltrasoundRegions: [
      {
        regionLocationMinX0: 0,
        regionLocationMaxX1: numberOfWaveformSamples,
        regionLocationMinY0: 0,
        regionLocationMaxY1: ECG_AMPLITUDE_INDEX_SIZE - 1,
        referencePixelX0: 0,
        referencePixelY0: ECG_AMPLITUDE_OFFSET,
        physicalDeltaX,
        physicalDeltaY,
        physicalUnitsXDirection: 4,
        physicalUnitsYDirection: -1,
        regionDataType: 1,
      },
    ],
  };
};
 
export function registerEcgFromInstanceProvider(): void {
  addTypedProvider(MetadataModules.ECG, ecgFromInstanceProvider, {
    priority: ECG_FROM_INSTANCE_PRIORITY,
  });
  addTypedProvider(MetadataModules.CALIBRATION, ecgCalibrationProvider, {
    priority: ECG_FROM_INSTANCE_PRIORITY,
  });
}