All files / app-play/src recording-controller.ts

79.83% Statements 95/119
64.7% Branches 22/34
85.71% Functions 6/7
81.57% Lines 93/114

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                          4x   4x   4x                                                                                       2x 2x       2x 2x 2x             2x       2x 2x 2x 2x 2x     2x   2x 2x 2x 2x                 2x           2x 2x       2x 1x 1x 1x 1x 1x 1x 1x 1x   2x 2x                   2x 2x       2x 2x   2x       2x 2x 2x 2x 2x 2x 2x 2x     2x 2x                         4x 4x 4x       3x 3x 3x 2x 2x 2x   1x 1x 1x   3x   1x 1x 1x 1x 1x 1x       1x                 1x 1x 1x 1x   1x         4x 4x 4x                           2x 1x                   6x 3x 3x 3x 3x 3x 6x 6x 6x 6x 6x 6x   1x 1x 1x      
import type { PixiSceneHost } from '@be-music/player-browser/host';
import { Rectangle, logger } from '@be-music/player-browser';
import {
  downloadBlob,
  makeWebMSeekable,
  recordingFileExtension,
  type RecordingFormat,
  type RecordingQuality,
} from '@be-music/player-browser/recording';
import type { OptionButton } from './ui/options-controls.ts';
import { setDisabled, setButtonTitle } from './pane-controls.ts';
 
/** The Options dialog button that records the play screen (gameplay) as a video. */
export const RECORD_LABEL = '● Record gameplay video';
/** The same button while a recording runs. */
export const STOP_RECORDING_LABEL = '■ Stop recording';
 
const recordLog = logger('record');
 
/**
 * Common recording-API surface both gameplay paths (a built-in or LR2 play scene's `recording` and beatoraja's
 * `PixiBeatorajaGameplayView`) expose. Narrowed type so {@link activeGameplayRecorder} can return a path-agnostic value the rest of the controller
 * acts on without branching by family.
 */
export interface GameplayRecorder {
  startRecording(options?: { format?: RecordingFormat; quality?: RecordingQuality }): void;
  stopRecording(): Promise<{ blob: Blob; mimeType: string; durationMs: number; seekable: boolean } | undefined>;
  isRecording(): boolean;
}
 
/**
 * Dependencies the recording controller's free functions read from / write to. Modelled as explicit getters /
 * setters / callbacks (rather than `this` references) so the player class can pass them in without having to drop its
 * private modifier on every backing field. Each call site builds one of these from the player's recording service — see
 * `RecordingService.deps` in `services/recording.ts`.
 */
export interface RecordingDeps {
  readonly sceneHost: PixiSceneHost;
  readonly recordController: OptionButton | undefined;
  /** Whichever gameplay view is mounted right now, or `undefined` when neither family is active. */
  getActiveGameplay(): GameplayRecorder | undefined;
  getAutoRecordArmed(): boolean;
  setAutoRecordArmed(value: boolean): void;
  /** Snapshot of the recording filename stem at call time; the player updates it per chart in `playChart`. */
  getRecordingFilenameBase(): string;
  /** The Options dialog's "Video format": the container and codec a new recording is written in. */
  getRecordingFormat(): RecordingFormat;
  /** The Options dialog's "Video quality": the bitrates a new recording is made at. */
  getRecordingQuality(): RecordingQuality;
  /** Disables the Video format and Video quality controls while a recording runs: they apply when one starts. */
  setRecordingSettingsLocked?(locked: boolean): void;
  setStatus(text: string): void;
}
 
/**
 * Captures the currently-mounted scene as a PNG and triggers a browser download. Mirrors `extract.canvas`'s rect
 * contract carefully because Pixi's internal `frame.copyTo(...)` call expects a real `Rectangle` instance — a plain
 * object literal silently falls back to `getLocalBounds`, which on a transform-reset container yields a zero rect
 * and produces a blank image.
 */
export async function captureScreenshot(deps: RecordingDeps): Promise<void> {
  const app = deps.sceneHost.app;
  Iif (app.renderer === undefined) {
    deps.setStatus('Screenshot failed: renderer not ready');
    return;
  }
  try {
    const activeScene = deps.sceneHost.getCurrentScene();
    const stageInfo = activeScene?.getStageInfo?.();
    // `extract.canvas` returns Pixi's `ICanvas` (HTMLCanvasElement | OffscreenCanvas
    // union). Player doesn't depend directly on `pixi.js` so we type it via the runtime
    // duck-type `{ toBlob }` we actually consume below.
    let canvas: { toBlob?: (cb: (blob: Blob | null) => void, type?: string) => void };
    let captureWidth: number;
    let captureHeight: number;
    if (stageInfo !== undefined) {
      // Native skin-size path. Reset the container's fitToStage transform around the
      // extract call; the next tick's fitToStage no-ops on cached screen dims and the
      // user never sees the broken state on the live canvas.
      const { container, width, height } = stageInfo;
      const savedScaleX = container.scale.x;
      const savedScaleY = container.scale.y;
      const savedX = container.x;
      const savedY = container.y;
      // Remove viewport magnification while preserving the skin's output pixel aspect (classic LR2 coordinates
      // may be stretched to widescreen). Resetting both axes to 1 would squeeze exported screenshots back to 4:3.
      const pixelAspect = savedScaleX / savedScaleY;
      const outputWidth =
        Number.isFinite(pixelAspect) && pixelAspect > 0 ? Math.max(1, Math.round(width * pixelAspect)) : width;
      container.scale.set(1, 1);
      container.position.set(0, 0);
      try {
        // Frame MUST be an actual `Rectangle` instance — Pixi's `extract.canvas`
        // internally calls `options.frame.copyTo(tempRect)` (see
        // `GenerateTextureSystem.js`'s `generateTexture`). A plain `{x, y, width,
        // height}` literal returns `undefined` from the optional chain there and the
        // code falls through to `getLocalBounds(container)`, which on a transform-reset
        // container yields a zero / negative rect → blank canvas, blob fails to encode,
        // download silently fails. Rectangle is re-exported from `@be-music/player-browser`
        // so this package doesn't need a direct `pixi.js` dep.
        canvas = app.renderer.extract.canvas({
          target: container,
          frame: new Rectangle(0, 0, width, height),
          resolution: 1,
        }) as typeof canvas;
      } finally {
        container.scale.set(savedScaleX, savedScaleY);
        container.position.set(savedX, savedY);
      }
      // Pixi extraction ignores the target's root transform. Stretch the extracted source canvas instead of
      // enlarging its frame, which would leave the extra columns transparent.
      if (outputWidth !== width) {
        const output = document.createElement('canvas');
        output.width = outputWidth;
        output.height = height;
        const context = output.getContext('2d');
        Iif (context === null) throw new Error('2D canvas unavailable');
        context.imageSmoothingEnabled = false;
        context.drawImage(canvas as unknown as CanvasImageSource, 0, 0, outputWidth, height);
        canvas = output;
      }
      captureWidth = outputWidth;
      captureHeight = height;
    } else E{
      // Fallback: capture the entire stage at the visible window size. Used when the
      // scene isn't a beatoraja `PixiScene` (= LR2 path today). Same toBlob pipeline.
      canvas = app.renderer.extract.canvas(app.stage) as typeof canvas;
      captureWidth = app.screen.width;
      captureHeight = app.screen.height;
    }
    // Both HTMLCanvasElement and OffscreenCanvas expose `toBlob` in modern browsers.
    // Narrow defensively in case a runtime returns something exotic.
    const toBlob = canvas.toBlob;
    Iif (typeof toBlob !== 'function') {
      deps.setStatus('Screenshot failed: canvas.toBlob unavailable');
      return;
    }
    const blob = await new Promise<Blob | null>((resolve) => {
      toBlob.call(canvas, (b) => resolve(b), 'image/png');
    });
    Iif (blob === null) {
      deps.setStatus('Screenshot failed: encoder returned null');
      return;
    }
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').replace(/Z$/, '');
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `bms-screenshot-${timestamp}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    // Revoke after a short delay — some browsers race the download against immediate
    // revocation. 5s is enough for the download dialog to grab the URL.
    setTimeout(() => URL.revokeObjectURL(url), 5_000);
    deps.setStatus(`Screenshot saved (${captureWidth}×${captureHeight})`);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    deps.setStatus(`Screenshot failed: ${message}`);
  }
}
 
/**
 * Toggles the recording state of the active gameplay view, or arms / disarms the "record on next song" auto-flag
 * when no gameplay view is mounted yet (= user pressed Record from song-select). Updates the GUI controller's
 * label / class to reflect the current state.
 */
export async function toggleRecording(deps: RecordingDeps): Promise<void> {
  const gameplay = deps.getActiveGameplay();
  const controller = deps.recordController;
  if (!gameplay) {
    // No chart is playing yet — interpret the click as "arm capture for the next song I pick" so the user can stage
    // recording from the song-select screen without having to hit Record at the precise moment gameplay starts. A
    // second click before picking a song disarms.
    const next = !deps.getAutoRecordArmed();
    deps.setAutoRecordArmed(next);
    if (next) {
      controller?.element.classList.add('arming');
      setButtonTitle(controller, '◉ Records the next play');
      deps.setStatus('Recording armed — pick a song to start capturing');
    } else {
      controller?.element.classList.remove('arming');
      setButtonTitle(controller, RECORD_LABEL);
      deps.setStatus('Recording disarmed');
    }
    return;
  }
  Eif (gameplay.isRecording()) {
    setDisabled(controller, true);
    deps.setStatus('Finalizing recording…');
    try {
      const result = await gameplay.stopRecording();
      Eif (result) {
        // A WebM from the `MediaRecorder` fallback has no seek index — post-process it to inject `Duration` + `Cues` so
        // external players can seek inside it. Falls back to the raw blob if the patch fails, so a take is never
        // silently lost. The WebCodecs backend, and MP4 from either, carry the index already.
        const seekable = result.seekable ? result.blob : await makeWebMSeekable(result.blob);
        // Named after what was written: the browser may have fallen back to another container.
        const filename = `${deps.getRecordingFilenameBase()}.${recordingFileExtension(result.mimeType)}`;
        downloadBlob(seekable, filename);
        const seconds = (result.durationMs / 1000).toFixed(1);
        const sizeMb = (seekable.size / (1024 * 1024)).toFixed(1);
        deps.setStatus(`Saved ${filename} (${seconds}s, ${sizeMb} MB)`);
      }
    } finally {
      controller?.element.classList.remove('recording');
      setButtonTitle(controller, RECORD_LABEL);
      setDisabled(controller, false);
      deps.setRecordingSettingsLocked?.(false);
    }
    return;
  }
  try {
    gameplay.startRecording({ format: deps.getRecordingFormat(), quality: deps.getRecordingQuality() });
    deps.setRecordingSettingsLocked?.(true);
    controller?.element.classList.add('recording');
    setButtonTitle(controller, STOP_RECORDING_LABEL);
    deps.setStatus('Recording…');
  } catch (error) {
    recordLog.warn('start failed', error);
    deps.setStatus(`Recording unavailable: ${(error as Error).message}`);
  }
}
 
/**
 * Stop the in-flight recording (if any) before a gameplay-view dispose. Sequencing matters: `MediaRecorder.stop()`
 * waits for a `'stop'` event from its source stream — disposing the gameplay view first kills the AudioContext that
 * feeds it, so the recorder never sees the event and the save never finalizes. Caller-side: invoke this BEFORE
 * disposing the gameplay view, whichever family it belongs to.
 */
export async function finalizeRecordingIfActive(deps: RecordingDeps): Promise<void> {
  if (deps.getActiveGameplay()?.isRecording() === true) {
    await toggleRecording(deps);
  }
}
 
/**
 * Starts the recording armed from song select (the Record button pressed with no play up) on the gameplay view that just
 * mounted, whichever family it belongs to. Call it once the view's AudioContext exists. A failure is not fatal: the
 * play goes on and the status says why nothing is recorded.
 */
export function startArmedRecording(deps: RecordingDeps): void {
  if (!deps.getAutoRecordArmed()) return;
  const gameplay = deps.getActiveGameplay();
  Iif (gameplay === undefined) return;
  deps.setAutoRecordArmed(false);
  const controller = deps.recordController;
  controller?.element.classList.remove('arming');
  try {
    gameplay.startRecording({ format: deps.getRecordingFormat(), quality: deps.getRecordingQuality() });
    deps.setRecordingSettingsLocked?.(true);
    controller?.element.classList.add('recording');
    setButtonTitle(controller, STOP_RECORDING_LABEL);
    deps.setStatus('Recording…');
  } catch (error) {
    setButtonTitle(controller, RECORD_LABEL);
    recordLog.warn('auto-start failed', error);
    deps.setStatus(`Recording unavailable: ${(error as Error).message}`);
  }
}