All files / app-play/src/services bga-camera.ts

75.1% Statements 175/233
69.32% Branches 113/163
79.54% Functions 35/44
80.82% Lines 156/193

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                                                                                                                15x           15x   15x   15x 15x   15x     15x 15x 15x                         9x         3x               4x         2x               4x 4x 4x 4x 4x         1x 1x 1x 1x         2x                     4x 4x 4x 4x 4x 4x                       4x               1x 1x 1x       1x 1x 1x           1x 1x 1x       1x 1x           4x 2x         2x 1x 1x   2x                                           1x 1x               13x 13x 2x 2x 2x   11x 11x 10x         13x 13x 1x 12x 12x 1x 1x   11x   11x 11x       1x 1x 1x 1x 1x   10x       10x   10x 10x 10x 1x     10x 10x   10x 10x 10x           5x 5x 5x 5x 5x 5x   5x   5x         5x 5x 5x 5x 2x 2x 2x   5x 5x   5x 5x       1x 1x   4x       4x 4x 4x 1x 1x 1x     4x   4x       12x 12x 12x 12x         2x       2x 2x       2x 2x 2x 2x 1x 1x   1x 2x                     1x 1x 1x         21x 21x 21x 40x               21x       5x 5x       4x 4x 4x       4x 3x 4x       29x 29x 29x       65x       19x             6x     6x 3x 1x 1x         3x 3x    
// The BGA camera: opens the camera the Options dialog picked while a play is on the stage and hands it to the play scene
// (`PlayScene.setBGACamera`), which shows it in the BGA frame in place of the chart's BGA. The camera opens only when
// the setting is on and a play is showing, and closes on every other screen. A camera that is unplugged or whose
// permission is taken back closes, and the play shows the chart's BGA again.
//
// The picture goes nowhere but the play's canvas. A Capture recording of the canvas includes it with the BGA frame.
 
import type { BGACamera } from '@be-music/player-browser/host';
import {
  BGA_CAMERA_STORAGE_KEY,
  cameraConstraints,
  cameraDevices,
  cameraNamesKnown,
  isPickedCameraMissing,
  parseStoredBGACameraSettings,
  pickCamera,
  serializeBGACameraSettings,
  type BGACameraSettings,
  type CameraDevice,
} from '../bga-camera-settings.ts';
import { playerText } from '../player-copy.ts';
import { defaultSettingStorage, type SettingStorage } from './settings.ts';
 
/**
 * Where the camera stands:
 * - `off`: the setting is off.
 * - `standby`: on, waiting for a play.
 * - `starting`: opening the camera.
 * - `live`: showing in the play's BGA frame.
 * - `denied`: the browser or the player refused the camera.
 * - `missing`: the picked camera, or any camera, is not connected.
 * - `busy`: another app holds the camera, or it failed to start.
 * - `unsupported`: the browser has no camera access here (no `getUserMedia`, or not a secure page).
 */
export type BGACameraStatus = 'off' | 'standby' | 'starting' | 'live' | 'denied' | 'missing' | 'busy' | 'unsupported';
 
/** What the service asks of the play scene. */
export interface BGACameraTarget {
  setBGACamera(camera: BGACamera | undefined): void;
}
 
export interface BGACameraServiceDeps {
  /** `navigator.mediaDevices`, or `undefined` where the page has none (not a secure context). */
  readonly mediaDevices?: Pick<MediaDevices, 'getUserMedia' | 'enumerateDevices' | 'addEventListener'> | undefined;
  /** `navigator.permissions`, to hear when the camera permission is taken back. */
  readonly permissions?: Pick<Permissions, 'query'> | undefined;
  readonly storage?: SettingStorage | undefined;
  /** Shows a status line: the camera was lost, or could not open. */
  setStatus?(text: string): void;
}
 
/** A camera's `MediaDeviceInfo`, as far as the service reads it. */
export type BGACameraDevice = CameraDevice;
 
export class BGACameraService {
  private settingsValue: BGACameraSettings;
  private camerasValue: BGACameraDevice[] = [];
  private statusValue: BGACameraStatus;
  private target: BGACameraTarget | undefined;
  private stream: MediaStream | undefined;
  /** The camera the Options dialog's preview opened while no play shows it. */
  private previewOwnStream: MediaStream | undefined;
  private previewWanted = false;
  private previewProblemValue: BGACameraStatus | undefined;
  private previewGeneration = 0;
  /** Moves on every open and close, so an open that settles after a newer one is dropped. */
  private generation = 0;
  private readonly listeners = new Set<() => void>();
  private readonly deps: BGACameraServiceDeps;
  private watching = false;
 
  public constructor(deps: BGACameraServiceDeps) {
    this.deps = deps;
    this.settingsValue = parseStoredBGACameraSettings(this.storage()?.getItem(BGA_CAMERA_STORAGE_KEY));
    this.statusValue = deps.mediaDevices === undefined ? 'unsupported' : this.settingsValue.enabled ? 'standby' : 'off';
  }
 
  public get settings(): BGACameraSettings {
    return this.settingsValue;
  }
 
  /** The connected cameras, named once the player has allowed the camera. */
  public get cameras(): readonly BGACameraDevice[] {
    return this.camerasValue;
  }
 
  public get status(): BGACameraStatus {
    return this.statusValue;
  }
 
  /** Whether the Options dialog's preview is on. */
  public get previewing(): boolean {
    return this.previewWanted;
  }
 
  /**
   * What the preview shows: the camera the play shows, or one opened for the preview alone. `undefined` while the
   * preview is off or the camera is opening.
   */
  public get previewStream(): MediaStream | undefined {
    return this.previewWanted ? (this.stream ?? this.previewOwnStream) : undefined;
  }
 
  /** Why the preview could not open (`denied`, `missing`, `busy`, `unsupported`), until it is tried again. */
  public get previewProblem(): BGACameraStatus | undefined {
    return this.previewProblemValue;
  }
 
  /**
   * Shows the picked camera in the Options dialog, mirrored as the play would show it, whether the setting is on or not.
   * It opens the camera unless a play already shows it, and the dialog stops it as the preview leaves the screen.
   */
  public async startPreview(): Promise<void> {
    Iif (this.previewWanted) return;
    this.previewWanted = true;
    this.previewProblemValue = undefined;
    this.emit();
    await this.openPreview();
  }
 
  /** Stops the preview, and closes the camera unless a play shows it. */
  public stopPreview(): void {
    Iif (!this.previewWanted) return;
    this.previewWanted = false;
    this.closePreview();
    this.emit();
  }
 
  /** Whether the browser has told the page the cameras' names (the player allowed the camera once). */
  public get namesKnown(): boolean {
    return cameraNamesKnown(this.camerasValue);
  }
 
  /** Runs `listener` whenever the settings, the cameras or the status change. Returns the unsubscribe. */
  public subscribe(listener: () => void): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }
 
  /** Lists the cameras, and from then on follows plugging and permission changes. */
  public async watch(): Promise<void> {
    const media = this.deps.mediaDevices;
    Iif (media === undefined) return;
    Eif (!this.watching) {
      this.watching = true;
      media.addEventListener('devicechange', () => void this.onDeviceChange());
      void this.deps.permissions
        ?.query({ name: 'camera' as PermissionName })
        .then((permission) => {
          permission.addEventListener('change', () => {
            if (permission.state === 'denied') this.lose('denied');
            void this.refreshCameras();
          });
        })
        .catch(() => {
          // Firefox has no `camera` permission query; a revoked permission still ends the camera's track.
        });
    }
    await this.refreshCameras();
  }
 
  /**
   * Asks the browser for the camera once, so it names the cameras, then closes it again (unless a play is showing it).
   * Resolves `false` when the player or the browser refused.
   */
  public async requestAccess(): Promise<boolean> {
    const media = this.deps.mediaDevices;
    Iif (media === undefined) return false;
    Iif (this.stream !== undefined || this.previewOwnStream !== undefined) {
      await this.refreshCameras();
      return true;
    }
    try {
      const stream = await media.getUserMedia(cameraConstraints(this.settingsValue, undefined));
      for (const track of stream.getTracks()) track.stop();
    } catch (error) {
      this.setStatusValue(statusOfError(error));
      await this.refreshCameras();
      return false;
    }
    await this.refreshCameras();
    Iif (this.statusValue === 'denied') this.setStatusValue(this.idleStatus());
    return true;
  }
 
  public setEnabled(enabled: boolean): void {
    this.save({ ...this.settingsValue, enabled });
    if (enabled) void this.open();
    else Ethis.close('off');
  }
 
  /** Picks the camera by `deviceId` (`''` for the browser's default) and opens it in place of the one showing. */
  public setDevice(deviceId: string): void {
    const camera = this.camerasValue.find((device) => device.deviceId === deviceId);
    this.save({
      ...this.settingsValue,
      deviceId,
      label: deviceId === '' ? '' : (camera?.label ?? this.settingsValue.label),
    });
    if (this.stream !== undefined || this.statusValue === 'missing' || this.statusValue === 'busy') {
      this.close(this.idleStatus());
      void this.open();
    }
    Iif (this.previewWanted && this.stream === undefined) {
      this.closePreview();
      this.previewProblemValue = undefined;
      void this.openPreview();
    }
  }
 
  /** Sets the picture's resolution and aspect ratio, and opens the camera again with them where it is open. */
  public setFormat(format: Partial<Pick<BGACameraSettings, 'resolution' | 'aspect'>>): void {
    this.save({ ...this.settingsValue, ...format });
    if (this.stream !== undefined) {
      this.close(this.idleStatus());
      void this.open();
    }
    if (this.previewWanted && this.stream === undefined) {
      this.closePreview();
      this.previewProblemValue = undefined;
      void this.openPreview();
    }
  }
 
  public setMirror(mirror: boolean): void {
    this.save({ ...this.settingsValue, mirror });
    Eif (this.stream !== undefined) this.target?.setBGACamera({ stream: this.stream, mirror });
  }
 
  /**
   * The play on the stage, or `undefined` when another screen shows: the camera opens for a play when the setting is on
   * and closes as the play leaves. A play that follows a play (a retry) takes the camera over without reopening it.
   */
  public follow(target: BGACameraTarget | undefined): void {
    Iif (target === this.target) return;
    if (target === undefined) {
      this.close(this.idleStatus());
      this.target = undefined;
      return;
    }
    this.target = target;
    if (this.stream !== undefined) target.setBGACamera({ stream: this.stream, mirror: this.settingsValue.mirror });
    else void this.open();
  }
 
  /** Opens the picked camera for the play showing, when the setting is on. */
  private async open(): Promise<void> {
    const media = this.deps.mediaDevices;
    if (media === undefined || !this.settingsValue.enabled || this.target === undefined || this.stream !== undefined)
      return;
    const generation = ++this.generation;
    if (isPickedCameraMissing(this.camerasValue, this.settingsValue)) {
      this.setStatusValue('missing');
      return;
    }
    this.setStatusValue('starting');
    let stream: MediaStream;
    try {
      stream = await media.getUserMedia(
        cameraConstraints(this.settingsValue, pickCamera(this.camerasValue, this.settingsValue)),
      );
    } catch (error) {
      Iif (generation !== this.generation) return;
      const status = statusOfError(error);
      this.setStatusValue(status);
      this.deps.setStatus?.(lostMessage(status));
      return;
    }
    Iif (generation !== this.generation || this.target === undefined || !this.settingsValue.enabled) {
      for (const track of stream.getTracks()) track.stop();
      return;
    }
    this.stream = stream;
    // The preview now shows the play's camera.
    this.closePreview();
    for (const track of stream.getVideoTracks()) {
      track.addEventListener('ended', () => {
        Eif (this.stream === stream) this.lose('missing');
      });
    }
    this.target.setBGACamera({ stream, mirror: this.settingsValue.mirror });
    this.setStatusValue('live');
    // The cameras have names now; a picked camera found by its name gets its new id.
    await this.refreshCameras();
    const picked = pickCamera(this.camerasValue, this.settingsValue);
    Iif (picked !== undefined && picked.deviceId !== this.settingsValue.deviceId && this.settingsValue.deviceId !== '')
      this.save({ ...this.settingsValue, deviceId: picked.deviceId });
  }
 
  /** Closes the camera and shows the chart's BGA again; `status` is where the camera stands after. */
  private close(status: BGACameraStatus): void {
    this.generation += 1;
    const stream = this.stream;
    this.stream = undefined;
    Eif (stream !== undefined) {
      this.target?.setBGACamera(undefined);
      for (const track of stream.getTracks()) track.stop();
    }
    this.setStatusValue(status);
    // A preview that showed the play's camera opens one of its own.
    if (stream !== undefined && this.previewWanted) void this.openPreview();
  }
 
  /** Opens the picked camera for the preview, unless a play shows it already. */
  private async openPreview(): Promise<void> {
    const media = this.deps.mediaDevices;
    Iif (!this.previewWanted || this.stream !== undefined || this.previewOwnStream !== undefined) return;
    const generation = ++this.previewGeneration;
    const fail = (problem: BGACameraStatus): void => {
      this.previewWanted = false;
      this.previewProblemValue = problem;
      this.emit();
    };
    Iif (media === undefined) return fail('unsupported');
    Iif (isPickedCameraMissing(this.camerasValue, this.settingsValue)) return fail('missing');
    let stream: MediaStream;
    try {
      stream = await media.getUserMedia(
        cameraConstraints(this.settingsValue, pickCamera(this.camerasValue, this.settingsValue)),
      );
    } catch (error) {
      Eif (generation === this.previewGeneration) fail(statusOfError(error));
      return;
    }
    Iif (generation !== this.previewGeneration || !this.previewWanted || this.stream !== undefined) {
      for (const track of stream.getTracks()) track.stop();
      return;
    }
    this.previewOwnStream = stream;
    for (const track of stream.getVideoTracks()) {
      track.addEventListener('ended', () => {
        Iif (this.previewOwnStream !== stream) return;
        this.closePreview();
        fail('missing');
      });
    }
    this.emit();
    // The cameras have names now.
    await this.refreshCameras();
  }
 
  private closePreview(): void {
    this.previewGeneration += 1;
    const stream = this.previewOwnStream;
    this.previewOwnStream = undefined;
    if (stream !== undefined) for (const track of stream.getTracks()) track.stop();
  }
 
  /** The camera went away during a play: close it, show the BGA, and say so. */
  private lose(status: BGACameraStatus): void {
    Iif (this.stream === undefined) {
      if (this.settingsValue.enabled) this.setStatusValue(status);
      return;
    }
    this.close(status);
    this.deps.setStatus?.(lostMessage(status));
  }
 
  private async onDeviceChange(): Promise<void> {
    await this.refreshCameras();
    const track = this.stream?.getVideoTracks()[0];
    const deviceId = track?.getSettings().deviceId;
    if (track !== undefined && deviceId !== undefined && this.namesKnown) {
      Eif (!this.camerasValue.some((camera) => camera.deviceId === deviceId)) this.lose('missing');
      return;
    }
    const previewId = this.previewOwnStream?.getVideoTracks()[0]?.getSettings().deviceId;
    Iif (
      previewId !== undefined &&
      this.namesKnown &&
      !this.camerasValue.some((camera) => camera.deviceId === previewId)
    ) {
      this.closePreview();
      this.previewWanted = false;
      this.previewProblemValue = 'missing';
      this.emit();
    }
    // A camera plugged in while a play waits for it.
    Eif (this.stream === undefined && (this.statusValue === 'missing' || this.statusValue === 'busy')) {
      this.setStatusValue(this.idleStatus());
      void this.open();
    }
  }
 
  private async refreshCameras(): Promise<void> {
    const media = this.deps.mediaDevices;
    Iif (media === undefined) return;
    try {
      this.camerasValue = cameraDevices(await media.enumerateDevices()).map(({ deviceId, kind, label }) => ({
        deviceId,
        kind,
        label,
      }));
    } catch {
      this.camerasValue = [];
    }
    this.emit();
  }
 
  private idleStatus(): BGACameraStatus {
    Iif (this.deps.mediaDevices === undefined) return 'unsupported';
    return this.settingsValue.enabled ? 'standby' : 'off';
  }
 
  private save(settings: BGACameraSettings): void {
    this.settingsValue = settings;
    try {
      this.storage()?.setItem(BGA_CAMERA_STORAGE_KEY, serializeBGACameraSettings(settings));
    } catch {
      // Storage blocked — the settings last for this visit.
    }
    if (!settings.enabled && this.stream === undefined) this.statusValue = this.idleStatus();
    else if (settings.enabled && this.statusValue === 'off') this.statusValue = 'standby';
    this.emit();
  }
 
  private setStatusValue(status: BGACameraStatus): void {
    Iif (this.statusValue === status) return;
    this.statusValue = status;
    this.emit();
  }
 
  private emit(): void {
    for (const listener of this.listeners) listener();
  }
 
  private storage(): SettingStorage | undefined {
    return this.deps.storage ?? defaultSettingStorage();
  }
}
 
/** Where the camera stands after `getUserMedia` threw `error`. */
export function statusOfError(error: unknown): BGACameraStatus {
  const name =
    error instanceof Error || (typeof error === 'object' && error !== null && 'name' in error)
      ? String((error as { name: unknown }).name)
      : '';
  if (name === 'NotAllowedError' || name === 'SecurityError') return 'denied';
  if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'missing';
  Iif (name === 'TypeError') return 'unsupported';
  return 'busy';
}
 
/** The status line for a camera that closed or did not open. */
function lostMessage(status: BGACameraStatus): string {
  const lost = playerText().camera.lost;
  return status === 'denied' || status === 'missing' || status === 'unsupported' ? lost[status] : lost.busy;
}