All files / player-browser/src/view/shared bga-renderer.ts

61.19% Statements 194/317
68.4% Branches 223/326
70.83% Functions 17/24
62.84% Lines 181/288

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                                                                                                                  31x     86x 86x       86x 86x   86x 86x           86x 86x       86x       86x 6x 6x     80x 80x 80x               80x 80x           86x             86x 105x     86x 86x 20x         80x             5x   80x 80x 86x 86x 69x       69x 297x     189x 297x 297x               69x 90x 90x 90x 90x 27x 27x 38x 33x 27x           69x 4x           69x 49x 7x 7x 7x   7x   69x 192x     80x 80x   14x                                 18x                       12x 12x         2x                                       12x 12x     68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x                 297x 175x 175x 175x         175x                                 297x                         175x 175x 175x 175x 175x 175x 175x 175x                           175x 175x 175x   525x       68x 92x       4x                 4x   88x                     92x                 92x                 92x 25x                   68x 4x   68x                                                                                                                   80x 80x 80x 80x                                 31x               5x 5x 2x 2x 2x                 193x 193x       31x                       18x 18x 18x 18x 18x     18x 18x               14x   4x 4x 4x 2x 2x 2x 2x   4x 4x 4x 4x       4x                                   31x                       45x 44x 43x                                                   192x     192x 192x 192x 192x 192x 192x   118x             118x   74x 192x     39x       39x 38x 6x 4x       6x   32x         32x 26x 26x       26x   35x 3x 3x 3x     35x 192x 192x 192x 192x           35x 25x         31x             18x                   18x                         18x 18x                                                  
import { resolveChartOptionsAt } from '@be-music/chart-model';
import { keyBoundBGAResourceKey } from '../../chart/key-bound-bga.ts';
import { canDrawBGAPixelsOnGPU, drawBGAPixelsOnGPU } from '../../media/bga-gpu-pixels.ts';
import { isColorKeyVideoCanvas } from '../../media/color-key-video.ts';
import type { BGAFeed } from '../../media/bga-camera.ts';
import { fitBGACameraRect } from '../../media/bga-camera-fit.ts';
/**
 * The chart's BGA on the built-in and LR2 play screens: composites the base, layer and POOR
 * images (or a stitched NONSTOP chart's per-stage stacks) into the skin's BGA rects, or hands them to a Be-Music Skin
 * that composites the BGA itself, and keeps the BGA videos playing in step with their cues.
 *
 * The functions read and write the scene's state through {@link BGARendererContext}; the play view passes itself.
 */
 
import { DEFAULT_POOR_BGA_DISPLAY_SECONDS } from '@be-music/player-engine/display';
import { Texture, type Sprite } from 'pixi.js';
import {
  buildSkinBGAFrame,
  pickActiveBGACue,
  isMissLayerShown,
  resolveBGAImageRect,
  resolveBGAStacks as resolveBGAStacksOf,
  type BGACue,
  type BGAStack,
} from '../../chart/bga-timeline.ts';
import type { PlaySessionOptions } from '../../session/play/play-options.ts';
import type { ChildPool } from '../../stage/pixi-utils.ts';
import type { BeMusicGameplayBinding } from '../../skin/be-music/binding.ts';
import type { BeMusicImage } from '../../skin/be-music/types.ts';
import type { PlayfieldBGATarget, PlayfieldSkin } from '../types.ts';
import type { PlayfieldRuntime } from './playfield/context.ts';
 
/** The view's members the BGA passes use: a play view's members of these names. */
export interface BGARendererContext {
  readonly play: PlayfieldRuntime;
  readonly options: Readonly<Pick<PlaySessionOptions, 'bga' | 'autoPlay' | 'nonstop' | 'replay'>>;
  readonly playfieldSkin: PlayfieldSkin;
  readonly bgaLayerPool: ChildPool;
  readonly bgaTargetsScratch: PlayfieldBGATarget[];
  readonly skinBinding: BeMusicGameplayBinding | undefined;
  readonly skinBGACrops: Map<Texture, ImageBitmap | null>;
}
 
/**
 * Composites the chart's BGA into the skin's BGA rectangles (`PlayfieldSkin.bgaTargets`; the default-family BGA
 * rectangle unless a skin supplies its own). The tracks stack from back to front: base (channel 04 / bmson `bga.events`), layer
 * (channel 07 / bmson `layerEvents`), second overlay (channel 0A), and a POOR override (channel 06 / `poorEvents`) that briefly replaces the
 * base while the player is inside the POOR-judgement window (`DEFAULT_POOR_BGA_DISPLAY_SECONDS`).
 *
 * The renderer is idempotent per frame — it tears down any existing sprites and rebuilds from the active cues, so cue
 * switches show up the next frame without explicit dirty tracking.
 */
/**
 * `cueSeconds` picks which BGA cue is active; `seconds` is the true clock that plays the cue (movie offsets, SWBGA
 * frames). They differ only past an LR2 negative-BPM reversal, where the event pump stops firing new BGA cues but a
 * movie that is already playing keeps running.
 */
const maskedBGASprites = new WeakMap<ChildPool, Sprite[]>();
 
export function renderBGA(ctx: BGARendererContext, seconds: number, cueSeconds: number = seconds): void {
  let masked = maskedBGASprites.get(ctx.bgaLayerPool);
  Iif (masked) {
    for (const sprite of masked) sprite.mask = null;
    masked.length = 0;
  }
  ctx.bgaLayerPool.begin();
  ctx.bgaTargetsScratch.length = 0;
  // The camera, else an LRX chart's composited BGA (plugout's transforms and layers 203 / 204).
  const camera = ctx.play.bgaCamera ?? (ctx.options.bga !== 'OFF' ? ctx.play.lrxBGA : undefined);
  Iif (camera !== undefined) {
    renderCameraBGA(ctx, camera);
    return;
  }
  // Honor the LR2 panel-1 BGA toggle (`#SRC_BUTTON,type=72`). - `'OFF'` → never render - `'AUTOPLAY_ONLY'` → render
  // only when autoplay is on - `'ON'` (default) → render whenever the chart has BGA
  const bgaMode = ctx.options.bga ?? 'ON';
  Iif (bgaMode === 'OFF') {
    ctx.bgaLayerPool.end();
    return;
  }
  Iif (bgaMode === 'AUTOPLAY_ONLY' && !ctx.options.autoPlay) {
    ctx.bgaLayerPool.end();
    return;
  }
  if (!ctx.play.hasBGA) {
    ctx.bgaLayerPool.end();
    return;
  }
  // Render into EVERY rectangle the skin reports this frame (a DP LR2 skin can show several at once).
  const visibleBGAs = ctx.bgaTargetsScratch;
  ctx.playfieldSkin.bgaTargets(visibleBGAs);
  Iif (visibleBGAs.length === 0) {
    ctx.bgaLayerPool.end();
    return;
  }
  // Drive video BGA playback once per frame (not per-rect) — base / layer cues are global to the chart, every rect
  // shows the same source video. Picking the first visible entry's `noBase` / `noLayer` flags as the controlling ones
  // is fine in practice: the LR2 default skin uses identical flags on every rect, and a future skin that mixes them
  // per-rect would still get a consistent global playback state from this single sync point.
  const controllingBGA = visibleBGAs[0]!;
  const inPoorWindow =
    (ctx.options.nonstop !== undefined || ctx.play.poorBGAMode !== 2) &&
    !controllingBGA.noPoor &&
    (ctx.play.engineFrame?.bmsonBGA?.plane === 'poor' ||
      isMissLayerShown(ctx.play.lastPoorAt / 1000, ctx.play.playClock() / 1000, DEFAULT_POOR_BGA_DISPLAY_SECONDS));
  // A stitched NONSTOP chart shows one BGA stack per stage, crossfading at the seams; any other chart one stack.
  const stacks = resolveBGAStacks(
    ctx,
    cueSeconds,
    controllingBGA.noBase === true,
    controllingBGA.noLayer === true,
    inPoorWindow,
  );
  const leading = stacks.reduce<(typeof stacks)[number] | undefined>(
    (best, stack) => (best === undefined || stack.alpha >= best.alpha ? stack : best),
    undefined,
  );
  let poorKey = ctx.play.nonstopBGATimelines !== undefined ? leading?.poorKey : undefined;
  if (inPoorWindow && ctx.play.nonstopBGATimelines === undefined) {
    poorKey = leading?.poorKey;
  }
  // BMP00 fallback: when no explicit POOR cue is active but the chart has a `#BMP00` (and no `#POORBGA 2`),
  // paint BMP00 during the miss window. Capped at the first authored POOR cue's chart-time so a chart that does
  // eventually author POOR isn't permanently stuck on the placeholder.
  if (
    inPoorWindow &&
    poorKey === undefined &&
    ctx.play.engineFrame?.bmsonBGA?.plane !== 'poor' &&
    ctx.play.poorBGAFallbackKey !== undefined &&
    cueSeconds < ctx.play.poorBGAFallbackUntilSeconds
  ) {
    poorKey = ctx.play.poorBGAFallbackKey;
  }
  if (ctx.play.nonstopBGATimelines === undefined && stacks[0] !== undefined) stacks[0].poorKey = poorKey;
  const keyBound = ctx.play.engineFrame?.keyBoundBGA;
  const keyBoundKey = keyBound ? keyBoundBGAResourceKey(keyBound.definitionId, keyBound.bmpKey) : undefined;
  if (ctx.play.audioContextStartTime !== 0) {
    const requests = new Map<
      string,
      { track: 'base' | 'layer' | 'layer2' | 'poor'; cue: BGACue; playbackRate?: number }
    >();
    const add = (track: 'base' | 'layer' | 'layer2' | 'poor', cue: BGACue | undefined) => {
      if (cue?.bmpKey === undefined) return;
      // Stitched stages own disjoint BMP namespaces. The cue key keeps a stage's slot stable while its
      // crossfade weight passes the leading stage or earlier stacks disappear from the visible list.
      const slot = ctx.play.nonstopBGATimelines === undefined ? track : `${track}:${cue.bmpKey}`;
      const frame = ctx.play.engineFrame?.bmsonBGA;
      requests.set(slot, {
        track,
        cue,
        ...(frame?.key === cue.bmpKey && (frame.plane === 'poor' ? track === 'poor' : track === 'layer')
          ? { playbackRate: frame.playbackRate }
          : {}),
      });
    };
    for (const stack of stacks) {
      add('base', stack.baseCue);
      add('layer', stack.layerCue);
      add('layer2', stack.layer2Cue);
      if (stack.poorKey !== undefined) {
        const timelines = ctx.play.nonstopBGATimelines ?? [ctx.play.bgaTimeline];
        const poorCue = timelines
          .map((timeline) => pickActiveBGACue(timeline.poor, cueSeconds))
          .find((cue) => cue?.bmpKey === stack.poorKey);
        add('poor', {
          bmpKey: stack.poorKey,
          seconds: stack.poorCue?.seconds ?? poorCue?.seconds ?? resolvePoorFallbackStart(ctx, seconds),
        });
      }
    }
    if (keyBound && keyBoundKey && !controllingBGA.noLayer)
      requests.set('key-bound', {
        track: 'layer2',
        cue: { bmpKey: keyBoundKey, seconds: keyBound.frameStartSeconds },
        playbackRate: keyBound.playbackRate,
      });
    // Retire departed cues before starting their replacements, including aliases that share a video handle.
    for (const [slot, previous] of Object.entries(ctx.play.bgaActiveVideos)) {
      if (requests.has(slot)) continue;
      Eif (previous) {
        const video = ctx.play.bgaVideos.get(previous.key)?.video;
        Eif (video && !video.paused) video.pause();
      }
      delete ctx.play.bgaActiveVideos[slot];
    }
    for (const [slot, { track, cue, playbackRate }] of requests)
      syncBGAVideo(ctx, track, cue, seconds, slot, playbackRate);
  }
 
  const binding = ctx.skinBinding;
  if (binding?.drawsBGA) {
    // The skin composites the BGA itself: hand it the images and leave the BGA layer empty.
    const skinFrame = (stack: BGAStack) => ({
      ...(stack.bgaMode !== undefined ? { bgaMode: stack.bgaMode } : {}),
      ...buildSkinBGAFrame(
        {
          base: stack.baseCue?.bmpKey !== undefined ? resolveBGAFrameKey(ctx, stack.baseCue.bmpKey) : undefined,
          layer:
            stack.layerCue?.bmpKey !== undefined ? resolveBGAFrameKey(ctx, stack.layerCue.bmpKey, 'layer') : undefined,
          layer2:
            stack.layer2Cue?.bmpKey !== undefined
              ? resolveBGAFrameKey(ctx, stack.layer2Cue.bmpKey, 'layer2')
              : undefined,
          poor: stack.poorKey !== undefined ? resolveBGAFrameKey(ctx, stack.poorKey, 'poor') : undefined,
          poorOverlays: stack.poorOverlays,
          opacity: stack.opacity,
          tint: stack.tint,
        },
        (key, track, tint) =>
          tintSkinBGAImage(
            resolveSkinBGAImage(
              ctx,
              (track === 'layer' ? ctx.play.bgaLayerTextures : ctx.play.bgaTextures).get(key),
              ctx.play.bgaSubRegionOrigins?.has(key),
              stack.bgaMode !== undefined,
            ),
            tint,
          ),
        ctx.play.bgaSubRegionOrigins,
      ),
    });
    const frame = leading !== undefined ? skinFrame(leading) : { poorActive: false };
    binding.setBGA({
      ...frame,
      ...(ctx.play.nonstopBGATimelines !== undefined || (keyBoundKey !== undefined && !controllingBGA.noLayer)
        ? {
            stacks: [
              ...stacks.map((stack) => ({ ...skinFrame(stack), alpha: stack.alpha })),
              ...(keyBoundKey !== undefined && !controllingBGA.noLayer
                ? [
                    {
                      layer: resolveSkinBGAImage(
                        ctx,
                        ctx.play.bgaLayerTextures.get(keyBoundKey),
                        ctx.play.bgaSubRegionOrigins.has(keyBoundKey),
                      ),
                      origins: { layer: ctx.play.bgaSubRegionOrigins.get(keyBoundKey) ?? { x: 0, y: 0 } },
                      bgaMode: leading?.bgaMode,
                      poorActive: false,
                      alpha: 1,
                    },
                  ]
                : []),
            ],
          }
        : {}),
    });
    ctx.bgaLayerPool.end();
    return;
  }
 
  for (const bga of visibleBGAs) {
    Iif (bga.w <= 0 || bga.h <= 0) continue;
    const backdrop = ctx.bgaLayerPool.acquireSprite();
    backdrop.texture = Texture.WHITE;
    backdrop.label = 'bga/background';
    backdrop.position.set(bga.x, bga.y);
    backdrop.width = bga.w;
    backdrop.height = bga.h;
    bga.applyToSprite(backdrop);
    backdrop.tint = 0x000000;
    const drawLayer = (
      key: string | undefined,
      textures: ReadonlyMap<string, Texture>,
      layerName: 'base' | 'layer' | 'layer2' | 'poor',
      alpha = 1,
      overlay = false,
      tint = 0xffffff,
      placementMode?: 0 | 1 | 2,
    ): void => {
      if (!key) return;
      const resolvedKey = resolveBGAFrameKey(ctx, key, layerName);
      const texture = textures.get(resolvedKey);
      Iif (!texture) return;
      // The rect stands for the 256x256 BMS canvas: an image that fits it keeps its pixel size there, centered
      // horizontally and top-aligned (a 256x161 frame leaves a band at the bottom), while a larger image or a
      // video fills the rect, as LR2 and beatoraja do.
      const placed =
        placementMode !== undefined
          ? resolveBGAImageRect(texture.frame.width, texture.frame.height, bga, undefined, placementMode)
          : ctx.play.bgaVideos.has(resolvedKey) && !ctx.play.bgaSubRegionOrigins.has(resolvedKey)
            ? bga.preserveVideoAspect
              ? (() => {
                  const scale = Math.min(bga.w / texture.width, bga.h / texture.height);
                  const w = texture.width * scale;
                  const h = texture.height * scale;
                  return { x: bga.x + (bga.w - w) / 2, y: bga.y + (bga.h - h) / 2, w, h };
                })()
              : bga
            : resolveBGAImageRect(
                texture.frame.width,
                texture.frame.height,
                bga,
                ctx.play.bgaSubRegionOrigins.get(resolvedKey),
              );
      Iif (layerName !== 'layer' && layerName !== 'layer2' && !overlay && (placed.w < bga.w || placed.h < bga.h)) {
        // The base canvas around a small image is black (a 1x1 black BMP blanks the BGA in LR2 and beatoraja), so
        // fill the rect before drawing the image; the layer track's canvas stays transparent.
        const backdrop = ctx.bgaLayerPool.acquireSprite();
        backdrop.texture = Texture.WHITE;
        backdrop.label = `bga/${layerName}/canvas`;
        backdrop.position.set(bga.x, bga.y);
        backdrop.width = bga.w;
        backdrop.height = bga.h;
        bga.applyToSprite(backdrop);
        backdrop.tint = 0x000000;
        backdrop.alpha *= alpha;
      }
      const sprite = ctx.bgaLayerPool.acquireSprite();
      sprite.texture = texture;
      sprite.label = `bga/${layerName}[key=${resolvedKey}]`;
      sprite.position.set(placed.x, placed.y);
      sprite.width = placed.w;
      sprite.height = placed.h;
      bga.applyToSprite(sprite);
      Iif (
        placementMode !== undefined &&
        (placed.x < bga.x || placed.x + placed.w > bga.x + bga.w || placed.y + placed.h > bga.y + bga.h)
      ) {
        const mask = ctx.bgaLayerPool.acquireGraphics().rect(0, 0, bga.w, bga.h).fill(0xffffff);
        mask.position.set(bga.x, bga.y);
        mask.rotation = backdrop.rotation;
        sprite.mask = mask;
        if (!masked) {
          masked = [];
          maskedBGASprites.set(ctx.bgaLayerPool, masked);
        }
        masked.push(sprite);
      }
      sprite.alpha *= alpha;
      const skinTint = sprite.tint;
      sprite.tint = [16, 8, 0].reduce(
        (value, shift) =>
          value | (Math.round((((skinTint >>> shift) & 255) * ((tint >>> shift) & 255)) / 255) << shift),
        0,
      );
    };
    for (const stack of stacks) {
      if (stack.poorKey && !stack.poorOverlays) {
        // POOR uses base-mode decoding (no chroma key) since it replaces the stack's base+layer composite during its
        // window. Conditional bmson frames supply their exact source-frame origin; ordinary POOR keeps its
        // existing static fallback when it has no explicit frame clock.
        drawLayer(
          stack.poorKey,
          ctx.play.bgaTextures,
          'poor',
          stack.alpha * (stack.opacity?.poor ?? 1),
          false,
          stack.tint?.poor,
          stack.bgaMode,
        );
        continue;
      }
      drawLayer(
        stack.baseCue?.bmpKey,
        ctx.play.bgaTextures,
        'base',
        stack.alpha * (stack.opacity?.base ?? 1),
        false,
        stack.tint?.base,
        stack.bgaMode,
      );
      // Layer track is composited on top with black→transparent so the base track shows through where the
      // foreground BMP is empty.
      drawLayer(
        stack.layerCue?.bmpKey,
        ctx.play.bgaLayerTextures,
        'layer',
        stack.alpha * (stack.opacity?.layer ?? 1),
        false,
        stack.tint?.layer,
        stack.bgaMode,
      );
      drawLayer(
        stack.layer2Cue?.bmpKey,
        ctx.play.bgaLayerTextures,
        'layer2',
        stack.alpha * (stack.opacity?.layer2 ?? 1),
        false,
        stack.tint?.layer2,
        stack.bgaMode,
      );
      if (stack.poorKey && stack.poorOverlays)
        drawLayer(
          stack.poorKey,
          ctx.play.bgaTextures,
          'poor',
          stack.alpha * (stack.opacity?.poor ?? 1),
          true,
          stack.tint?.poor,
          stack.bgaMode,
        );
    }
    if (keyBoundKey && !bga.noLayer)
      drawLayer(keyBoundKey, ctx.play.bgaLayerTextures, 'layer2', 1, true, undefined, leading?.bgaMode);
  }
  ctx.bgaLayerPool.end();
}
 
/**
 * Draws the camera in every BGA rect the skin reports, in place of the chart's BGA: fitted whole on a black canvas
 * (`fitBGACameraRect`). It shows whatever the BGA setting and whether the chart has a BGA, since the player turned it
 * on. The chart's videos pause; when the camera goes, the next frame starts the active cues' videos again at chart time.
 */
function renderCameraBGA(ctx: BGARendererContext, camera: BGAFeed): void {
  for (const [slot, active] of Object.entries(ctx.play.bgaActiveVideos)) {
    const video = active === undefined ? undefined : ctx.play.bgaVideos.get(active.key)?.video;
    if (video !== undefined && !video.paused) video.pause();
    delete ctx.play.bgaActiveVideos[slot];
  }
  const binding = ctx.skinBinding;
  if (binding?.drawsBGA) {
    const image = camera.image();
    binding.setBGA(image !== undefined ? { base: image, poorActive: false } : { poorActive: false });
    ctx.bgaLayerPool.end();
    return;
  }
  const targets = ctx.bgaTargetsScratch;
  ctx.playfieldSkin.bgaTargets(targets);
  const texture = camera.texture();
  for (const bga of targets) {
    if (bga.w <= 0 || bga.h <= 0) continue;
    const backdrop = ctx.bgaLayerPool.acquireSprite();
    backdrop.texture = Texture.WHITE;
    backdrop.label = 'bga/background';
    backdrop.position.set(bga.x, bga.y);
    backdrop.width = bga.w;
    backdrop.height = bga.h;
    bga.applyToSprite(backdrop);
    backdrop.tint = 0x000000;
    if (texture === undefined) continue;
    const placed = fitBGACameraRect(texture.width, texture.height, bga);
    const sprite = ctx.bgaLayerPool.acquireSprite();
    sprite.texture = texture;
    sprite.label = 'bga/camera';
    sprite.position.set(placed.x, placed.y);
    sprite.width = placed.w;
    sprite.height = placed.h;
    bga.applyToSprite(sprite);
  }
  ctx.bgaLayerPool.end();
}
 
/**
 * The BGA stacks to draw at `cueSeconds` ({@link resolveBGAStacksOf}). The chart's own POOR cue (with its `#BMP00`
 * fallback) is resolved by the caller, so a chart that is not stitched passes no POOR cues.
 */
function resolveBGAStacks(
  ctx: BGARendererContext,
  cueSeconds: number,
  noBase: boolean,
  noLayer: boolean,
  inPoorWindow: boolean,
): BGAStack[] {
  const stages = ctx.options.nonstop?.stages;
  const timelines = ctx.play.nonstopBGATimelines;
  const program = ctx.options.replay ? ctx.options.replay.chart.chartOptions : ctx.options.nonstop?.chartOptions;
  return resolveBGAStacksOf({
    bgaMode: ctx.play.engineFrame?.chartOptions?.bgaMode,
    stageBGAMode:
      program && ((windowStart) => resolveChartOptionsAt(program, Math.round(windowStart * 1_000_000)).bgaMode),
    timeline: ctx.play.bgaTimeline,
    poorBGAMode: ctx.play.poorBGAMode,
    nonstop: stages !== undefined && timelines !== undefined ? { stages, timelines } : undefined,
    seconds: cueSeconds,
    noBase,
    noLayer,
    inPoorWindow,
    noPoor: ctx.bgaTargetsScratch[0]?.noPoor === true,
    bmsonBGA: ctx.play.engineFrame?.bmsonBGA,
  });
}
 
/** Chart-second start of each play's miss window, fixed when the window opens. */
const poorFallbackStarts = new WeakMap<object, { lastPoorAt: number; seconds: number }>();
 
/**
 * Where a POOR image with no authored cue started on the chart clock. The miss time is on the wall clock, so convert it
 * once per miss: recomputing every frame drifts with the audio clock and tempo, and the video sync would treat each
 * frame as a new cue and seek again.
 */
function resolvePoorFallbackStart(ctx: BGARendererContext, seconds: number): number {
  const cached = poorFallbackStarts.get(ctx.play);
  if (cached?.lastPoorAt === ctx.play.lastPoorAt) return cached.seconds;
  const start = seconds - Math.max(0, (ctx.play.playClock() - ctx.play.lastPoorAt) / 1000);
  poorFallbackStarts.set(ctx.play, { lastPoorAt: ctx.play.lastPoorAt, seconds: start });
  return start;
}
 
/** The texture key for the BGA slot `key` on `track`: its per-track video instance when one exists, else `key`. */
function resolveBGAFrameKey(
  ctx: BGARendererContext,
  key: string,
  track: 'base' | 'layer' | 'layer2' | 'poor' = 'base',
): string {
  const videoKey = String.fromCharCode(0) + track + ':' + key;
  return ctx.play.bgaVideos?.has(videoKey) ? videoKey : key;
}
 
/** Video crops remain live canvases; their Texture keys disappear with the play session. */
const videoCrops = new WeakMap<Texture, HTMLCanvasElement>();
 
/**
 * The image behind a loaded BGA texture, for `frame.bga`: the decoded bitmap or the `<video>` element itself, or a
 * cropped copy for a `#BGAxx` sub-region (made on first use, so `undefined` for a frame or two).
 */
function resolveSkinBGAImage(
  ctx: BGARendererContext,
  texture: Texture | undefined,
  subRegion = false,
  authoredPlacement = false,
): BeMusicImage | undefined {
  Iif (!texture) return undefined;
  const source = texture.source;
  const resource = source.resource as BeMusicImage | undefined;
  Iif (!resource) return undefined;
  const { frame } = texture;
  // A keyed video is a canvas rather than a <video>; present a full-source movie at the BMS canvas size
  // so Canvas skins retain the same fill behavior as Pixi. Aliases keep their native crop dimensions.
  const fullKeyedVideo = !authoredPlacement && !subRegion && isColorKeyVideoCanvas(resource);
  if (
    !fullKeyedVideo &&
    !subRegion &&
    frame.x === 0 &&
    frame.y === 0 &&
    frame.width === source.width &&
    frame.height === source.height
  ) {
    return resource;
  }
  Eif ('videoWidth' in resource || isColorKeyVideoCanvas(resource)) {
    let canvas = videoCrops.get(texture);
    if (!canvas) {
      canvas = document.createElement('canvas');
      canvas.width = fullKeyedVideo ? 256 : frame.width;
      canvas.height = fullKeyedVideo ? 256 : frame.height;
      videoCrops.set(texture, canvas);
    }
    const context = canvas.getContext('2d')!;
    try {
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.drawImage(resource, frame.x, frame.y, frame.width, frame.height, 0, 0, canvas.width, canvas.height);
    } catch {
      // A seeking/not-yet-buffered video gets another opportunity next frame.
    }
    return canvas;
  }
  const crop = ctx.skinBGACrops.get(texture);
  if (crop !== undefined) return crop ?? undefined;
  ctx.skinBGACrops.set(texture, null);
  createImageBitmap(resource, frame.x, frame.y, frame.width, frame.height).then(
    (bitmap) => {
      if (ctx.play.disposed || !ctx.skinBGACrops.has(texture)) bitmap.close();
      else ctx.skinBGACrops.set(texture, bitmap);
    },
    () => {
      // Leave the `null` marker: the crop isn't retried, the sub-region just doesn't show.
    },
  );
  return undefined;
}
 
/** How far (seconds) a BGA video may drift from the chart's time since its cue before it is set back in step. */
export const BGA_VIDEO_DRIFT_SECONDS = 0.25;
 
/**
 * Where a BGA video playing its cue should be set to keep in step with the chart: `expectedSeconds` (the chart time
 * since the cue, which the video runs at the play tempo) when it has drifted more than {@link BGA_VIDEO_DRIFT_SECONDS}
 * from it — a seek, a stall, a throttled tab — and the video has not played out; `undefined` while it is in step.
 */
export function resolveBGAVideoResync(
  currentSeconds: number,
  expectedSeconds: number,
  durationSeconds: number,
): number | undefined {
  if (!Number.isFinite(expectedSeconds) || expectedSeconds < 0) return undefined;
  if (Number.isFinite(durationSeconds) && expectedSeconds >= durationSeconds) return undefined;
  return Math.abs(currentSeconds - expectedSeconds) > BGA_VIDEO_DRIFT_SECONDS ? expectedSeconds : undefined;
}
 
/**
 * Drives playback of a video BGA on one of the four planes. When the cue's key matches a known video: -
 * first time it fires, `play()` from the cue's start offset - re-firing the same cue is a no-op (video keeps playing)
 * - switching keys pauses the previous video, then plays the new
 *
 * Static (non-video) cues just clear the active-video record so the next video transition starts fresh. The seek
 * offset uses `seconds - cue.seconds` directly because BMS BGA semantics are "start playing this video from t=0 the
 * moment the cue fires".
 */
function syncBGAVideo(
  ctx: BGARendererContext,
  track: 'base' | 'layer' | 'layer2' | 'poor',
  cue: BGACue | undefined,
  seconds: number,
  slot: string = track,
  playbackRate = 1,
): void {
  // Hold off on every video state mutation until the chart-start gate has fired and `audioContextStartTime` is
  // anchored to the audio clock. Without this guard `renderBGA` (which runs every tick from the moment `start()`
  // reveals the scene) picks up the t=0 BGA cue while we're still in the LR2 LOADING phase and `play()`s the video —
  // the user sees the BGA running behind the LOADING / DONE chrome. By short-circuiting we also avoid populating
  // `bgaActiveVideos[slot]`, so when PLAY START fires the next sync call still sees `previous = undefined` and
  // re-enters the "first cue" branch with the correct seek offset.
  Iif (ctx.play.audioContextStartTime === 0) {
    return;
  }
  const previous = ctx.play.bgaActiveVideos[slot];
  const cueKey = cue?.bmpKey;
  const independentKey = String.fromCharCode(0) + track + ':' + cueKey;
  const key = ctx.play.bgaVideos?.has(independentKey) ? independentKey : cueKey;
  const handle = key ? ctx.play.bgaVideos.get(key) : undefined;
  if (!handle) {
    // Cue points at a still image (or nothing). If we were playing a video, pause it.
    Iif (previous) {
      const prevHandle = ctx.play.bgaVideos.get(previous.key);
      if (prevHandle && !prevHandle.video.paused) {
        prevHandle.video.pause();
      }
      ctx.play.bgaActiveVideos[slot] = undefined;
    }
    return;
  }
  handle.video.playbackRate = (ctx.play.playbackTempo ?? ctx.play.tempo) * playbackRate;
  if (previous !== undefined && previous.key === key && previous.cueSeconds === (cue?.seconds ?? 0)) {
    // Same cue still active: the video plays forward on its own and the Pixi VideoSource pulls fresh frames each tick;
    // one that drifted from the chart is set back in step.
    const video = handle.video;
    // A seek, or a buffer that is not ready yet, aborts play() and leaves the element paused. Stopping there keeps
    // the black canvas behind the texture: the chart has a BGA, so the skin does not fall back to SOUND ONLY.
    // Retry until it plays. A seek still in progress, an ended video, and a paused play stay as they are.
    if (video.seeking) return;
    if (video.paused) {
      if (!ctx.play.paused && !video.ended) {
        void video.play().catch(() => {
          // The next frame tries again.
        });
      }
      return;
    }
    const resync = resolveBGAVideoResync(
      video.currentTime,
      (seconds - previous.cueSeconds) * playbackRate,
      video.duration,
    );
    if (resync === undefined) return;
    try {
      video.currentTime = resync;
    } catch {
      // Not seekable yet: the next frame tries again.
    }
    return;
  }
  if (previous) {
    const prevHandle = ctx.play.bgaVideos.get(previous.key);
    Eif (prevHandle && !prevHandle.video.paused) {
      prevHandle.video.pause();
    }
  }
  const cueSeconds = cue?.seconds ?? 0;
  ctx.play.bgaActiveVideos[slot] = { key: key!, cueSeconds };
  const offset = Math.max(0, (seconds - cueSeconds) * playbackRate);
  try {
    handle.video.currentTime = Math.min(offset, Math.max(0, handle.video.duration - 0.05) || offset);
  } catch {
    // Some browsers throw on currentTime assignment before the video has its initial buffer. The play() below, and
    // the same-cue path on the following frames, retry once the buffer arrives.
  }
  // A paused play (one sought while paused) shows the cue's frame; resuming plays the active videos.
  if (ctx.play.paused) return;
  void handle.video.play().catch(() => {
    // A rejection leaves the element paused. The same-cue path retries on the following frames.
  });
}
 
const tintedSkinImages = new WeakMap<BeMusicImage, Map<number, HTMLCanvasElement>>();
/**
 * Canvas skins receive already-tinted pixels, so existing skins honor the same plane controls as Pixi scenes. A still
 * image is tinted once per colour; a live source (video, keyed or cropped canvas) each frame, on the shared GPU context
 * where it can (`bga-gpu-pixels.ts`), so the frame is not read back.
 */
function tintSkinBGAImage(image: BeMusicImage | undefined, tint = 0xffffff): BeMusicImage | undefined {
  Eif (!image || tint === 0xffffff) return image;
  let colors = tintedSkinImages.get(image);
  if (!colors) {
    colors = new Map();
    tintedSkinImages.set(image, colors);
  }
  const existing = colors.get(tint);
  if (existing && ('naturalWidth' in image || (typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap)))
    return existing;
  const canvas = existing ?? document.createElement('canvas');
  Iif (!existing) {
    if (colors.size >= 4) colors.delete(colors.keys().next().value!);
    colors.set(tint, canvas);
  }
  const source = image as {
    videoWidth?: number;
    videoHeight?: number;
    naturalWidth?: number;
    naturalHeight?: number;
    width?: number;
    height?: number;
  };
  const width = source.videoWidth ?? source.naturalWidth ?? source.width ?? 0;
  const height = source.videoHeight ?? source.naturalHeight ?? source.height ?? 0;
  Iif (!width || !height) return undefined;
  if (canvas.width !== width || canvas.height !== height) {
    canvas.width = width;
    canvas.height = height;
  }
  const onGPU = canDrawBGAPixelsOnGPU();
  // Only the CPU path reads the pixels back; on the GPU path the canvas stays on the GPU.
  const context = canvas.getContext('2d', { willReadFrequently: !onGPU });
  if (!context) return undefined;
  try {
    if (onGPU && drawBGAPixelsOnGPU(image as TexImageSource, width, height, { tint }, context)) return canvas;
    context.clearRect(0, 0, width, height);
    context.drawImage(image, 0, 0);
    const pixels = context.getImageData(0, 0, width, height);
    for (let offset = 0; offset < pixels.data.length; offset += 4) {
      pixels.data[offset] = Math.round((pixels.data[offset]! * ((tint >>> 16) & 255)) / 255);
      pixels.data[offset + 1] = Math.round((pixels.data[offset + 1]! * ((tint >>> 8) & 255)) / 255);
      pixels.data[offset + 2] = Math.round((pixels.data[offset + 2]! * (tint & 255)) / 255);
    }
    context.putImageData(pixels, 0, 0);
    return canvas;
  } catch {
    return undefined;
  }
}