All files / player-terminal/src bga.ts

96.97% Statements 289/298
88.42% Branches 214/242
100% Functions 36/36
97.2% Lines 278/286

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 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072                                                                                                                      13x 13x 13x 13x 13x                                                                                                                       4x 4x             4x 4x       4x 4x 4x               4x             1x       38x     13x                                                             114x   114x   114x   114x                           114x   114x   114x   114x   114x   114x   114x   114x   114x   114x                         114x                                                               114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x           114x           114x           114x       83x 81x 83x 83x 23x   58x 58x 58x 58x 58x       25x 4x   21x 21x 21x 21x 21x       13x 13x 13x 13x 13x       49x 49x     49x 49x 49x                 108x 108x 1x   107x 105x     105x   107x                 377x 377x 377x               377x 377x 377x           377x           377x           377x       377x         377x 125x     252x         252x   252x         377x 955x                   377x     377x               377x 377x       163x           163x           163x           163x           163x           163x           163x           163x 163x       163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x 163x                 108x 108x 108x               108x   108x                 108x                 108x               108x                 108x                       2x     106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x         106x 106x                 386x         108x 108x                                       485x 485x 485x 485x 485x 485x 485x 485x           485x           485x                                                           108x       108x       108x       120x 87x   33x 33x                   114x 114x 114x 114x 114x   114x 114x 42x 42x   114x   114x 114x 234x 234x     114x 114x 114x 114x 114x 12x 12x 27x     114x 114x 8x 12x 12x 12x 12x 12x     114x   114x 114x 114x 8x   114x   114x       114x 114x 194x 174x   20x 20x           114x       114x   114x                                                                                                           114x   114x                   2x     112x 112x 112x   112x                                                                                                           456x 456x 456x 456x       200x 200x 200x 6x   194x 194x 194x 194x           194x   200x 200x 185x                     185x 185x     194x 194x 194x   194x         456x       456x 456x 200x 194x     456x       20x       167x                             5x 5x 5x                 5x 5x     5x 5x                           8x 8x 8x 8x 8x         8x     8x 8x     8x 8x 8x         8x                         8x          
import type { KeyBoundBGACue } from '@be-music/chart-model';
import { availableParallelism } from 'node:os';
import { runWithConcurrency, throwIfAborted } from '@be-music/shared-utils/core';
import type { BeMusicJSON } from '@be-music/chart-source';
import {
  parseBMSExBMP,
  buildBGAOpacityTimelines,
  buildKeyBoundBGATimeline,
  buildBmsonBGAEventTimeline,
  type BmsonBGAEventCue,
  pickBGAOpacity,
  pickBGATint,
  type BGAOpacityTimelines,
  resolvePoorBGAMode,
  type PoorBGAMode,
  resolveChart,
  type BGACue,
} from '@be-music/chart-model';
import {
  DEFAULT_IMAGE_RESIZE_ALGORITHM,
  DEFAULT_POOR_BGA_DISPLAY_SECONDS,
  pickActiveBGACue,
  type ImageResizeAlgorithm,
  type KeyBoundBGAFrame,
  type BmsonBGAFrame,
} from '@be-music/player-engine/display';
import {
  TERMINAL_PIXEL_ASPECT_X,
  TERMINAL_PIXEL_ASPECT_Y,
  type FrameMode,
  type ANSIFrame,
  createMissingSourceFrame,
  createSolidANSIFrame,
  resizeANSIFrame,
  placeHDXBGAFrame,
} from './bga-frame.ts';
import {
  type FrameSource,
  type FrameSelection,
  resizeFrameSourceMap,
  resolveFrameSelection,
  resizeFrameSource,
  resizeFrameSourceCover,
  resizeFrameSourceWithAspectMode,
  selectFrameFromSource,
  resolveTimelinePlaybackEndSeconds,
  startStreamingFrameSourceMap,
} from './bga-frame-source.ts';
import {
  type CompositeFrame,
  cropANSIFrameToOpaqueBounds,
  mergeCompositeLayers,
  fillANSIFrameBackground,
  composeANSILines,
  createBlackBackgroundANSILines,
} from './bga-compose.ts';
import { loadFrameSource, loadTerminalImageSourceFrame, resolveMediaPath } from './bga-media.ts';
import { cropBGAFrameSource, resolveBGAResource, type BGAResource } from './bga-subregions.ts';
 
const MAX_NORMAL_BGA_COMPOSITE_LAYERS = 3;
const DEFAULT_BGA_ASCII_WIDTH = 34;
const DEFAULT_BGA_ASCII_HEIGHT = 20;
const KITTY_GRAPHICS_PIXEL_SCALE = 4;
const BGA_SOURCE_LOAD_CONCURRENCY = Math.max(1, Math.min(8, availableParallelism()));
 
export interface BgaANSIOptions {
  /** Host-remapped selections; NONSTOP callers pass map.keyBoundBGA. */
  keyBoundBGACues?: readonly KeyBoundBGACue[];
  bmsonBGACues?: readonly BmsonBGAEventCue[];
  baseDir: string;
  width?: number;
  height?: number;
  imageResizeAlgorithm?: ImageResizeAlgorithm;
  videoBGAStreaming?: boolean;
  onLoadProgress?: (progress: BgaANSILoadProgress) => void;
  signal?: AbortSignal;
}
 
export interface BgaANSILoadProgress {
  ratio: number;
  detail: string;
}
 
interface TerminalANSIImageOptions extends Omit<BgaANSIOptions, 'baseDir' | 'onLoadProgress'> {
  fitMode?: 'contain' | 'cover';
  includeKittyImage?: boolean;
}
 
export interface TerminalANSIImage {
  width: number;
  height: number;
  rgb: Uint8Array;
  lines: string[];
  kittyImage?: TerminalKittyImage;
}
 
export interface TerminalKittyImage {
  pixelWidth: number;
  pixelHeight: number;
  cellWidth: number;
  cellHeight: number;
  rgb: Uint8Array;
}
 
export type StageFileANSIImage = TerminalANSIImage;
export type StageFileKittyImage = TerminalKittyImage;
 
type FrameSourceLoadCache = Map<string, Promise<FrameSource | null>>;
 
export interface BGAKittyImage {
  pixelWidth: number;
  pixelHeight: number;
  cellWidth: number;
  cellHeight: number;
  rgb: Uint8Array;
  token: string;
}
 
export async function loadTerminalANSIImage(
  baseDir: string,
  mediaPath: string,
  options: TerminalANSIImageOptions = {},
): Promise<TerminalANSIImage | undefined> {
  const loaded = await loadTerminalANSIImageInternal(baseDir, mediaPath, options);
  return loaded?.image;
}
 
export async function loadStageFileANSIImage(
  json: BeMusicJSON,
  options: Omit<BgaANSIOptions, 'onLoadProgress'>,
): Promise<StageFileANSIImage | undefined> {
  const stageFile = json.metadata.stageFile;
  Iif (typeof stageFile !== 'string' || stageFile.length === 0) {
    return undefined;
  }
 
  throwIfAborted(options.signal);
  const displaySize = normalizeDisplaySize(options.width, options.height);
  const loaded = await loadTerminalANSIImageInternal(options.baseDir, stageFile, {
    width: displaySize.width,
    height: displaySize.height,
    imageResizeAlgorithm: options.imageResizeAlgorithm,
    signal: options.signal,
    fitMode: 'cover',
    includeKittyImage: true,
  });
  return loaded?.image;
}
 
export async function loadStageFileANSILines(
  json: BeMusicJSON,
  options: Omit<BgaANSIOptions, 'onLoadProgress'>,
): Promise<string[] | undefined> {
  return (await loadStageFileANSIImage(json, options))?.lines;
}
 
function keyBoundResourceKey(id: string, bmp: string): string {
  return `${String.fromCharCode(0)}swbga:${id}:${bmp}`;
}
 
const EMPTY_KEY_BOUND_FRAME = createSolidANSIFrame(1, 1, 0, 0, 0, 0);
 
export class BgaANSIRenderer {
  readonly playbackEndSeconds: number;
 
  private readonly baseTimeline: BGACue[];
 
  private readonly poorTimeline: BGACue[];
 
  private readonly layerTimeline: BGACue[];
 
  private readonly layer2Timeline: BGACue[];
 
  private readonly baseSourceFramesByKey: Map<string, FrameSource>;
 
  private readonly poorSourceFramesByKey: Map<string, FrameSource>;
 
  private readonly layerSourceFramesByKey: Map<string, FrameSource>;
 
  private readonly layer2SourceFramesByKey: Map<string, FrameSource>;
 
  private readonly missingBaseSourceFrame: ANSIFrame;
 
  private readonly missingPoorSourceFrame: ANSIFrame;
 
  private readonly missingLayerSourceFrame: ANSIFrame;
 
  private readonly poorFallbackKey?: string;
 
  private readonly poorFallbackUntilSeconds: number;
 
  private baseFramesByKey = new Map<string, FrameSource>();
 
  private poorFramesByKey = new Map<string, FrameSource>();
 
  private layerFramesByKey = new Map<string, FrameSource>();
 
  private layer2FramesByKey = new Map<string, FrameSource>();
 
  private missingBaseFrame: ANSIFrame;
 
  private missingPoorFrame: ANSIFrame;
 
  private missingLayerFrame: ANSIFrame;
 
  private displayWidth: number;
 
  private displayHeight: number;
 
  private readonly resizeAlgorithm: ImageResizeAlgorithm;
 
  private cachedBaseKey = '__INIT__';
 
  private cachedLayerKey = '__INIT__';
 
  private cachedLayer2Key = '__INIT__';
 
  private cachedPoorKey = '__INIT__';
 
  private cachedBaseFrameIndex = -1;
 
  private cachedPoorFrameIndex = -1;
 
  private cachedLayerFrameIndex = -1;
 
  private cachedLayer2FrameIndex = -1;
 
  private cachedPoorActive = false;
 
  private cachedOpacityToken = '';
 
  private readonly opacityTimelines: BGAOpacityTimelines;
 
  private cachedComposite?: CompositeFrame;
 
  private cachedLines?: string[];
 
  private cachedKittyImage?: BGAKittyImage;
 
  private blackBackgroundLines: string[];
 
  private readonly poorBGAMode: PoorBGAMode;
  private poorActiveUntilSeconds = Number.NEGATIVE_INFINITY;
 
  /**
   * LR2 negative-BPM reversal: its event pump stops firing BGA cues there, so cue selection never looks past this
   * chart time. Elapsed time inside a cue (a movie that is already playing) and the POOR window stay on the true
   * clock. `+Infinity` when the chart has no reversal.
   */
  private readonly cueFreezeSeconds: number;
 
  constructor(params: {
    baseTimeline: BGACue[];
    poorTimeline: BGACue[];
    layerTimeline: BGACue[];
    layer2Timeline: BGACue[];
    baseSourceFramesByKey: Map<string, FrameSource>;
    poorSourceFramesByKey: Map<string, FrameSource>;
    layerSourceFramesByKey: Map<string, FrameSource>;
    layer2SourceFramesByKey: Map<string, FrameSource>;
    missingBaseSourceFrame: ANSIFrame;
    missingPoorSourceFrame: ANSIFrame;
    missingLayerSourceFrame: ANSIFrame;
    poorBGAMode?: PoorBGAMode;
    opacityTimelines?: BGAOpacityTimelines;
    poorFallbackKey?: string;
    poorFallbackUntilSeconds: number;
    playbackEndSeconds: number;
    /** Chart time at which BGA cues stop changing (the LR2 negative-BPM reversal). Defaults to never. */
    cueFreezeSeconds?: number;
    width: number;
    height: number;
    resizeAlgorithm: ImageResizeAlgorithm;
  }) {
    this.baseTimeline = params.baseTimeline;
    this.poorTimeline = params.poorTimeline;
    this.layerTimeline = params.layerTimeline;
    this.layer2Timeline = params.layer2Timeline;
    this.baseSourceFramesByKey = params.baseSourceFramesByKey;
    this.poorSourceFramesByKey = params.poorSourceFramesByKey;
    this.layerSourceFramesByKey = params.layerSourceFramesByKey;
    this.layer2SourceFramesByKey = params.layer2SourceFramesByKey;
    this.missingBaseSourceFrame = params.missingBaseSourceFrame;
    this.missingPoorSourceFrame = params.missingPoorSourceFrame;
    this.missingLayerSourceFrame = params.missingLayerSourceFrame;
    this.poorBGAMode = params.poorBGAMode ?? 0;
    this.opacityTimelines = params.opacityTimelines ?? { base: [], layer: [], layer2: [], poor: [] };
    this.poorFallbackKey = params.poorFallbackKey;
    this.poorFallbackUntilSeconds = params.poorFallbackUntilSeconds;
    this.playbackEndSeconds = params.playbackEndSeconds;
    this.cueFreezeSeconds = params.cueFreezeSeconds ?? Number.POSITIVE_INFINITY;
    this.displayWidth = params.width;
    this.displayHeight = params.height;
    this.resizeAlgorithm = params.resizeAlgorithm;
    this.blackBackgroundLines = [];
    this.missingBaseFrame = resizeANSIFrame(
      this.missingBaseSourceFrame,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.missingPoorFrame = resizeANSIFrame(
      this.missingPoorSourceFrame,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.missingLayerFrame = resizeANSIFrame(
      this.missingLayerSourceFrame,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.rebuildFrames();
  }
 
  triggerPoor(currentSeconds: number): void {
    if (this.poorBGAMode === 2) return;
    const safeCurrentSeconds = Number.isFinite(currentSeconds) ? currentSeconds : 0;
    const nextPoorActiveUntilSeconds = safeCurrentSeconds + DEFAULT_POOR_BGA_DISPLAY_SECONDS;
    if (nextPoorActiveUntilSeconds <= this.poorActiveUntilSeconds) {
      return;
    }
    this.poorActiveUntilSeconds = nextPoorActiveUntilSeconds;
    this.cachedPoorActive = false;
    this.cachedComposite = undefined;
    this.cachedLines = undefined;
    this.cachedKittyImage = undefined;
  }
 
  clearPoor(): void {
    if (this.poorActiveUntilSeconds === Number.NEGATIVE_INFINITY) {
      return;
    }
    this.poorActiveUntilSeconds = Number.NEGATIVE_INFINITY;
    this.cachedPoorActive = false;
    this.cachedComposite = undefined;
    this.cachedLines = undefined;
    this.cachedKittyImage = undefined;
  }
 
  startStreaming(): void {
    const seen = new Set<FrameSource>();
    startStreamingFrameSourceMap(this.baseSourceFramesByKey, seen);
    startStreamingFrameSourceMap(this.poorSourceFramesByKey, seen);
    startStreamingFrameSourceMap(this.layerSourceFramesByKey, seen);
    startStreamingFrameSourceMap(this.layer2SourceFramesByKey, seen);
  }
 
  setDisplaySize(width: number, height: number): void {
    const next = normalizeDisplaySize(width, height);
    Iif (next.width === this.displayWidth && next.height === this.displayHeight) {
      return;
    }
    this.displayWidth = next.width;
    this.displayHeight = next.height;
    this.rebuildFrames();
  }
 
  getANSILines(
    currentSeconds: number,
    keyBound?: KeyBoundBGAFrame,
    bmson?: BmsonBGAFrame,
    bgaMode?: 0 | 1 | 2,
  ): string[] | undefined {
    this.refreshComposite(currentSeconds, keyBound, bmson, bgaMode);
    if (!this.cachedComposite) {
      return this.blackBackgroundLines;
    }
    if (!this.cachedLines) {
      const frame = this.cachedComposite.alpha
        ? fillANSIFrameBackground(this.cachedComposite, 0, 0, 0)
        : this.cachedComposite;
      this.cachedLines = composeANSILines(frame.rgb, frame.opaqueMask, frame.width, frame.height);
    }
    return this.cachedLines;
  }
 
  getKittyImage(
    currentSeconds: number,
    keyBound?: KeyBoundBGAFrame,
    bmson?: BmsonBGAFrame,
    bgaMode?: 0 | 1 | 2,
  ): BGAKittyImage {
    const state = this.resolveActiveState(currentSeconds, bmson);
    const keyBoundKey = keyBound ? keyBoundResourceKey(keyBound.definitionId, keyBound.bmpKey) : '';
    const keyBoundSelection = keyBound
      ? resolveFrameSelection(
          this.layer2SourceFramesByKey,
          EMPTY_KEY_BOUND_FRAME,
          keyBoundKey,
          Math.max(0, (currentSeconds - keyBound.frameStartSeconds) * (keyBound.playbackRate ?? 1)),
        )
      : { frame: undefined, index: -1 };
    const pixelWidth = Math.max(1, this.displayWidth * KITTY_GRAPHICS_PIXEL_SCALE);
    const pixelHeight = Math.max(1, this.displayHeight * KITTY_GRAPHICS_PIXEL_SCALE);
    const baseSelection = resolveFrameSelection(
      this.baseSourceFramesByKey,
      this.missingBaseSourceFrame,
      state.baseKey,
      state.baseSeconds,
    );
    const layerSelection = resolveFrameSelection(
      this.layerSourceFramesByKey,
      this.missingLayerSourceFrame,
      state.layerKey,
      state.layerSeconds,
    );
    const layer2Selection = resolveFrameSelection(
      this.layer2SourceFramesByKey,
      this.missingLayerSourceFrame,
      state.layer2Key,
      state.layer2Seconds,
    );
    const poorSelection = state.poorActive
      ? resolveFrameSelection(this.poorSourceFramesByKey, this.missingPoorSourceFrame, state.poorKey, state.poorSeconds)
      : { frame: undefined, index: -1 };
    const token =
      `${pixelWidth}x${pixelHeight}:${bgaMode ?? ''}:` +
      `${state.baseKey}:${baseSelection.index}:` +
      `${state.layerKey}:${layerSelection.index}:` +
      `${state.layer2Key}:${layer2Selection.index}:` +
      `${state.poorActive ? '1' : '0'}:${state.poorKey}:${poorSelection.index}:${state.opacityToken}:${keyBoundKey}:${keyBoundSelection.index}`;
    if (this.cachedKittyImage?.token === token) {
      return this.cachedKittyImage;
    }
 
    const normalFrames = [
      { frame: baseSelection.frame, opacity: state.opacity.base, tint: state.tint.base },
      { frame: layerSelection.frame, opacity: state.opacity.layer, tint: state.tint.layer },
      { frame: layer2Selection.frame, opacity: state.opacity.layer2, tint: state.tint.layer2 },
    ].slice(0, MAX_NORMAL_BGA_COMPOSITE_LAYERS);
    const poorLayer = { frame: poorSelection.frame, opacity: state.opacity.poor, tint: state.tint.poor };
    const frames =
      state.poorActive && poorSelection.frame
        ? this.poorBGAMode === 1
          ? [...normalFrames, poorLayer]
          : [poorLayer]
        : normalFrames;
    const composite = mergeCompositeLayers(
      [...frames, { frame: keyBoundSelection.frame, opacity: 1, tint: 0xffffff }].map(({ frame, opacity, tint }) => ({
        frame: frame
          ? bgaMode === undefined
            ? resizeANSIFrame(frame, pixelWidth, pixelHeight, this.resizeAlgorithm)
            : placeHDXBGAFrame(frame, pixelWidth, pixelHeight, bgaMode)
          : undefined,
        opacity,
        tint,
      })),
    );
    const filledFrame = composite
      ? fillANSIFrameBackground(composite, 0, 0, 0)
      : createSolidANSIFrame(1, 1, 0, 0, 0, 1);
    const image = {
      pixelWidth: filledFrame.width,
      pixelHeight: filledFrame.height,
      cellWidth: this.displayWidth,
      cellHeight: this.displayHeight,
      rgb: filledFrame.rgb,
      token,
    };
    this.cachedKittyImage = image;
    return image;
  }
 
  private rebuildFrames(): void {
    this.baseFramesByKey = resizeFrameSourceMap(
      this.baseSourceFramesByKey,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.poorFramesByKey = resizeFrameSourceMap(
      this.poorSourceFramesByKey,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.layerFramesByKey = resizeFrameSourceMap(
      this.layerSourceFramesByKey,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.layer2FramesByKey = resizeFrameSourceMap(
      this.layer2SourceFramesByKey,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.missingBaseFrame = resizeANSIFrame(
      this.missingBaseSourceFrame,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.missingPoorFrame = resizeANSIFrame(
      this.missingPoorSourceFrame,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.missingLayerFrame = resizeANSIFrame(
      this.missingLayerSourceFrame,
      this.displayWidth,
      this.displayHeight,
      this.resizeAlgorithm,
    );
    this.blackBackgroundLines = createBlackBackgroundANSILines(this.displayWidth, this.displayHeight);
    this.resetCache();
  }
 
  private resetCache(): void {
    this.cachedBaseKey = '__INIT__';
    this.cachedLayerKey = '__INIT__';
    this.cachedLayer2Key = '__INIT__';
    this.cachedPoorKey = '__INIT__';
    this.cachedBaseFrameIndex = -1;
    this.cachedLayerFrameIndex = -1;
    this.cachedLayer2FrameIndex = -1;
    this.cachedPoorFrameIndex = -1;
    this.cachedPoorActive = false;
    this.cachedComposite = undefined;
    this.cachedLines = undefined;
    this.cachedKittyImage = undefined;
  }
 
  private refreshComposite(
    currentSeconds: number,
    keyBound?: KeyBoundBGAFrame,
    bmson?: BmsonBGAFrame,
    bgaMode?: 0 | 1 | 2,
  ): void {
    const state = this.resolveActiveState(currentSeconds, bmson);
    const keyBoundKey = keyBound ? keyBoundResourceKey(keyBound.definitionId, keyBound.bmpKey) : '';
    const keyBoundSelection = keyBound
      ? resolveFrameSelection(
          bgaMode === undefined ? this.layer2FramesByKey : this.layer2SourceFramesByKey,
          EMPTY_KEY_BOUND_FRAME,
          keyBoundKey,
          Math.max(0, (currentSeconds - keyBound.frameStartSeconds) * (keyBound.playbackRate ?? 1)),
        )
      : { frame: undefined, index: -1 };
    state.opacityToken += `:${keyBoundKey}:${keyBoundSelection.index}:${bgaMode ?? ''}`;
    const baseSelection =
      bgaMode === undefined
        ? this.resolveBaseFrame(state.baseKey, state.baseSeconds)
        : resolveFrameSelection(
            this.baseSourceFramesByKey,
            this.missingBaseSourceFrame,
            state.baseKey,
            state.baseSeconds,
          );
    const layerSelection =
      bgaMode === undefined
        ? this.resolveLayerFrame(state.layerKey, state.layerSeconds)
        : resolveFrameSelection(
            this.layerSourceFramesByKey,
            this.missingLayerSourceFrame,
            state.layerKey,
            state.layerSeconds,
          );
    const layer2Selection =
      bgaMode === undefined
        ? this.resolveLayer2Frame(state.layer2Key, state.layer2Seconds)
        : resolveFrameSelection(
            this.layer2SourceFramesByKey,
            this.missingLayerSourceFrame,
            state.layer2Key,
            state.layer2Seconds,
          );
    const poorSelection = state.poorActive
      ? resolveFrameSelection(
          bgaMode === undefined ? this.poorFramesByKey : this.poorSourceFramesByKey,
          bgaMode === undefined ? this.missingPoorFrame : this.missingPoorSourceFrame,
          state.poorKey,
          state.poorSeconds,
        )
      : { frame: undefined, index: -1 };
 
    if (
      this.cachedBaseKey === state.baseKey &&
      this.cachedLayerKey === state.layerKey &&
      this.cachedLayer2Key === state.layer2Key &&
      this.cachedPoorKey === state.poorKey &&
      this.cachedBaseFrameIndex === baseSelection.index &&
      this.cachedLayerFrameIndex === layerSelection.index &&
      this.cachedLayer2FrameIndex === layer2Selection.index &&
      this.cachedPoorFrameIndex === poorSelection.index &&
      this.cachedPoorActive === state.poorActive &&
      this.cachedOpacityToken === state.opacityToken
    ) {
      return;
    }
 
    this.cachedBaseKey = state.baseKey;
    this.cachedLayerKey = state.layerKey;
    this.cachedLayer2Key = state.layer2Key;
    this.cachedPoorKey = state.poorKey;
    this.cachedBaseFrameIndex = baseSelection.index;
    this.cachedLayerFrameIndex = layerSelection.index;
    this.cachedLayer2FrameIndex = layer2Selection.index;
    this.cachedPoorFrameIndex = poorSelection.index;
    this.cachedPoorActive = state.poorActive;
    this.cachedOpacityToken = state.opacityToken;
    const normalFrames = [
      { frame: baseSelection.frame, opacity: state.opacity.base, tint: state.tint.base },
      { frame: layerSelection.frame, opacity: state.opacity.layer, tint: state.tint.layer },
      { frame: layer2Selection.frame, opacity: state.opacity.layer2, tint: state.tint.layer2 },
    ].slice(0, MAX_NORMAL_BGA_COMPOSITE_LAYERS);
    const poorLayer = { frame: poorSelection.frame, opacity: state.opacity.poor, tint: state.tint.poor };
    this.cachedComposite = mergeCompositeLayers(
      [
        ...(state.poorActive && poorSelection.frame
          ? this.poorBGAMode === 1
            ? [...normalFrames, poorLayer]
            : [poorLayer]
          : normalFrames),
        { frame: keyBoundSelection.frame, opacity: 1 },
      ].map((layer) =>
        bgaMode === undefined || layer.frame === undefined
          ? layer
          : { ...layer, frame: placeHDXBGAFrame(layer.frame, this.displayWidth, this.displayHeight, bgaMode) },
      ),
    );
    this.cachedLines = undefined;
    this.cachedKittyImage = undefined;
  }
 
  private resolveActiveState(
    currentSeconds: number,
    bmson?: BmsonBGAFrame,
  ): {
    baseKey: string;
    layerKey: string;
    layer2Key: string;
    poorKey: string;
    baseSeconds: number;
    layerSeconds: number;
    layer2Seconds: number;
    poorSeconds: number;
    poorActive: boolean;
    opacity: Record<keyof BGAOpacityTimelines, number>;
    opacityToken: string;
    tint: Record<keyof BGAOpacityTimelines, number>;
  } {
    const cueSeconds = Math.min(currentSeconds, this.cueFreezeSeconds);
    const baseCue = pickActiveBGACue(this.baseTimeline, cueSeconds);
    const layerCue = pickActiveBGACue(this.layerTimeline, cueSeconds);
    const layer2Cue = pickActiveBGACue(this.layer2Timeline, cueSeconds);
    const poorCue = pickActiveBGACue(this.poorTimeline, cueSeconds);
    const sequencePoor = bmson?.plane === 'poor' && this.poorBGAMode !== 2;
    const poorActive = sequencePoor || (this.poorBGAMode !== 2 && currentSeconds < this.poorActiveUntilSeconds);
    const opacity = {
      base: pickBGAOpacity(this.opacityTimelines.base, cueSeconds),
      layer: pickBGAOpacity(this.opacityTimelines.layer, cueSeconds),
      layer2: pickBGAOpacity(this.opacityTimelines.layer2, cueSeconds),
      poor: pickBGAOpacity(this.opacityTimelines.poor, cueSeconds),
    };
    const tint = {
      base: pickBGATint(this.opacityTimelines.base, cueSeconds),
      layer: pickBGATint(this.opacityTimelines.layer, cueSeconds),
      layer2: pickBGATint(this.opacityTimelines.layer2, cueSeconds),
      poor: pickBGATint(this.opacityTimelines.poor, cueSeconds),
    };
    return {
      opacity,
      tint,
      opacityToken: [...Object.values(opacity), ...Object.values(tint)].join(':'),
      baseKey: baseCue?.key ?? '',
      layerKey: bmson?.plane === 'layer' ? (bmson.key ?? '') : (layerCue?.key ?? ''),
      layer2Key: layer2Cue?.key ?? '',
      poorKey: sequencePoor
        ? (bmson.key ?? '')
        : poorActive
          ? (this.resolvePoorKey(poorCue, currentSeconds) ?? '')
          : '',
      baseSeconds: baseCue ? Math.max(0, currentSeconds - baseCue.seconds) : Math.max(0, currentSeconds),
      layerSeconds:
        bmson?.plane === 'layer'
          ? Math.max(0, (currentSeconds - bmson.frameStartSeconds) * (bmson.playbackRate ?? 1))
          : layerCue
            ? Math.max(0, currentSeconds - layerCue.seconds)
            : 0,
      layer2Seconds: layer2Cue ? Math.max(0, currentSeconds - layer2Cue.seconds) : 0,
      poorSeconds: sequencePoor
        ? Math.max(0, (currentSeconds - bmson.frameStartSeconds) * (bmson.playbackRate ?? 1))
        : poorCue
          ? Math.max(0, currentSeconds - poorCue.seconds)
          : Math.max(0, currentSeconds),
      poorActive,
    };
  }
 
  private resolveBaseFrame(baseKey: string, seconds: number): FrameSelection {
    return resolveFrameSelection(this.baseFramesByKey, this.missingBaseFrame, baseKey, seconds);
  }
 
  private resolveLayerFrame(layerKey: string, seconds: number): FrameSelection {
    return resolveFrameSelection(this.layerFramesByKey, this.missingLayerFrame, layerKey, seconds);
  }
 
  private resolveLayer2Frame(layer2Key: string, seconds: number): FrameSelection {
    return resolveFrameSelection(this.layer2FramesByKey, this.missingLayerFrame, layer2Key, seconds);
  }
 
  private resolvePoorKey(poorCue: BGACue | undefined, currentSeconds: number): string | undefined {
    if (poorCue) {
      return poorCue.key;
    }
    Eif (this.poorFallbackKey && currentSeconds < this.poorFallbackUntilSeconds) {
      return this.poorFallbackKey;
    }
    return undefined;
  }
}
 
export async function createBgaANSIRenderer(
  json: BeMusicJSON,
  options: BgaANSIOptions,
): Promise<BgaANSIRenderer | undefined> {
  throwIfAborted(options.signal);
  const displaySize = normalizeDisplaySize(options.width, options.height);
  const resizeAlgorithm = options.imageResizeAlgorithm ?? DEFAULT_IMAGE_RESIZE_ALGORITHM;
  const resolved = resolveChart(json);
  const { base: baseTimeline, poor: poorTimeline, layer: layerTimeline, layer2: layer2Timeline } = resolved.bga;
  // bmson cues carry header filenames directly; BMS cues carry resource slots. Keep that lookup local to loading.
  const resources = { ...json.resources.bmp };
  for (const [key, raw] of Object.entries(json.bms.exBMP)) {
    const definition = parseBMSExBMP(raw);
    if (definition && !resources[key]) resources[key] = definition.filename;
  }
  for (const entry of json.bmson.bga.header) resources[entry.name] = entry.name;
 
  const resourceDefinitions = new Map<string, BGAResource>();
  for (const key of new Set([...Object.keys(resources), ...Object.keys(json.bms.bga)])) {
    const definition = resolveBGAResource(json, resources, key);
    if (definition) resourceDefinitions.set(key, definition);
  }
 
  const baseKeys = new Set(baseTimeline.flatMap((cue) => (cue.key ? [cue.key] : [])));
  const poorKeys = new Set(poorTimeline.flatMap((cue) => (cue.key ? [cue.key] : [])));
  const layerKeys = new Set(layerTimeline.flatMap((cue) => (cue.key ? [cue.key] : [])));
  const layer2Keys = new Set(layer2Timeline.flatMap((cue) => (cue.key ? [cue.key] : [])));
  for (const cue of options.bmsonBGACues ?? buildBmsonBGAEventTimeline(json, resolved.timing)) {
    const keys = cue.condition === 'miss' ? poorKeys : layerKeys;
    for (const sequence of cue.sequences) {
      for (const frame of sequence.frames) if (frame.key) keys.add(frame.key);
    }
  }
  const keyBoundKeys = new Set<string>();
  for (const cue of options.keyBoundBGACues ?? buildKeyBoundBGATimeline(json, resolved.timing)) {
    for (const bmp of cue.definition.frames) {
      const key = keyBoundResourceKey(cue.definitionId, bmp);
      const resource = resourceDefinitions.get(bmp);
      Iif (!resource) continue;
      resourceDefinitions.set(key, { ...resource, swBGAColorKey: cue.definition.argb });
      keyBoundKeys.add(key);
    }
  }
  for (const key of keyBoundKeys) layer2Keys.add(key);
  // LR2 starts its miss layer from `#BMP00`; only `#POORBGA 2` (no POOR image) turns that off.
  const shouldUsePoorBMP00Fallback = resolvePoorBGAMode(json.bms.poorBGA) !== 2 && resourceDefinitions.has('00');
  const poorFallbackKey = shouldUsePoorBMP00Fallback ? '00' : undefined;
  if (poorFallbackKey) {
    poorKeys.add(poorFallbackKey);
  }
  const poorFallbackUntilSeconds = poorTimeline[0]?.seconds ?? Number.POSITIVE_INFINITY;
  const totalLoadTargetCount =
    countMappedBMPResourceTargets(baseKeys, resourceDefinitions) +
    countMappedBMPResourceTargets(poorKeys, resourceDefinitions) +
    countMappedBMPResourceTargets(layerKeys, resourceDefinitions) +
    countMappedBMPResourceTargets(layer2Keys, resourceDefinitions);
  let loadedTargetCount = 0;
  const reportLoadProgress = (detail: string): void => {
    if (!options.onLoadProgress || totalLoadTargetCount <= 0) {
      return;
    }
    loadedTargetCount += 1;
    options.onLoadProgress({
      ratio: Math.max(0, Math.min(1, loadedTargetCount / totalLoadTargetCount)),
      detail: normalizeProgressDetail(detail),
    });
  };
 
  const sharedSourceCache: FrameSourceLoadCache = new Map();
  // bmson 1.0.0 spec — layer images "will not have black pixels made transparent", unlike BMS `#xxx07`. Pick the
  // spec-aware overlay mode for bmson charts so the layer compositor skips the black chroma-key while still honoring
  // the PNG alpha channel. BMS / json sources stay on the historical `'layer'` mode.
  const layerMode: FrameMode = json.sourceFormat === 'bmson' ? 'bmson-layer' : 'layer';
  const [baseSourceFramesByKey, poorSourceFramesByKey, layerSourceFramesByKey, layer2SourceFramesByKey] =
    await Promise.all([
      loadFramesByKeys({
        keys: baseKeys,
        resources: resourceDefinitions,
        baseDir: options.baseDir,
        mode: 'base',
        width: displaySize.width,
        height: displaySize.height,
        imageResizeAlgorithm: resizeAlgorithm,
        videoBGAStreaming: options.videoBGAStreaming,
        onLoadProgress: reportLoadProgress,
        signal: options.signal,
        sharedSourceCache,
      }),
      loadFramesByKeys({
        keys: poorKeys,
        resources: resourceDefinitions,
        baseDir: options.baseDir,
        mode: resolvePoorBGAMode(json.bms.poorBGA) === 1 ? 'bmson-layer' : 'base',
        width: displaySize.width,
        height: displaySize.height,
        imageResizeAlgorithm: resizeAlgorithm,
        videoBGAStreaming: options.videoBGAStreaming,
        onLoadProgress: reportLoadProgress,
        signal: options.signal,
        sharedSourceCache,
      }),
      loadFramesByKeys({
        keys: layerKeys,
        resources: resourceDefinitions,
        baseDir: options.baseDir,
        mode: layerMode,
        width: displaySize.width,
        height: displaySize.height,
        imageResizeAlgorithm: resizeAlgorithm,
        videoBGAStreaming: options.videoBGAStreaming,
        onLoadProgress: reportLoadProgress,
        signal: options.signal,
        sharedSourceCache,
      }),
      loadFramesByKeys({
        keys: layer2Keys,
        resources: resourceDefinitions,
        baseDir: options.baseDir,
        mode: layerMode,
        width: displaySize.width,
        height: displaySize.height,
        imageResizeAlgorithm: resizeAlgorithm,
        videoBGAStreaming: options.videoBGAStreaming,
        onLoadProgress: reportLoadProgress,
        signal: options.signal,
        sharedSourceCache,
      }),
    ]);
  throwIfAborted(options.signal);
 
  if (
    baseSourceFramesByKey.size === 0 &&
    poorSourceFramesByKey.size === 0 &&
    layerSourceFramesByKey.size === 0 &&
    layer2SourceFramesByKey.size === 0 &&
    baseTimeline.length === 0 &&
    poorTimeline.length === 0 &&
    layerTimeline.length === 0 &&
    layer2Timeline.length === 0
  ) {
    return undefined;
  }
 
  const missingBaseSourceFrame = createMissingSourceFrame('base');
  const missingPoorSourceFrame = createMissingSourceFrame('base');
  const missingLayerSourceFrame = createMissingSourceFrame('layer');
 
  return new BgaANSIRenderer({
    baseTimeline,
    poorTimeline,
    layerTimeline,
    layer2Timeline,
    baseSourceFramesByKey,
    poorSourceFramesByKey,
    layerSourceFramesByKey,
    layer2SourceFramesByKey,
    missingBaseSourceFrame,
    missingPoorSourceFrame,
    missingLayerSourceFrame,
    poorBGAMode: resolvePoorBGAMode(json.bms.poorBGA),
    opacityTimelines: buildBGAOpacityTimelines(json, resolved.timing),
    poorFallbackKey,
    poorFallbackUntilSeconds,
    playbackEndSeconds: Math.max(
      resolveTimelinePlaybackEndSeconds(baseTimeline, baseSourceFramesByKey),
      resolveTimelinePlaybackEndSeconds(layerTimeline, layerSourceFramesByKey),
      resolveTimelinePlaybackEndSeconds(layer2Timeline, layer2SourceFramesByKey),
    ),
    // BGA cues on the LR2 reversal tick still fire (ops 4/6/7 precede the negative BPM's op 8); later ones never do.
    cueFreezeSeconds: resolved.reversal?.seconds,
    width: displaySize.width,
    height: displaySize.height,
    resizeAlgorithm,
  });
}
 
async function loadFramesByKeys(params: {
  keys: ReadonlySet<string>;
  resources: ReadonlyMap<string, BGAResource>;
  baseDir: string;
  mode: FrameMode;
  width: number;
  height: number;
  imageResizeAlgorithm: ImageResizeAlgorithm;
  videoBGAStreaming?: boolean;
  onLoadProgress?: (detail: string) => void;
  signal?: AbortSignal;
  sharedSourceCache: FrameSourceLoadCache;
}): Promise<Map<string, FrameSource>> {
  const {
    keys,
    resources,
    baseDir,
    mode,
    width,
    height,
    imageResizeAlgorithm,
    videoBGAStreaming,
    onLoadProgress,
    signal,
    sharedSourceCache,
  } = params;
  const map = new Map<string, FrameSource>();
  const orderedKeys = [...keys];
  await runWithConcurrency(
    orderedKeys,
    Math.min(orderedKeys.length || 1, BGA_SOURCE_LOAD_CONCURRENCY),
    async (key) => {
      throwIfAborted(signal);
      const definition = resources.get(key);
      if (!definition) {
        return;
      }
      const resourcePath = definition.path;
      const preserveSourceGeometry = definition.regions.length > 0;
      const resolved = await resolveMediaPath(baseDir, resourcePath, signal);
      Iif (!resolved) {
        onLoadProgress?.(resourcePath);
        return;
      }
 
      const cacheKey =
        `${mode}:${preserveSourceGeometry ? 'native' : 'spec'}:${width}x${height}:${imageResizeAlgorithm}:` +
        `${videoBGAStreaming === false ? 'full' : 'stream'}:${JSON.stringify(definition.colorKey)}:${JSON.stringify(definition.swBGAColorKey)}:${resolved}`;
      let sourcePromise = sharedSourceCache.get(cacheKey);
      if (!sourcePromise) {
        sourcePromise = loadFrameSource(
          resolved,
          mode,
          width,
          height,
          imageResizeAlgorithm,
          videoBGAStreaming,
          signal,
          preserveSourceGeometry,
          definition.colorKey,
          definition.swBGAColorKey,
        ).then((source) => source ?? null);
        sharedSourceCache.set(cacheKey, sourcePromise);
      }
 
      const source = await sourcePromise;
      Eif (source) {
        map.set(key, cropBGAFrameSource(source, definition.regions, mode));
      }
      onLoadProgress?.(resourcePath);
    },
    { signal },
  );
 
  return map;
}
 
function countMappedBMPResourceTargets(keys: ReadonlySet<string>, resources: ReadonlyMap<string, BGAResource>): number {
  let count = 0;
  for (const key of keys) {
    if (resources.has(key)) {
      count += 1;
    }
  }
  return count;
}
 
function normalizeProgressDetail(detail: string): string {
  return detail.replaceAll('\\', '/');
}
 
function normalizeDisplaySize(width?: number, height?: number): { width: number; height: number } {
  return {
    width: Math.max(8, Math.floor(width ?? DEFAULT_BGA_ASCII_WIDTH)),
    height: Math.max(6, Math.floor(height ?? DEFAULT_BGA_ASCII_HEIGHT)),
  };
}
 
function buildTerminalKittyImage(
  source: FrameSource,
  cellWidth: number,
  cellHeight: number,
  fitMode: 'contain' | 'cover',
  resizeAlgorithm = DEFAULT_IMAGE_RESIZE_ALGORITHM,
  aspectX = TERMINAL_PIXEL_ASPECT_X,
  aspectY = TERMINAL_PIXEL_ASPECT_Y,
): TerminalKittyImage | undefined {
  const pixelWidth = Math.max(1, Math.floor(cellWidth) * KITTY_GRAPHICS_PIXEL_SCALE);
  const pixelHeight = Math.max(1, Math.floor(cellHeight) * KITTY_GRAPHICS_PIXEL_SCALE);
  const resizedSource = resizeFrameSourceWithAspectMode(
    source,
    pixelWidth,
    pixelHeight,
    aspectX,
    aspectY,
    fitMode,
    resizeAlgorithm,
  );
  const frame = selectFrameFromSource(resizedSource, 0).frame;
  Iif (!frame) {
    return undefined;
  }
  const filledFrame = fillANSIFrameBackground(frame, 0, 0, 0);
  return {
    pixelWidth: filledFrame.width,
    pixelHeight: filledFrame.height,
    cellWidth: Math.max(1, Math.floor(cellWidth)),
    cellHeight: Math.max(1, Math.floor(cellHeight)),
    rgb: filledFrame.rgb,
  };
}
 
async function loadTerminalANSIImageInternal(
  baseDir: string,
  mediaPath: string,
  options: TerminalANSIImageOptions = {},
): Promise<{ image: TerminalANSIImage; sourceFrame: FrameSource } | undefined> {
  throwIfAborted(options.signal);
  const displaySize = normalizeTerminalImageDisplaySize(options.width, options.height);
  const resizeAlgorithm = options.imageResizeAlgorithm ?? DEFAULT_IMAGE_RESIZE_ALGORITHM;
  const sourceFrame = await loadTerminalImageSourceFrame(baseDir, mediaPath, options.signal);
  Iif (!sourceFrame) {
    return undefined;
  }
 
  const resizedSource =
    options.fitMode === 'cover'
      ? resizeFrameSourceCover(sourceFrame, displaySize.width, displaySize.height, resizeAlgorithm)
      : resizeFrameSource(sourceFrame, displaySize.width, displaySize.height, resizeAlgorithm);
  const selected = selectFrameFromSource(resizedSource, 0);
  Iif (!selected.frame) {
    return undefined;
  }
  const outputFrame = options.fitMode === 'cover' ? selected.frame : cropANSIFrameToOpaqueBounds(selected.frame);
  const filledFrame = fillANSIFrameBackground(outputFrame, 0, 0, 0);
  const kittyImage = options.includeKittyImage
    ? options.fitMode === 'cover'
      ? buildTerminalKittyImage(sourceFrame, displaySize.width, displaySize.height, 'cover', resizeAlgorithm)
      : buildTerminalKittyImage(sourceFrame, filledFrame.width, filledFrame.height, 'contain', resizeAlgorithm)
    : undefined;
  return {
    sourceFrame,
    image: {
      width: filledFrame.width,
      height: filledFrame.height,
      rgb: filledFrame.rgb,
      lines: composeANSILines(filledFrame.rgb, filledFrame.opaqueMask, filledFrame.width, filledFrame.height),
      kittyImage,
    },
  };
}
 
function normalizeTerminalImageDisplaySize(width?: number, height?: number): { width: number; height: number } {
  return {
    width: Math.max(1, Math.floor(width ?? DEFAULT_BGA_ASCII_WIDTH)),
    height: Math.max(1, Math.floor(height ?? DEFAULT_BGA_ASCII_HEIGHT)),
  };
}