All files / src/lib/barcodePicker cameraManager.ts

95.33% Statements 347/364
87.6% Branches 212/242
93.94% Functions 62/66
95.38% Lines 330/346

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 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 77415x 15x 15x 15x     15x 15x 15x 15x 15x                                         15x 15x 15x 15x 15x 15x 15x 15x 15x                     76x 76x 76x 76x 76x                                           76x 76x 76x     15x           59x 59x 59x 59x     15x 6x     15x 5x   7x 3x 3x 2x     2x       15x 6x     15x 5x   5x 3x 1x     2x       15x 6x     15x 5x   5x 2x 1x   1x         15x 6x     15x 5x   5x 2x 1x   1x         15x 57x     15x 149x     15x 58x     15x 28x       28x 28x   28x 22x     28x   17x         17x 10x 10x   10x       18x 12x   6x       15x 117x 22x     117x   117x 33x 33x 33x 33x 33x 33x 33x 33x   33x 33x       15x 3x   3x 1x     2x     15x 2x 1x         1x     15x 106x 53x 53x   53x   1x 1x   2x 2x     50x 50x   53x   53x     15x 11x 5x 5x   5x 10x         15x 2x 4x     15x 15x 9x   9x 9x 9x             18x             15x 12x 16x 7x 1x 6x 6x       9x     12x 16x   15x   8x 8x 2x   8x 4x 4x 4x   4x     1x     28x 28x   28x 22x           22x   44x 17x 17x 17x 17x           22x 22x         28x     15x 27x 27x       27x     18x 18x 18x 7x 7x 7x 1x         15x               15x 1x 2x       2x 1x 2x             15x 2x   2x 1x       4x           15x 8x 3x 3x 1x     2x 1x   1x     6x 6x 7x 5x 6x   7x     2x 4x 4x           15x 5x 1x   4x 4x       4x 3x   3x 3x 3x 3x 2x   2x     2x 1x             15x 5x 1x   4x 8x                     15x   17x 17x   17x 11x         15x 8x 8x   8x 3x 3x         2x 2x               15x 40x             15x   45x 45x 45x 13x       32x     35x 35x 70x       15x 35x 35x     15x 1x 2x       15x 1x 1x     15x         106x   34x                               53x       15x             24x 17x       7x       15x               62x                                     31x   7x     24x     70x 70x 1x   69x 69x 69x   69x   69x   38x 38x 38x                               38x 38x     38x     38x 38x 34x   38x 34x   38x 38x 38x 38x   62x         38x 38x         38x 38x 2x 2x     38x           38x 36x 36x       36x         20x 10x     20x     16x   16x 16x     157x         143x 2x 2x   2x     141x     14x 14x 7x 7x     14x       15x  
import { Camera } from "../camera";
import { CameraAccess } from "../cameraAccess";
import { CameraSettings } from "../cameraSettings";
import { CustomError } from "../customError";
import { GUI } from "./gui";
 
export enum MeteringMode {
  CONTINUOUS = "continuous",
  MANUAL = "manual",
  NONE = "none",
  SINGLE_SHOT = "single-shot",
}
 
export interface ExtendedMediaTrackCapabilities extends MediaTrackCapabilities {
  focusMode?: MeteringMode[];
  torch?: boolean;
  zoom?: {
    max: number;
    min: number;
    step: number;
  };
}
 
export interface ExtendedMediaTrackConstraintSet extends MediaTrackConstraintSet {
  torch?: boolean;
  zoom?: number;
}
 
/**
 * A barcode picker utility class used to handle camera interaction.
 */
export class CameraManager {
  private static readonly cameraAccessTimeoutMs: number = 4000;
  private static readonly cameraMetadataCheckTimeoutMs: number = 4000;
  private static readonly cameraMetadataCheckIntervalMs: number = 50;
  private static readonly getCapabilitiesTimeoutMs: number = 500;
  private static readonly autofocusIntervalMs: number = 1500;
  private static readonly manualToAutofocusResumeTimeoutMs: number = 5000;
  private static readonly manualFocusWaitTimeoutMs: number = 400;
  private static readonly noCameraErrorParameters: { name: string; message: string } = {
    name: "NoCameraAvailableError",
    message: "No camera available",
  };
 
  public selectedCamera?: Camera;
  public activeCamera?: Camera;
  public activeCameraSettings?: CameraSettings;
 
  private readonly triggerFatalError: (error: Error) => void;
  private readonly gui: GUI;
  private readonly postStreamInitializationListener: () => void = this.postStreamInitialization.bind(this);
  private readonly videoTrackUnmuteListener: () => void = this.videoTrackUnmuteRecovery.bind(this);
  private readonly triggerManualFocusListener: () => void = this.triggerManualFocus.bind(this);
  private readonly triggerZoomStartListener: () => void = this.triggerZoomStart.bind(this);
  private readonly triggerZoomMoveListener: () => void = this.triggerZoomMove.bind(this);
 
  private initialCameraType: Camera.Type;
  private selectedCameraSettings?: CameraSettings;
  private mediaStream?: MediaStream;
  private mediaTrackCapabilities?: ExtendedMediaTrackCapabilities;
  private cameraAccessTimeout: number;
  private cameraMetadataCheckInterval: number;
  private getCapabilitiesTimeout: number;
  private autofocusInterval: number;
  private manualToAutofocusResumeTimeout: number;
  private manualFocusWaitTimeout: number;
  private cameraSwitcherEnabled: boolean;
  private torchToggleEnabled: boolean;
  private tapToFocusEnabled: boolean;
  private pinchToZoomEnabled: boolean;
  private pinchToZoomDistance?: number;
  private pinchToZoomInitialZoom: number;
  private torchEnabled: boolean;
  private cameraInitializationPromise?: Promise<void>;
 
  constructor(triggerFatalError: (error: Error) => void, gui: GUI) {
    this.triggerFatalError = triggerFatalError;
    this.gui = gui;
    this.initialCameraType = Camera.Type.BACK;
  }
 
  public setInteractionOptions(
    cameraSwitcherEnabled: boolean,
    torchToggleEnabled: boolean,
    tapToFocusEnabled: boolean,
    pinchToZoomEnabled: boolean
  ): void {
    this.cameraSwitcherEnabled = cameraSwitcherEnabled;
    this.torchToggleEnabled = torchToggleEnabled;
    this.tapToFocusEnabled = tapToFocusEnabled;
    this.pinchToZoomEnabled = pinchToZoomEnabled;
  }
 
  public isCameraSwitcherEnabled(): boolean {
    return this.cameraSwitcherEnabled;
  }
 
  public async setCameraSwitcherEnabled(enabled: boolean): Promise<void> {
    this.cameraSwitcherEnabled = enabled;
 
    if (this.cameraSwitcherEnabled) {
      const cameras: Camera[] = await CameraAccess.getCameras();
      if (cameras.length > 1) {
        this.gui.setCameraSwitcherVisible(true);
      }
    } else {
      this.gui.setCameraSwitcherVisible(false);
    }
  }
 
  public isTorchToggleEnabled(): boolean {
    return this.torchToggleEnabled;
  }
 
  public setTorchToggleEnabled(enabled: boolean): void {
    this.torchToggleEnabled = enabled;
 
    if (this.torchToggleEnabled) {
      if (this.mediaStream != null && this.mediaTrackCapabilities?.torch === true) {
        this.gui.setTorchTogglerVisible(true);
      }
    } else {
      this.gui.setTorchTogglerVisible(false);
    }
  }
 
  public isTapToFocusEnabled(): boolean {
    return this.tapToFocusEnabled;
  }
 
  public setTapToFocusEnabled(enabled: boolean): void {
    this.tapToFocusEnabled = enabled;
 
    if (this.mediaStream != null) {
      if (this.tapToFocusEnabled) {
        this.enableTapToFocusListeners();
      } else {
        this.disableTapToFocusListeners();
      }
    }
  }
 
  public isPinchToZoomEnabled(): boolean {
    return this.pinchToZoomEnabled;
  }
 
  public setPinchToZoomEnabled(enabled: boolean): void {
    this.pinchToZoomEnabled = enabled;
 
    if (this.mediaStream != null) {
      if (this.pinchToZoomEnabled) {
        this.enablePinchToZoomListeners();
      } else {
        this.disablePinchToZoomListeners();
      }
    }
  }
 
  public setInitialCameraType(cameraType: Camera.Type): void {
    this.initialCameraType = cameraType;
  }
 
  public setSelectedCamera(camera?: Camera): void {
    this.selectedCamera = camera;
  }
 
  public setSelectedCameraSettings(cameraSettings?: CameraSettings): void {
    this.selectedCameraSettings = cameraSettings;
  }
 
  public async setupCameras(): Promise<void> {
    Iif (this.cameraInitializationPromise != null) {
      return this.cameraInitializationPromise;
    }
 
    const mediaStreamTrack: void | MediaStreamTrack = await this.accessInitialCamera();
    const cameras: Camera[] = await CameraAccess.getCameras();
 
    if (this.cameraSwitcherEnabled && cameras.length > 1) {
      this.gui.setCameraSwitcherVisible(true);
    }
 
    if (mediaStreamTrack != null) {
      // We successfully accessed a camera, check if it's really the correct (main with wanted type or only) camera
      const wantedCamera: Camera | undefined = CameraAccess.adjustCamerasFromCameraStream(
        mediaStreamTrack,
        cameras,
        this.initialCameraType
      );
      if (wantedCamera != null) {
        this.setSelectedCamera(wantedCamera);
        this.updateActiveCameraCurrentResolution(wantedCamera);
 
        return Promise.resolve();
      }
    }
 
    if (this.selectedCamera == null) {
      return this.accessAutoselectedCamera(cameras);
    } else {
      return this.initializeCameraWithSettings(this.selectedCamera, this.selectedCameraSettings);
    }
  }
 
  public stopStream(): void {
    if (this.activeCamera != null) {
      this.activeCamera.currentResolution = undefined;
    }
 
    this.activeCamera = undefined;
 
    if (this.mediaStream != null) {
      window.clearTimeout(this.cameraAccessTimeout);
      window.clearInterval(this.cameraMetadataCheckInterval);
      window.clearTimeout(this.getCapabilitiesTimeout);
      window.clearTimeout(this.manualFocusWaitTimeout);
      window.clearTimeout(this.manualToAutofocusResumeTimeout);
      window.clearInterval(this.autofocusInterval);
      this.mediaStream.getVideoTracks().forEach((track) => {
        track.stop();
      });
      this.mediaStream = undefined;
      this.mediaTrackCapabilities = undefined;
    }
  }
 
  public applyCameraSettings(cameraSettings?: CameraSettings): Promise<void> {
    this.selectedCameraSettings = cameraSettings;
 
    if (this.activeCamera == null) {
      return Promise.reject(new CustomError(CameraManager.noCameraErrorParameters));
    }
 
    return this.initializeCameraWithSettings(this.activeCamera, cameraSettings);
  }
 
  public reinitializeCamera(): Promise<void> {
    if (this.activeCamera != null) {
      return this.initializeCameraWithSettings(this.activeCamera, this.activeCameraSettings).catch(
        this.triggerFatalError
      );
    }
 
    return Promise.resolve();
  }
 
  public async initializeCameraWithSettings(camera: Camera, cameraSettings?: CameraSettings): Promise<void> {
    await (this.cameraInitializationPromise ?? Promise.resolve());
    this.setSelectedCamera(camera);
    this.selectedCameraSettings = this.activeCameraSettings = cameraSettings;
    let resolutionFallbackLevel: number;
    switch (cameraSettings?.resolutionPreference) {
      case CameraSettings.ResolutionPreference.ULTRA_HD:
        resolutionFallbackLevel = 0;
        break;
      case CameraSettings.ResolutionPreference.FULL_HD:
        resolutionFallbackLevel = 1;
        break;
      case CameraSettings.ResolutionPreference.HD:
      default:
        resolutionFallbackLevel = 2;
        break;
    }
    this.cameraInitializationPromise = this.initializeCameraAndCheckUpdatedSettings(camera, resolutionFallbackLevel);
 
    return this.cameraInitializationPromise;
  }
 
  public async setTorchEnabled(enabled: boolean): Promise<void> {
    if (this.mediaStream != null && this.mediaTrackCapabilities?.torch === true) {
      this.torchEnabled = enabled;
      const videoTracks: MediaStreamTrack[] = this.mediaStream.getVideoTracks();
      // istanbul ignore else
      if (IvideoTracks.length !== 0 && typeof videoTracks[0].applyConstraints === "function") {
        await videoTracks[0].applyConstraints({ advanced: <ExtendedMediaTrackConstraintSet[]>[{ torch: enabled }] });
      }
    }
  }
 
  public async toggleTorch(): Promise<void> {
    this.torchEnabled = !this.torchEnabled;
    await this.setTorchEnabled(this.torchEnabled);
  }
 
  public async setZoom(zoomPercentage: number, currentZoom?: number): Promise<void> {
    if (this.mediaStream != null && this.mediaTrackCapabilities?.zoom != null) {
      const videoTracks: MediaStreamTrack[] = this.mediaStream.getVideoTracks();
      // istanbul ignore else
      if (IvideoTracks.length !== 0 && typeof videoTracks[0].applyConstraints === "function") {
        const zoomRange: number = this.mediaTrackCapabilities.zoom.max - this.mediaTrackCapabilities.zoom.min;
        const targetZoom: number = Math.max(
          this.mediaTrackCapabilities.zoom.min,
          Math.min(
            (currentZoom ?? this.mediaTrackCapabilities.zoom.min) + zoomRange * zoomPercentage,
            this.mediaTrackCapabilities.zoom.max
          )
        );
        await videoTracks[0].applyConstraints({
          advanced: <ExtendedMediaTrackConstraintSet[]>[{ zoom: targetZoom }],
        });
      }
    }
  }
 
  private async accessAutoselectedCamera(cameras: Camera[]): Promise<void> {
    cameras.sort((camera1, camera2) => {
      if (camera1.cameraType !== camera2.cameraType) {
        if (camera1.cameraType === this.initialCameraType) {
          return -1;
        } else Eif (camera2.cameraType === this.initialCameraType) {
          return 1;
        }
      }
 
      return camera1.label.localeCompare(camera2.label);
    });
 
    let autoselectedCamera: Camera | undefined = cameras.shift();
    while (autoselectedCamera != null) {
      try {
        return await this.initializeCameraWithSettings(autoselectedCamera, this.selectedCameraSettings);
      } catch (error) {
        this.setSelectedCamera();
        if (cameras.length === 1) {
          this.gui.setCameraSwitcherVisible(false);
        }
        if (cameras.length >= 1) {
          console.warn("Couldn't access camera", autoselectedCamera, error);
          autoselectedCamera = cameras.shift();
          continue;
        }
        throw error;
      }
    }
    throw new CustomError(CameraManager.noCameraErrorParameters);
  }
 
  private accessInitialCamera(): Promise<void | MediaStreamTrack> {
    let initialCameraAccessPromise: Promise<void | MediaStreamTrack> = Promise.resolve();
 
    if (this.selectedCamera == null) {
      const primaryCamera: Camera = {
        deviceId: "",
        label: "",
        cameraType: this.initialCameraType,
      };
 
      initialCameraAccessPromise = new Promise(async (resolve) => {
        try {
          await this.initializeCameraWithSettings(primaryCamera, this.selectedCameraSettings);
          Eif (this.mediaStream != null) {
            const videoTracks: MediaStreamTrack[] = this.mediaStream.getVideoTracks();
            Eif (videoTracks.length !== 0) {
              return resolve(videoTracks[0]);
            }
          }
        } catch {
          // Ignored
        } finally {
          this.setSelectedCamera();
          resolve();
        }
      });
    }
 
    return initialCameraAccessPromise;
  }
 
  private updateActiveCameraCurrentResolution(camera: Camera): void {
    this.activeCamera = camera;
    this.activeCamera.currentResolution = {
      width: this.gui.videoElement.videoWidth,
      height: this.gui.videoElement.videoHeight,
    };
    this.gui.setMirrorImageEnabled(this.gui.isMirrorImageEnabled(), false);
  }
 
  private postStreamInitialization(): void {
    window.clearTimeout(this.getCapabilitiesTimeout);
    this.getCapabilitiesTimeout = window.setTimeout(() => {
      this.storeStreamCapabilities();
      this.setupAutofocus();
      if (this.torchToggleEnabled && this.mediaStream != null && this.mediaTrackCapabilities?.torch === true) {
        this.gui.setTorchTogglerVisible(true);
      }
    }, CameraManager.getCapabilitiesTimeoutMs);
  }
 
  private videoTrackUnmuteRecovery(): void {
    this.reinitializeCamera().catch(
      /* istanbul ignore next */ () => {
        // Ignored
      }
    );
  }
 
  private async triggerManualFocusForContinuous(): Promise<void> {
    this.manualToAutofocusResumeTimeout = window.setTimeout(async () => {
      await this.triggerFocusMode(MeteringMode.CONTINUOUS);
    }, CameraManager.manualToAutofocusResumeTimeoutMs);
 
    try {
      await this.triggerFocusMode(MeteringMode.CONTINUOUS);
      this.manualFocusWaitTimeout = window.setTimeout(async () => {
        await this.triggerFocusMode(MeteringMode.MANUAL);
      }, CameraManager.manualFocusWaitTimeoutMs);
    } catch {
      // istanbul ignore next
    }
  }
 
  private async triggerManualFocusForSingleShot(): Promise<void> {
    window.clearInterval(this.autofocusInterval);
 
    this.manualToAutofocusResumeTimeout = window.setTimeout(() => {
      this.autofocusInterval = window.setInterval(this.triggerAutoFocus.bind(this), CameraManager.autofocusIntervalMs);
    }, CameraManager.manualToAutofocusResumeTimeoutMs);
 
    try {
      await this.triggerFocusMode(MeteringMode.SINGLE_SHOT);
    } catch {
      // istanbul ignore next
    }
  }
 
  private async triggerManualFocus(event?: MouseEvent | TouchEvent): Promise<void> {
    if (event != null) {
      event.preventDefault();
      if (event.type === "touchend" && (<TouchEvent>event).touches.length !== 0) {
        return;
      }
      // Check if we were using pinch-to-zoom
      if (this.pinchToZoomDistance != null) {
        this.pinchToZoomDistance = undefined;
 
        return;
      }
    }
    window.clearTimeout(this.manualFocusWaitTimeout);
    window.clearTimeout(this.manualToAutofocusResumeTimeout);
    if (this.mediaStream != null && this.mediaTrackCapabilities != null) {
      const focusModeCapability: MeteringMode[] | undefined = this.mediaTrackCapabilities.focusMode;
      if (focusModeCapability instanceof Array && focusModeCapability.includes(MeteringMode.SINGLE_SHOT)) {
        if (
          focusModeCapability.includes(MeteringMode.CONTINUOUS) &&
          focusModeCapability.includes(MeteringMode.MANUAL)
        ) {
          await this.triggerManualFocusForContinuous();
        } else if (!focusModeCapability.includes(MeteringMode.CONTINUOUS)) {
          await this.triggerManualFocusForSingleShot();
        }
      }
    }
  }
 
  private triggerZoomStart(event?: TouchEvent): void {
    if (event?.touches.length !== 2) {
      return;
    }
    event.preventDefault();
    this.pinchToZoomDistance = Math.hypot(
      (event.touches[1].screenX - event.touches[0].screenX) / screen.width,
      (event.touches[1].screenY - event.touches[0].screenY) / screen.height
    );
    if (this.mediaStream != null && this.mediaTrackCapabilities?.zoom != null) {
      const videoTracks: MediaStreamTrack[] = this.mediaStream.getVideoTracks();
      // istanbul ignore else
      if (videoTracks.length !== 0 && typeof videoTracks[0].getConstraints === "function") {
        this.pinchToZoomInitialZoom = this.mediaTrackCapabilities.zoom.min;
        const currentConstraints: MediaTrackConstraints = videoTracks[0].getConstraints();
        if (currentConstraints.advanced != null) {
          const currentZoomConstraint: ExtendedMediaTrackConstraintSet | undefined = currentConstraints.advanced.find(
            (constraint) => {
              return "zoom" in constraint;
            }
          );
          if (currentZoomConstraint?.zoom != null) {
            this.pinchToZoomInitialZoom = currentZoomConstraint.zoom;
          }
        }
      }
    }
  }
 
  private async triggerZoomMove(event?: TouchEvent): Promise<void> {
    if (this.pinchToZoomDistance == null || event?.touches.length !== 2) {
      return;
    }
    event.preventDefault();
    await this.setZoom(
      (Math.hypot(
        (event.touches[1].screenX - event.touches[0].screenX) / screen.width,
        (event.touches[1].screenY - event.touches[0].screenY) / screen.height
      ) -
        this.pinchToZoomDistance) *
        2,
      this.pinchToZoomInitialZoom
    );
  }
 
  private storeStreamCapabilities(): void {
    // istanbul ignore else
    if (this.mediaStream != null) {
      const videoTracks: MediaStreamTrack[] = this.mediaStream.getVideoTracks();
      // istanbul ignore else
      if (videoTracks.length !== 0 && typeof videoTracks[0].getCapabilities === "function") {
        this.mediaTrackCapabilities = videoTracks[0].getCapabilities();
      }
    }
  }
 
  private setupAutofocus(): void {
    window.clearTimeout(this.manualFocusWaitTimeout);
    window.clearTimeout(this.manualToAutofocusResumeTimeout);
    // istanbul ignore else
    if (this.mediaStream != null && this.mediaTrackCapabilities != null) {
      const focusModeCapability: MeteringMode[] | undefined = this.mediaTrackCapabilities.focusMode;
      if (
        focusModeCapability instanceof Array &&
        !focusModeCapability.includes(MeteringMode.CONTINUOUS) &&
        focusModeCapability.includes(MeteringMode.SINGLE_SHOT)
      ) {
        window.clearInterval(this.autofocusInterval);
        this.autofocusInterval = window.setInterval(
          this.triggerAutoFocus.bind(this),
          CameraManager.autofocusIntervalMs
        );
      }
    }
  }
 
  private triggerAutoFocus(): void {
    this.triggerFocusMode(MeteringMode.SINGLE_SHOT).catch(
      /* istanbul ignore next */ () => {
        // Ignored
      }
    );
  }
 
  private triggerFocusMode(focusMode: MeteringMode): Promise<void> {
    // istanbul ignore else
    if (this.mediaStream != null) {
      const videoTracks: MediaStreamTrack[] = this.mediaStream.getVideoTracks();
      if (videoTracks.length !== 0 && typeof videoTracks[0].applyConstraints === "function") {
        return videoTracks[0].applyConstraints({ advanced: <MediaTrackConstraintSet[]>(<unknown>[{ focusMode }]) });
      }
    }
 
    return Promise.reject(undefined);
  }
 
  private enableTapToFocusListeners(): void {
    ["touchend", "mousedown"].forEach((eventName) => {
      this.gui.videoElement.addEventListener(eventName, this.triggerManualFocusListener);
    });
  }
 
  private enablePinchToZoomListeners(): void {
    this.gui.videoElement.addEventListener("touchstart", this.triggerZoomStartListener);
    this.gui.videoElement.addEventListener("touchmove", this.triggerZoomMoveListener);
  }
 
  private disableTapToFocusListeners(): void {
    ["touchend", "mousedown"].forEach((eventName) => {
      this.gui.videoElement.removeEventListener(eventName, this.triggerManualFocusListener);
    });
  }
 
  private disablePinchToZoomListeners(): void {
    this.gui.videoElement.removeEventListener("touchstart", this.triggerZoomStartListener);
    this.gui.videoElement.removeEventListener("touchmove", this.triggerZoomMoveListener);
  }
 
  private async initializeCameraAndCheckUpdatedSettings(
    camera: Camera,
    resolutionFallbackLevel: number
  ): Promise<void> {
    try {
      await this.initializeCamera(camera, resolutionFallbackLevel);
      // Check if due to asynchronous behaviour camera settings were changed while camera was initialized
      Iif (
        this.selectedCameraSettings !== this.activeCameraSettings &&
        (this.selectedCameraSettings == null ||
          this.activeCameraSettings == null ||
          (<(keyof CameraSettings)[]>Object.keys(this.selectedCameraSettings)).some((cameraSettingsProperty) => {
            return (
              (<CameraSettings>this.selectedCameraSettings)[cameraSettingsProperty] !==
              (<CameraSettings>this.activeCameraSettings)[cameraSettingsProperty]
            );
          }))
      ) {
        this.activeCameraSettings = this.selectedCameraSettings;
 
        return this.initializeCameraAndCheckUpdatedSettings(camera, resolutionFallbackLevel);
      }
    } finally {
      this.cameraInitializationPromise = undefined;
    }
  }
 
  private retryInitializeCameraIfNeeded(
    camera: Camera,
    resolutionFallbackLevel: number,
    resolve: (value?: void | PromiseLike<void> | undefined) => void,
    reject: (reason?: Error) => void,
    error: Error
  ): Promise<void> | void {
    if (resolutionFallbackLevel < 4) {
      return this.initializeCamera(camera, resolutionFallbackLevel + 1)
        .then(resolve)
        .catch(reject);
    } else {
      return reject(error);
    }
  }
 
  private async handleCameraInitializationError(
    error: Error,
    resolutionFallbackLevel: number,
    camera: Camera,
    resolve: (value?: void | PromiseLike<void> | undefined) => void,
    reject: (reason?: Error) => void
  ): Promise<void> {
    if (
      Eerror.message === "Invalid constraint" ||
      // tslint:disable-next-line:no-any
      (error.name === "OverconstrainedError" && (<any>error).constraint === "deviceId")
    ) {
      // Camera might have changed deviceId: check for new cameras with same label and type but different deviceId
      const cameras: Camera[] = await CameraAccess.getCameras();
      const newCamera: Camera | undefined = cameras.find((currentCamera) => {
        return (
          currentCamera.label === camera.label &&
          currentCamera.cameraType === camera.cameraType &&
          currentCamera.deviceId !== camera.deviceId
        );
      });
      if (newCamera == null) {
        return this.retryInitializeCameraIfNeeded(camera, resolutionFallbackLevel, resolve, reject, error);
      } else {
        return this.initializeCamera(newCamera, resolutionFallbackLevel).then(resolve).catch(reject);
      }
    }
    if (["AbortError", "NotAllowedError", "NotFoundError", "NotReadableError", "SecurityError"].includes(error.name)) {
      // Camera is not accessible at all
      return reject(error);
    }
 
    return this.retryInitializeCameraIfNeeded(camera, resolutionFallbackLevel, resolve, reject, error);
  }
 
  private initializeCamera(camera: Camera, resolutionFallbackLevel: number): Promise<void> {
    if (camera == null) {
      return Promise.reject(new CustomError(CameraManager.noCameraErrorParameters));
    }
    this.stopStream();
    this.torchEnabled = false;
    this.gui.setTorchTogglerVisible(false);
 
    return new Promise(async (resolve, reject) => {
      try {
        const stream: MediaStream = await CameraAccess.accessCameraStream(resolutionFallbackLevel, camera);
        // Detect weird browser behaviour that on unsupported resolution returns a 2x2 video instead
        Eif (typeof stream.getTracks()[0].getSettings === "function") {
          const mediaTrackSettings: MediaTrackSettings = stream.getTracks()[0].getSettings();
          Iif (
            mediaTrackSettings.width != null &&
            mediaTrackSettings.height != null &&
            (mediaTrackSettings.width === 2 || mediaTrackSettings.height === 2)
          ) {
            if (resolutionFallbackLevel === 4) {
              return reject(
                new CustomError({ name: "NotReadableError", message: "Could not initialize camera correctly" })
              );
            } else {
              return this.initializeCamera(camera, resolutionFallbackLevel + 1)
                .then(resolve)
                .catch(reject);
            }
          }
        }
        this.mediaStream = stream;
        this.mediaStream.getVideoTracks().forEach((track) => {
          // Reinitialize camera on weird pause/resumption coming from the OS
          // This will add the listener only once in the case of multiple calls, identical listeners are ignored
          track.addEventListener("unmute", this.videoTrackUnmuteListener);
        });
        // This will add the listener only once in the case of multiple calls, identical listeners are ignored
        this.gui.videoElement.addEventListener("loadedmetadata", this.postStreamInitializationListener);
        if (this.tapToFocusEnabled) {
          this.enableTapToFocusListeners();
        }
        if (this.pinchToZoomEnabled) {
          this.enablePinchToZoomListeners();
        }
        this.resolveInitializeCamera(camera, resolve, reject);
        this.gui.videoElement.srcObject = stream;
        this.gui.videoElement.load();
        this.gui.playVideo();
      } catch (error) {
        await this.handleCameraInitializationError(error, resolutionFallbackLevel, camera, resolve, reject);
      }
    });
  }
 
  private resolveInitializeCamera(camera: Camera, resolve: () => void, reject: (reason: Error) => void): void {
    const cameraNotReadableError: Error = new CustomError({
      name: "NotReadableError",
      message: "Could not initialize camera correctly",
    });
 
    window.clearTimeout(this.cameraAccessTimeout);
    this.cameraAccessTimeout = window.setTimeout(() => {
      this.stopStream();
      reject(cameraNotReadableError);
    }, CameraManager.cameraAccessTimeoutMs);
 
    this.gui.videoElement.onresize = () => {
      if (this.activeCamera != null) {
        this.updateActiveCameraCurrentResolution(this.activeCamera);
      }
    };
 
    this.gui.videoElement.onloadeddata = () => {
      this.gui.videoElement.onloadeddata = null;
      window.clearTimeout(this.cameraAccessTimeout);
 
      // Detect weird browser behaviour that on unsupported resolution returns a 2x2 video instead
      // Also detect failed camera access with no error but also no video stream provided
      if (
        this.gui.videoElement.videoWidth > 2 &&
        this.gui.videoElement.videoHeight > 2 &&
        this.gui.videoElement.currentTime > 0
      ) {
        if (camera.deviceId !== "") {
          this.updateActiveCameraCurrentResolution(camera);
        }
 
        return resolve();
      }
 
      const cameraMetadataCheckStartTime: number = performance.now();
 
      window.clearInterval(this.cameraMetadataCheckInterval);
      this.cameraMetadataCheckInterval = window.setInterval(() => {
        // Detect weird browser behaviour that on unsupported resolution returns a 2x2 video instead
        // Also detect failed camera access with no error but also no video stream provided
        if (
          this.gui.videoElement.videoWidth === 2 ||
          this.gui.videoElement.videoHeight === 2 ||
          this.gui.videoElement.currentTime === 0
        ) {
          if (performance.now() - cameraMetadataCheckStartTime > CameraManager.cameraMetadataCheckTimeoutMs) {
            window.clearInterval(this.cameraMetadataCheckInterval);
            this.stopStream();
 
            return reject(cameraNotReadableError);
          }
 
          return;
        }
 
        window.clearInterval(this.cameraMetadataCheckInterval);
        if (camera.deviceId !== "") {
          this.updateActiveCameraCurrentResolution(camera);
          this.gui.videoElement.dispatchEvent(new Event("canplay"));
        }
 
        return resolve();
      }, CameraManager.cameraMetadataCheckIntervalMs);
    };
  }
}