All files / src/lib cameraAccess.ts

100% Statements 122/122
97.83% Branches 90/92
100% Functions 37/37
100% Lines 118/118

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 50015x 15x 15x 15x         15x                   15x                                                                                       15x         15x                           53x   53x 1660x                       8x                                                       1x                           30x   19x 42x   19x 23x   19x         11x                                   15x           35x 32x   35x 55x   35x 30x           30x   71x     8x     30x 17x       18x                   39x   98x       94x     90x     84x 65x     19x 19x           19x 14x     19x   39x     38x         2x   2x 4x 4x 2x     2x   2x   3x     1x       2x     39x                                   45x 45x 1x     44x 44x 1x     43x 43x   41x     98x     39x     5x             36x           43x     43x 40x 39x   39x   39x   4x 4x   43x 4x   43x       43x                       32x   32x 32x 32x                             32x     32x   1x           8x           20x           1x           2x                               15x 32x         32x 12x       20x         32x 4x 4x 3x 3x   4x                       83x 44x 39x       31x   8x 8x 8x 1x   7x 7x     22x     18x                         2x           2x            
import { BrowserCompatibility } from "./browserCompatibility";
import { BrowserHelper } from "./browserHelper";
import { Camera } from "./camera";
import { UnsupportedBrowserError } from "./unsupportedBrowserError";
 
/**
 * A helper object to interact with cameras.
 */
export namespace CameraAccess {
  /**
   * @hidden
   *
   * Handle localized camera labels. Supported languages:
   * English, German, French, Spanish (spain), Portuguese (brasil), Portuguese (portugal), Italian,
   * Chinese (simplified), Chinese (traditional), Japanese, Russian, Turkish, Dutch, Arabic, Thai, Swedish,
   * Danish, Vietnamese, Norwegian, Polish, Finnish, Indonesian, Hebrew, Greek, Romanian, Hungarian, Czech,
   * Catalan, Slovak, Ukraininan, Croatian, Malay, Hindi.
   */
  const backCameraKeywords: string[] = [
    "rear",
    "back",
    "rück",
    "arrière",
    "trasera",
    "trás",
    "traseira",
    "posteriore",
    "后面",
    "後面",
    "背面",
    "后置", // alternative
    "後置", // alternative
    "背置", // alternative
    "задней",
    "الخلفية",
    "후",
    "arka",
    "achterzijde",
    "หลัง",
    "baksidan",
    "bagside",
    "sau",
    "bak",
    "tylny",
    "takakamera",
    "belakang",
    "אחורית",
    "πίσω",
    "spate",
    "hátsó",
    "zadní",
    "darrere",
    "zadná",
    "задня",
    "stražnja",
    "belakang",
    "बैक",
  ];
 
  /**
   * @hidden
   */
  const cameraObjects: Map<string, Camera> = new Map<string, Camera>();
 
  /**
   * @hidden
   */
  const inaccessibleCameras: Set<string> = new Set<string>();
 
  /**
   * @hidden
   */
  let getCamerasPromise: Promise<Camera[]> | undefined;
 
  /**
   * @hidden
   *
   * @param label The camera label.
   * @returns Whether the label mentions the camera being a back-facing one.
   */
  function isBackCameraLabel(label: string): boolean {
    const lowercaseLabel: string = label.toLowerCase();
 
    return backCameraKeywords.some((keyword) => {
      return lowercaseLabel.includes(keyword);
    });
  }
 
  /**
   * @hidden
   *
   * Map non-standard error names to standard ones.
   *
   * @param error The error object.
   */
  function mapNonStandardErrorName(error: Error): void {
    let name: string = error.name;
    // istanbul ignore next
    switch (name) {
      case "DeviceCaptureError":
      case "ScreenCaptureError":
      case "TabCaptureError":
        name = "AbortError";
        break;
      case "InvalidStateError":
      case "MediaDeviceFailedDueToShutdown":
      case "MediaDeviceKillSwitchOn":
      case "PermissionDeniedError":
      case "PermissionDismissedError":
        name = "NotAllowedError";
        break;
      case "DevicesNotFoundError":
        name = "NotFoundError";
        break;
      case "SourceUnavailableError":
      case "TrackStartError":
        name = "NotReadableError";
        break;
      case "ConstraintNotSatisfiedError":
        name = "OverconstrainedError";
        break;
      default:
        return;
    }
    Object.defineProperty(error, "name", {
      value: name,
    });
  }
 
  /**
   * @hidden
   *
   * @param cameras The array of available [[Camera]] objects.
   * @param activeCamera The current active [[Camera]] object.
   * @param activeCameraIsBackFacing Whether *activeCamera* is facing back (environment).
   */
  function adjustCameraTypes(cameras: Camera[], activeCamera: Camera, activeCameraIsBackFacing: boolean): void {
    // TODO: improve logic for possible multiple front/back cameras
    if (activeCameraIsBackFacing) {
      // Correct camera types if needed
      cameras.forEach((camera) => {
        if (camera.deviceId === activeCamera.deviceId) {
          // tslint:disable-next-line:no-any
          (<any>camera).cameraType = Camera.Type.BACK;
        } else if (!isBackCameraLabel(camera.label)) {
          // tslint:disable-next-line:no-any
          (<any>camera).cameraType = Camera.Type.FRONT;
        }
      });
    } else {
      // tslint:disable-next-line:no-any
      (<any>activeCamera).cameraType = Camera.Type.FRONT;
    }
  }
 
  /**
   * @hidden
   *
   * Adjusts the cameras' type classification based on the given currently active video stream:
   * If the stream comes from an environment-facing camera, the camera is marked to be a back-facing camera
   * and the other cameras to be of other types accordingly (if they are not correctly set already).
   *
   * The method returns the currently active camera if it's actually the correct (main with wanted type or only) one.
   *
   * @param mediaStreamTrack The currently active `MediaStreamTrack`.
   * @param cameras The array of available [[Camera]] objects.
   * @param wantedCameraType The wanted camera type.
   * @returns The active [[Camera]] object if the stream is actually from the correct camera.
   */
  export function adjustCamerasFromCameraStream(
    mediaStreamTrack: MediaStreamTrack,
    cameras: Camera[],
    wantedCameraType: Camera.Type
  ): Camera | undefined {
    let mediaTrackSettings: MediaTrackSettings | undefined;
    if (typeof mediaStreamTrack.getSettings === "function") {
      mediaTrackSettings = mediaStreamTrack.getSettings();
    }
    const activeCamera: Camera | undefined = cameras.find((camera) => {
      return camera.deviceId === mediaTrackSettings?.deviceId || camera.label === mediaStreamTrack.label;
    });
    if (activeCamera != null) {
      adjustCameraTypes(
        cameras,
        activeCamera,
        mediaTrackSettings?.facingMode === "environment" || isBackCameraLabel(mediaStreamTrack.label)
      );
 
      const mainCameraForType: Camera | undefined = cameras
        .filter((camera) => {
          return camera.cameraType === wantedCameraType;
        })
        .sort((camera1, camera2) => {
          return camera1.label.localeCompare(camera2.label);
        })[0];
 
      if (cameras.length === 1 || activeCamera.deviceId === mainCameraForType?.deviceId) {
        return activeCamera;
      }
    }
 
    return undefined;
  }
 
  /**
   * @hidden
   *
   * @param devices The list of available devices.
   * @returns The extracted list of accessible camera objects initialized from the given devices.
   */
  function extractAccessibleCamerasFromDevices(devices: MediaDeviceInfo[]): Camera[] {
    const cameras: Camera[] = devices
      .filter((device) => {
        return device.kind === "videoinput";
      })
      .filter((videoDevice) => {
        // Ignore infrared cameras as they often fail to be accessed and are not useful in any case
        return !/\b(?:ir|infrared)\b/i.test(videoDevice.label);
      })
      .filter((videoDevice) => {
        return !inaccessibleCameras.has(videoDevice.deviceId);
      })
      .map((videoDevice) => {
        if (cameraObjects.has(videoDevice.deviceId)) {
          return <Camera>cameraObjects.get(videoDevice.deviceId);
        }
 
        const label: string = videoDevice.label ?? "";
        const camera: Camera = {
          deviceId: videoDevice.deviceId,
          label,
          cameraType: isBackCameraLabel(label) ? Camera.Type.BACK : Camera.Type.FRONT,
        };
 
        if (label !== "") {
          cameraObjects.set(videoDevice.deviceId, camera);
        }
 
        return camera;
      });
    if (
      cameras.length > 1 &&
      !cameras.some((camera) => {
        return camera.cameraType === Camera.Type.BACK;
      })
    ) {
      // Check if cameras are labeled with resolution information, take the higher-resolution one in that case
      // Otherwise pick the last camera
      let backCameraIndex: number = cameras.length - 1;
 
      const cameraResolutions: number[] = cameras.map((camera) => {
        const match: RegExpMatchArray | null = camera.label.match(/\b([0-9]+)MP?\b/i);
        if (match != null) {
          return parseInt(match[1], 10);
        }
 
        return NaN;
      });
      if (
        !cameraResolutions.some((cameraResolution) => {
          return isNaN(cameraResolution);
        })
      ) {
        backCameraIndex = cameraResolutions.lastIndexOf(Math.max(...cameraResolutions));
      }
 
      // tslint:disable-next-line:no-any
      (<any>cameras[backCameraIndex]).cameraType = Camera.Type.BACK;
    }
 
    return cameras;
  }
 
  /**
   * Get a list of cameras (if any) available on the device, a camera access permission is requested to the user
   * the first time this method is called if needed.
   *
   * Depending on device features and user permissions for camera access, any of the following errors
   * could be the rejected result of the returned promise:
   * - `AbortError`
   * - `NotAllowedError`
   * - `NotFoundError`
   * - `NotReadableError`
   * - `SecurityError`
   * - `UnsupportedBrowserError`
   *
   * @returns A promise resolving to the array of available [[Camera]] objects (could be empty).
   */
  export function getCameras(): Promise<Camera[]> {
    if (getCamerasPromise != null) {
      return getCamerasPromise;
    }
 
    const browserCompatibility: BrowserCompatibility = BrowserHelper.checkBrowserCompatibility();
    if (!browserCompatibility.fullSupport) {
      return Promise.reject(new UnsupportedBrowserError(browserCompatibility));
    }
 
    const accessPermissionPromise: Promise<null | MediaStream> = new Promise((resolve, reject) => {
      return enumerateDevices()
        .then((devices) => {
          if (
            devices
              .filter((device) => {
                return device.kind === "videoinput";
              })
              .every((device) => {
                return device.label === "";
              })
          ) {
            resolve(
              navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false,
              })
            );
          } else {
            resolve(null);
          }
        })
        .catch(reject);
    });
 
    getCamerasPromise = new Promise(async (resolve, reject) => {
      let stream!: MediaStream | null;
      try {
        stream = await accessPermissionPromise;
        const devices: MediaDeviceInfo[] = await enumerateDevices();
        const cameras: Camera[] = extractAccessibleCamerasFromDevices(devices);
 
        console.debug("Camera list: ", ...cameras);
 
        return resolve(cameras);
      } catch (error) {
        mapNonStandardErrorName(error);
        reject(error);
      } finally {
        stream?.getVideoTracks().forEach((track) => {
          track.stop();
        });
        getCamerasPromise = undefined;
      }
    });
 
    return getCamerasPromise;
  }
 
  /**
   * @hidden
   *
   * Call `navigator.mediaDevices.getUserMedia` asynchronously in a `setTimeout` call.
   *
   * @param getUserMediaParams The parameters for the `navigator.mediaDevices.getUserMedia` call.
   * @returns A promise resolving when the camera is accessed.
   */
  function getUserMediaDelayed(getUserMediaParams: MediaStreamConstraints): Promise<MediaStream> {
    console.debug("Camera access:", getUserMediaParams.video);
 
    return new Promise((resolve, reject) => {
      window.setTimeout(() => {
        navigator.mediaDevices.getUserMedia(getUserMediaParams).then(resolve).catch(reject);
      }, 0);
    });
  }
 
  /**
   * @hidden
   *
   * Get the *getUserMedia* *video* parameters to be used given a resolution fallback level and the browser used.
   *
   * @param resolutionFallbackLevel The number representing the wanted resolution, from 0 to 4,
   * resulting in higher to lower video resolutions.
   * @returns The resulting *getUserMedia* *video* parameters.
   */
  function getUserMediaVideoParams(resolutionFallbackLevel: number): MediaTrackConstraints {
    const userMediaVideoParams: MediaTrackConstraints = {
      resizeMode: "none",
    };
    switch (resolutionFallbackLevel) {
      case 0:
        return {
          ...userMediaVideoParams,
          width: { min: 3200, ideal: 3840, max: 4096 },
          height: { min: 1800, ideal: 2160, max: 2400 },
        };
      case 1:
        return {
          ...userMediaVideoParams,
          width: { min: 1400, ideal: 1920, max: 2160 },
          height: { min: 900, ideal: 1080, max: 1440 },
        };
      case 2:
        return {
          ...userMediaVideoParams,
          width: { min: 960, ideal: 1280, max: 1440 },
          height: { min: 480, ideal: 720, max: 960 },
        };
      case 3:
        return {
          ...userMediaVideoParams,
          width: { min: 640, ideal: 640, max: 800 },
          height: { min: 480, ideal: 480, max: 600 },
        };
      default:
        return {};
    }
  }
 
  /**
   * @hidden
   *
   * Try to access a given camera for video input at the given resolution level.
   *
   * If a camera is inaccessible because of unknown issues, then it's added to the device blacklist.
   *
   * @param resolutionFallbackLevel The number representing the wanted resolution, from 0 to 4,
   * resulting in higher to lower video resolutions.
   * @param camera The camera to try to access for video input.
   * @returns A promise resolving to the `MediaStream` object coming from the accessed camera.
   */
  export function accessCameraStream(resolutionFallbackLevel: number, camera: Camera): Promise<MediaStream> {
    const getUserMediaParams: MediaStreamConstraints = {
      audio: false,
      video: getUserMediaVideoParams(resolutionFallbackLevel),
    };
 
    if (camera.deviceId === "") {
      (<MediaTrackConstraints>getUserMediaParams.video).facingMode = {
        ideal: camera.cameraType === Camera.Type.BACK ? "environment" : "user",
      };
    } else {
      (<MediaTrackConstraints>getUserMediaParams.video).deviceId = {
        exact: camera.deviceId,
      };
    }
 
    return getUserMediaDelayed(getUserMediaParams).catch((error) => {
      mapNonStandardErrorName(error);
      if (camera.deviceId !== "" && (error.name !== "OverconstrainedError" || resolutionFallbackLevel === 4)) {
        inaccessibleCameras.add(camera.deviceId);
        cameraObjects.delete(camera.deviceId);
      }
      throw error;
    });
  }
 
  /**
   * @hidden
   *
   * Get a list of available devices in a cross-browser compatible way.
   *
   * @returns A promise resolving to the `MediaDeviceInfo` array of all available devices.
   */
  function enumerateDevices(): Promise<MediaDeviceInfo[]> {
    if (typeof navigator.enumerateDevices === "function") {
      return navigator.enumerateDevices();
    } else if (
      typeof navigator.mediaDevices === "object" &&
      typeof navigator.mediaDevices.enumerateDevices === "function"
    ) {
      return navigator.mediaDevices.enumerateDevices();
    } else {
      return new Promise((resolve, reject) => {
        try {
          if (window.MediaStreamTrack?.getSources == null) {
            throw new Error();
          }
          window.MediaStreamTrack.getSources((devices) => {
            resolve(
              devices
                .filter((device) => {
                  return device.kind.toLowerCase() === "video" || device.kind.toLowerCase() === "videoinput";
                })
                .map((device) => {
                  return {
                    deviceId: device.deviceId ?? "",
                    groupId: device.groupId,
                    kind: <MediaDeviceKind>"videoinput",
                    label: device.label,
                    toJSON: /* istanbul ignore next */ function (): MediaDeviceInfo {
                      return this;
                    },
                  };
                })
            );
          });
        } catch {
          const browserCompatibility: BrowserCompatibility = {
            fullSupport: false,
            scannerSupport: true,
            missingFeatures: [BrowserCompatibility.Feature.MEDIA_DEVICES],
          };
 
          return reject(new UnsupportedBrowserError(browserCompatibility));
        }
      });
    }
  }
}