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 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 | 74x 74x 74x 4x 1x 17x 17x 17x 74x 74x 74x 74x 3x 9x 3x 3x 9x 7x 7x 2x 2x 2x 2x 2x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 74x 17x 74x 49x 10x 5x 7x 13x 13x 13x 4x 4x 4x 4x 4x 9x 9x 1x 8x 8x 3x 3x 2x 6x 6x 6x 7x 7x 7x 7x 7x 2x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 13x 2x 11x 11x 6x 6x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 8x 8x 8x 8x 8x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 2x 2x 1x 1x 2x 2x 1x 1x 9x 9x 7x 2x 5x 2x 3x 2x 11x 11x | import { applyBMSColorKey, type BmsARGB } from '@be-music/chart-model';
import { Texture, VideoSource } from 'pixi.js';
import { logger } from '../logger.ts';
// Types only: the runtime module is imported on demand in `transcodeViaWebCodecsLocked`.
import type { BufferTarget, Mp4OutputFormat, Output } from 'mediabunny';
import {
buildScaleFilterArg,
estimateBGATranscodeBitrate,
FFMPEG_CORE_URL,
FFMPEG_WASM_URL,
resolveBGATranscodeCRF,
type BGATranscodeQuality,
} from './bga-stream/ffmpeg-args.ts';
import { attachBGAVideoStream } from './bga-stream/media-source.ts';
import { canStreamBGAVideo, openBGAVideoStream, pickInputExtension } from './bga-stream/stream.ts';
const log = logger('bga-video');
let ffmpegQueue: Promise<void> = Promise.resolve();
async function withExclusiveFFmpeg<T>(task: () => Promise<T>): Promise<T> {
const previous = ffmpegQueue;
let release: () => void = () => {};
ffmpegQueue = new Promise<void>((resolve) => {
release = resolve;
});
await previous;
try {
return await task();
} finally {
release();
}
}
/**
* Symbol used to attach a blob `objectURL` to a `Texture` so that downstream destroy paths
* (`destroyUniqueTextures`, `LR2SkinTextureStore.clear()`) can revoke the URL alongside the GPU resource.
*
* Pixi v8 doesn't surface a destroy hook on `TextureSource`, and we can't simply `URL.revokeObjectURL` on the load path
* — the texture's `<img>` source keeps a reference to the URL for the lifetime of the GPU upload (and for re-decode on
* a WebGL context-loss event). Storing the URL on the texture itself lets the destroy site free both at once, without
* forcing every texture map to carry a parallel `Map<Texture, string>`.
*/
const TEXTURE_BLOB_URL = Symbol.for('be-music-player-web/texture-blob-url');
interface TextureWithBlobURL extends Texture {
[TEXTURE_BLOB_URL]?: string;
}
/**
* Records the blob `objectURL` the texture was decoded from. The URL is revoked the next time the texture passes
* through {@link destroyTextureAndRevokeBlobURL}.
*
* Defensively no-op when `texture` is null/undefined: Pixi v8's `Assets.load(url)` occasionally resolves with a
* falsy value for unsupported payloads (notably when the URL points at bytes that don't match the MIME-implied
* format — e.g. a `.dds` file blob-loaded as `image/png` falls through every decoder and resolves to null). The
* defensive branch keeps a stray null from cascading into a `Cannot set properties of null (setting 'Symbol...')`
* crash and lets the caller route the decode result through its normal "unsupported asset" fallback. Returns the
* texture unchanged so existing callers can keep using `attachBlobURLToTexture(t, url)` as a pass-through.
*/
export function attachBlobURLToTexture(texture: Texture | null | undefined, objectURL: string): void {
if (texture === null || texture === undefined) return;
(texture as TextureWithBlobURL)[TEXTURE_BLOB_URL] = objectURL;
}
/**
* Destroys `texture` and, if it was created from a blob via {@link attachBlobURLToTexture}, revokes the associated
* object URL. `destroySource` mirrors `Texture.destroy(destroySource)` — pass `true` (the default) to also tear down
* the underlying `TextureSource`. Errors thrown by Pixi's destroy path are propagated; the URL is still revoked first
* so a failed destroy doesn't strand the blob in the URL store.
*/
export function destroyTextureAndRevokeBlobURL(texture: Texture, destroySource = true): void {
const url = (texture as TextureWithBlobURL)[TEXTURE_BLOB_URL];
Iif (typeof url === 'string') {
URL.revokeObjectURL(url);
delete (texture as TextureWithBlobURL)[TEXTURE_BLOB_URL];
}
texture.destroy(destroySource);
}
/**
* Result of `loadVideoTexture`. The texture is a Pixi `Texture` whose source is a `VideoSource` wrapping the
* same `<video>` element returned alongside it. Callers seek / play the video element directly to drive frame updates;
* the Pixi source polls `requestVideoFrameCallback` (or a rAF fallback) to push fresh frames into the GL texture.
*
* The associated `objectURL` is created from the bytes' `Blob` and MUST be revoked (via `URL.revokeObjectURL`) once the
* texture is disposed to free the underlying memory.
*/
export interface VideoTextureHandle {
texture: Texture;
video: HTMLVideoElement;
objectURL: string;
}
/**
* Tunables for the ffmpeg.wasm fallback path. Plumbed through from the host so end-users can trade encode time for
* visual resolution at runtime (the player wires this to a Tweakpane pair).
*/
export interface VideoTranscodeOptions {
/**
* When set to a positive integer, the transcode pass downscales the source so neither side exceeds this many pixels
* (aspect ratio preserved). Single-threaded libx264's per-frame cost scales linearly with width × height, so this is
* the single biggest lever we have once `-preset ultrafast` is in effect. BMS BGA renders into a 256-px spec canvas
* and even at 3× DPR tops out near 768 px on screen, so caps in the 480–720 range are visually transparent under
* nearest-filter scaling.
*
* `undefined` / `0` / negative values disable the cap and the source resolution is preserved verbatim (the original
* behavior).
*/
maxLongEdgePx?: number;
/**
* When true, the encode step uses the WebCodecs `VideoEncoder` API instead of libx264 in the wasm core. The decode
* step still goes through ffmpeg.wasm because WebCodecs' `VideoDecoder` doesn't support the legacy codecs (MPEG-1,
* VC-1, etc.) BMS BGA usually ships in.
*
* WebCodecs is hardware-accelerated where the browser's platform decoder/encoder is available — typically a 5–20×
* encode-side speedup over the single-threaded wasm libx264. Falls back to the ffmpeg-only path silently when the
* browser doesn't expose `VideoEncoder` (currently Safari < 17 / older Firefox builds), when `isConfigSupported`
* rejects the requested codec parameters, or when any step of the WebCodecs pipeline throws.
*/
useWebCodecs?: boolean;
/** How much bitrate the encode spends (libx264's `-crf`, WebCodecs' bitrate), `standard` by default. */
quality?: BGATranscodeQuality;
/** Estimated conversion progress until the video is ready to play. */
onProgress?: (fraction: number) => void;
}
/**
* Loads a video file (`mp4` / `webm` / etc.) into a Pixi `Texture` backed by an HTML `<video>` element. The video
* starts paused and muted — the caller is expected to seek + `.play()` it on cue.
*
* When the browser refuses to decode the original bytes — typical for legacy BMS BGA shipping `.mpg` / `.wmv` / `.avi`
* that no modern browser plays natively — the video is transcoded to H.264 with ffmpeg.wasm:
*
* - **Streaming** (when the host installed the workers, see `configureBGAVideoWorkers`, and the browser has Media
* Source Extensions): the `<video>` plays fragmented MP4 through a `MediaSource` while the transcode is still
* running, so this returns as soon as the first frame is decoded.
* - **Whole file** otherwise, or when the stream fails before its first frame: {@link transcodeVideoToBrowserCodec}
* writes a complete MP4 in memory and feeds that back through the same `<video>` path.
*
* Either way the rest of the BGA pipeline (Pixi `VideoSource`, frame polling) is identical to a native video.
*
* `file` is a dropped `File` or an archive entry's bytes. A `File` is played and streamed from where it lies, without
* reading it into memory; only the whole-file transcode reads it.
*
* Returns `undefined` only when the native decode and every transcode fail — at that point we accept the asset is
* unplayable and the BGA preloader simply skips it.
*/
export async function loadVideoTexture(
path: string,
file: Blob | Uint8Array,
options?: VideoTranscodeOptions,
): Promise<VideoTextureHandle | undefined> {
const source = videoBlobOf(file);
const direct = await tryLoadVideoTextureFromBlob(path, source);
if (direct) return direct;
if (canStreamBGAVideo()) {
log.info(`native decode failed; streaming an ffmpeg.wasm transcode: ${path}`);
const streamed = await tryLoadStreamedVideoTexture(path, source, options);
if (streamed) return streamed;
}
log.info(`native decode failed; falling back to ffmpeg.wasm transcode: ${path}`);
const bytes = file instanceof Uint8Array ? file : new Uint8Array(await file.arrayBuffer());
let transcoded: Uint8Array | undefined;
if (options?.useWebCodecs && isWebCodecsEncodeSupported()) {
transcoded = await transcodeViaWebCodecs(bytes, path, options).catch((error) => {
log.warn(`WebCodecs transcode failed; falling back to ffmpeg encode: ${path}`, error);
return undefined;
});
}
if (!transcoded) {
transcoded = await transcodeVideoToBrowserCodec(bytes, path, options).catch((error) => {
log.warn(`transcode failed: ${path}`, error);
return undefined;
});
}
if (!transcoded) return undefined;
// The transcoded payload is always MP4 / H.264 (whether it came out of libx264 or the WebCodecs encoder); pass an
// explicit name so `guessVideoMIMEType` picks `video/mp4` and the browser's H.264 decoder takes the fast path.
return tryLoadVideoTextureFromBlob(`${stripVideoExtension(path)}.transcoded.mp4`, videoBlobOf(transcoded));
}
/**
* The blob behind each in-memory video, made once: the same bytes on several tracks then share one blob, which keys the
* stream that transcodes them once (`openBGAVideoStream`).
*/
const videoBlobs = new WeakMap<Uint8Array, Blob>();
function videoBlobOf(file: Blob | Uint8Array): Blob {
if (file instanceof Blob) return file;
let blob = videoBlobs.get(file);
if (!blob) {
// The `Uint8Array<ArrayBuffer>` cast narrows away the lib's `ArrayBufferLike` (which includes
// `SharedArrayBuffer`): every caller decodes regular `ArrayBuffer`s, so the runtime payload is identical.
blob = new Blob([file as Uint8Array<ArrayBuffer>]);
videoBlobs.set(file, blob);
}
return blob;
}
/**
* Browser-side check for the `VideoEncoder` half of WebCodecs. Used to gate the Web Codecs encode path before we even
* hand bytes to ffmpeg for decoding — there's no point paying the decode cost if we can't encode the result with
* WebCodecs.
*
* `'VideoEncoder' in globalThis` is the canonical feature detection; it avoids tripping a `ReferenceError` on older
* browsers (Safari < 17, older Firefox) that don't define the symbol at all.
*/
function isWebCodecsEncodeSupported(): boolean {
return typeof globalThis !== 'undefined' && 'VideoEncoder' in globalThis;
}
async function tryLoadVideoTextureFromBlob(path: string, file: Blob): Promise<VideoTextureHandle | undefined> {
// A slice of the whole blob shares its data (a `File` stays on disk) and carries the MIME type guessed from the path.
const blob = file.slice(0, file.size, guessVideoMIMEType(path));
const objectURL = URL.createObjectURL(blob);
const video = createBGAVideoElement();
video.src = objectURL;
return wrapVideoTexture(path, video, objectURL, () => waitForVideoMetadata(video, 5000));
}
/**
* How long a streamed BGA may take to show its first frame. The first one in a session also downloads the ~30 MB
* ffmpeg.wasm core; a stream that fails says so at once (the video's `error`), so this only bounds a stuck one.
*/
const STREAM_FIRST_FRAME_TIMEOUT_MS = 120_000;
/** Plays `source` through a streaming transcode (see {@link loadVideoTexture}); `undefined` if it fails. */
async function tryLoadStreamedVideoTexture(
path: string,
source: Blob,
options?: VideoTranscodeOptions,
): Promise<VideoTextureHandle | undefined> {
const maxLongEdge = resolveMaxLongEdge(options);
const stream = openBGAVideoStream(source, path, {
...(maxLongEdge !== undefined ? { maxLongEdge } : {}),
useWebCodecs: options?.useWebCodecs ?? true,
...(options?.quality !== undefined ? { quality: options.quality } : {}),
});
const video = createBGAVideoElement();
// Subscribes to the stream before anything is awaited, so the stream can't be cancelled under this video.
const objectURL = attachBGAVideoStream(video, stream);
// The init segment (metadata) leaves before the first fragment is encoded, which a slow libx264 encode can take a
// while over.
return wrapVideoTexture(
path,
video,
objectURL,
async () => {
await Promise.race([waitForVideoMetadata(video, STREAM_FIRST_FRAME_TIMEOUT_MS), stream.failure]);
options?.onProgress?.(0.5);
},
STREAM_FIRST_FRAME_TIMEOUT_MS,
);
}
function createBGAVideoElement(): HTMLVideoElement {
const video = document.createElement('video');
// BMS BGA video has no soundtrack of its own — audio comes from `#WAV` samples on the chart timeline. Muting also
// lets some browsers skip the autoplay-policy gating since silent media is exempt.
video.muted = true;
video.playsInline = true;
video.preload = 'auto';
video.crossOrigin = 'anonymous';
// `loop` is left at false — BGA cues drive when the video starts; looping would replay forever after the cue ends,
// which doesn't match BMS semantics.
video.loop = false;
return video;
}
/**
* Waits for `video`'s first frame (`waitForMetadata`, then the decoded frame) and wraps it in a Pixi texture; releases
* the video and `objectURL` and returns `undefined` if it never comes.
*/
async function wrapVideoTexture(
path: string,
video: HTMLVideoElement,
objectURL: string,
waitForMetadata: () => Promise<void>,
frameTimeoutMs = 5000,
): Promise<VideoTextureHandle | undefined> {
try {
await waitForMetadata();
// WAIT FOR THE FIRST FRAME, not just metadata. Pixi's WebGPU renderer calls
// `copyExternalImageToTexture(video)` at upload time and that fails with
// "Failed to import texture from video element that doesn't have back resource"
// when `readyState < HAVE_CURRENT_DATA` (= 2). `loadedmetadata` only guarantees
// readyState >= 1 (HAVE_METADATA — dimensions / duration known but no frame data),
// so on a paused-on-load BGA the very first render upload would crash. Holding for
// `loadeddata` ensures frame 0 is decoded before the source goes anywhere near the
// GPU.
await waitForVideoFrameData(video, frameTimeoutMs);
} catch {
releaseVideoElement(video);
URL.revokeObjectURL(objectURL);
return undefined;
}
const source = new VideoSource({ resource: video, autoPlay: false, autoLoad: true });
// BGA video should look as the artist authored it; nearest-pixel sampling matches our per-skin default for low-res
// BGA frames and avoids the smeary look the GPU's bilinear gives on 256x256 BMS-spec frames scaled up to 800px+
// playfields.
source.scaleMode = 'nearest';
source.label = path;
const texture = new Texture({ source });
texture.label = path;
return { texture, video, objectURL };
}
/**
* Lazy-imports libav.js (ffmpeg.wasm) and remuxes / re-encodes `bytes` to MP4 / H.264 / yuv420p — the
* lowest-common-denominator codec every modern browser plays natively. The libav module is a multi-megabyte WASM
* bundle, so the import is intentionally deferred to here: a typical drop with only modern BGA video never pays the
* download cost.
*
* `noworker: true` keeps everything on the main thread so the dev-server doesn't need to ship the COOP / COEP headers a
* worker-based libav build would otherwise require. Transcoding is CPU-bound but happens during the BGA prepare phase
* (which already overlaps the Decide splash), so the user never sees a frozen frame waiting for it.
*/
async function transcodeVideoToBrowserCodec(
bytes: Uint8Array,
path: string,
options?: VideoTranscodeOptions,
): Promise<Uint8Array | undefined> {
return withExclusiveFFmpeg(() => transcodeVideoToBrowserCodecLocked(bytes, path, options));
}
async function transcodeVideoToBrowserCodecLocked(
bytes: Uint8Array,
path: string,
options?: VideoTranscodeOptions,
): Promise<Uint8Array | undefined> {
const startedAt = performance.now();
const maxLongEdge = resolveMaxLongEdge(options);
log.info(`transcode start: ${path} (${bytes.byteLength} bytes${maxLongEdge ? `, resize ≤ ${maxLongEdge}px` : ''})`);
const ffmpeg = await loadFFmpeg().catch((error) => {
log.warn('failed to load ffmpeg.wasm — BGA video will be skipped', error);
return undefined;
});
if (!ffmpeg) return undefined;
const inputName = `bga-input${pickInputExtension(path)}`;
const outputName = 'bga-output.mp4';
try {
// Clone before handing to ffmpeg.wasm: the worker channel posts the buffer with `transfer` ownership (detaching the
// source ArrayBuffer), which would brick any caller that wants to retry the same bytes through a different
// transcode path (e.g. the WebCodecs → ffmpeg fallback chain in `loadVideoTexture`).
await ffmpeg.writeFile(inputName, new Uint8Array(bytes));
// libx264 fast path. Encoder-side flags chosen for the fastest possible single-threaded encode while keeping the
// output universally browser-decodable:
//
// - - `-c:v libx264 -pix_fmt yuv420p` — universally decoded - `-preset ultrafast` skips most analysis passes. -
// `-tune fastdecode,zerolatency` drops bidirectional prediction. `fastdecode` also swaps CABAC for CAVLC, which
// is ~10–15% faster to encode in addition to being faster to decode. - `-crf 30` trades a notch of quality for
// speed; BGA art tolerates it cleanly under nearest-filter scaling. - `-an` strips audio (BMS BGA's audio is
// irrelevant — `#WAV` drives chart audio). - `-movflags +faststart` puts the moov atom at the head of the file.
// Adds a second muxer pass but gives the `<video>` element predictable structure either way.
//
// `-vf scale=...` is only inserted when the host opted into resizing via `options.maxLongEdgePx`. See {@link
// buildScaleFilterArg} for the exact filter graph.
//
// No `-threads` override: the wasm core is single-threaded (see `loadFFmpeg` for why we don't use core-mt), so
// libx264 picks 1 by itself.
const ffmpegArgs: string[] = ['-y', '-i', inputName];
if (maxLongEdge) {
ffmpegArgs.push('-vf', buildScaleFilterArg(maxLongEdge));
}
ffmpegArgs.push(
'-c:v',
'libx264',
'-preset',
'ultrafast',
'-tune',
'fastdecode,zerolatency',
'-crf',
String(resolveBGATranscodeCRF(options?.quality)),
'-pix_fmt',
'yuv420p',
'-an',
'-movflags',
'+faststart',
outputName,
);
const report = ({ progress }: { progress: number }): void => {
if (Number.isFinite(progress)) options?.onProgress?.(Math.max(0, Math.min(0.95, 0.95 * progress)));
};
if (options?.onProgress) ffmpeg.on('progress', report);
let exitCode: number;
try {
exitCode = await ffmpeg.exec(ffmpegArgs);
} finally {
if (options?.onProgress) ffmpeg.off('progress', report);
}
if (exitCode !== 0) {
log.warn(`ffmpeg exited with code ${exitCode} for ${path}`);
return undefined;
}
const out = await ffmpeg.readFile(outputName);
let outBytes: Uint8Array | undefined;
if (out instanceof Uint8Array) {
outBytes = out;
} else if (typeof out === 'string') {
// ffmpeg.readFile can return string when no encoding is overridden — coerce via TextEncoder so we always return
// raw bytes downstream.
outBytes = new TextEncoder().encode(out);
}
if (!outBytes || outBytes.byteLength === 0) {
log.warn(`ffmpeg produced empty output for ${path}`);
return undefined;
}
const elapsed = ((performance.now() - startedAt) / 1000).toFixed(2);
log.info(`transcode ok: ${path} → ${outBytes.byteLength} bytes (${elapsed}s)`);
return outBytes;
} catch (error) {
log.warn(`transcode threw for ${path}`, error);
return undefined;
} finally {
try {
await ffmpeg.deleteFile(inputName);
} catch {
// ignore — the in-memory FS lives only as long as the FFmpeg instance, which we leak between calls (see
// `loadFFmpeg` for why) so cleanup just keeps the VFS tidy across calls.
}
try {
await ffmpeg.deleteFile(outputName);
} catch {
// ignore
}
}
}
/**
* Resolves the user's `maxLongEdgePx` knob into a strictly positive integer (or `undefined`). Anything else — `NaN`,
* `0`, negative numbers — is treated as "no resize", which matches the GUI's `Off` row in the player dropdown.
*/
function resolveMaxLongEdge(options: VideoTranscodeOptions | undefined): number | undefined {
const raw = options?.maxLongEdgePx;
if (raw === undefined || !Number.isFinite(raw) || raw <= 0) return undefined;
return Math.floor(raw);
}
/**
* WebCodecs encode path. Pipeline:
*
* - 1. ffmpeg.wasm decodes the source to raw `yuv420p` planes. We keep ffmpeg as the decoder because WebCodecs'
* `VideoDecoder` doesn't speak the legacy MPEG-1 / VC-1 / WMV codecs typical BMS BGA ships in. 2. JS wraps each
* decoded frame in a `VideoFrame` and feeds it to `VideoEncoder` (H.264 / avc1 baseline). On most platforms this hits
* the GPU / ASIC video encoder, taking encode time from ~1× realtime down to 5–20× realtime. 3. Encoded chunks land
* in Mediabunny's in-memory MP4 writer; once the encoder flushes and the output is finalized, we hand its
* `BufferTarget` bytes back to the caller — same shape as the ffmpeg-encode path returns, so the downstream `<video>` blob plumbing is
* unchanged.
*
* Memory: decode and encode are interleaved in chunks rather than buffering the whole video as raw YUV. We can't get
* true stream-style concurrency (the wasm worker's `exec()` call blocks the worker from servicing `readFile` until
* decode completes, and there are no pipes in @ffmpeg/ffmpeg), but looping `ffmpeg.exec(['-ss', t, '-t', N, '-i',
* input, ...])` + `readFile` + `deleteFile` per chunk keeps MEMFS usage bounded by `MAX_CHUNK_BYTES` regardless of
* total duration.
*
* Trade-off: each chunk requires ffmpeg to seek+demux from the input again. Chunk size is sized to amortize this seek
* over many frames — too small and demux overhead dominates, too large and per-chunk MEMFS pressure blows the wasm
* heap. 256 MiB lands ~21 s of 512×512@30 (a typical BMS BGA) and ~3 s of 1920×1080@30 (HD outlier) per chunk; both
* have negligible seek overhead relative to the encode work.
*/
const MAX_CHUNK_BYTES = 256 * 1024 * 1024; // 256 MiB
const MIN_CHUNK_SECONDS = 5;
async function transcodeViaWebCodecs(
bytes: Uint8Array,
path: string,
options: VideoTranscodeOptions,
): Promise<Uint8Array | undefined> {
return withExclusiveFFmpeg(() => transcodeViaWebCodecsLocked(bytes, path, options));
}
async function transcodeViaWebCodecsLocked(
bytes: Uint8Array,
path: string,
options: VideoTranscodeOptions,
): Promise<Uint8Array | undefined> {
if (!isWebCodecsEncodeSupported()) return undefined;
const startedAt = performance.now();
const maxLongEdge = resolveMaxLongEdge(options);
log.info(
`WebCodecs transcode start: ${path} (${bytes.byteLength} bytes${maxLongEdge ? `, resize ≤ ${maxLongEdge}px` : ''})`,
);
const ffmpeg = await loadFFmpeg().catch((error) => {
log.warn('failed to load ffmpeg.wasm — WebCodecs transcode aborted', error);
return undefined;
});
if (!ffmpeg) return undefined;
const inputName = `bga-input${pickInputExtension(path)}`;
const chunkName = 'bga-chunk.yuv';
let probeListener: ((event: { type: string; message: string }) => void) | undefined;
const probeLines: string[] = [];
let encoder: VideoEncoder | undefined;
let output: Output<Mp4OutputFormat, BufferTarget> | undefined;
let muxing: Promise<void> = Promise.resolve();
try {
// Clone before writeFile — see the libx264 path for why. We need the caller's `bytes` to survive intact in case the
// WebCodecs path bails out and the ffmpeg-encode fallback is run with the same buffer.
await ffmpeg.writeFile(inputName, new Uint8Array(bytes));
// ffmpeg's stderr log carries the input geometry, frame rate, and total duration we need to drive the WebCodecs
// encoder + chunk loop. Hook a parallel listener that doesn't displace `loadFFmpeg`'s diagnostic listener.
probeListener = ({ type, message }) => {
if (type === 'stderr') {
probeLines.push(message);
}
};
ffmpeg.on('log', probeListener);
// ── Probe pass ────────────────────────────────────────── `-t 0.05` decodes ~1-2 frames purely so ffmpeg emits the
// `Input #0` / `Stream #0:0` / `Duration:` lines we parse below. `-f null -` discards the output entirely so this
// costs only ffmpeg's cold-start time (~50–100 ms once the wasm core is cached). Cheaper than running ffprobe
// separately, and the stderr format is identical.
const probeArgs: string[] = ['-y', '-i', inputName, '-t', '0.05'];
if (maxLongEdge) probeArgs.push('-vf', buildScaleFilterArg(maxLongEdge));
probeArgs.push('-f', 'null', '-');
const probeExit = await ffmpeg.exec(probeArgs);
if (probeExit !== 0) {
log.warn(`ffmpeg probe (WebCodecs path) exited with code ${probeExit} for ${path}`);
return undefined;
}
const probe = parseFFmpegProbe(probeLines);
if (!probe) {
log.warn(`WebCodecs path could not parse ffmpeg probe; falling back: ${path}`);
return undefined;
}
const { width, height, frameRate, durationSec, inputFormat } = probe;
if (isRawVideoStreamFormat(inputFormat)) {
log.info(
`WebCodecs path skipped for a bare ${inputFormat} stream (no reliable duration / seek); falling back: ${path}`,
);
return undefined;
}
if (!durationSec || durationSec <= 0) {
log.warn(`WebCodecs path could not determine duration; falling back: ${path}`);
return undefined;
}
// 12 bits per pixel (yuv420p): 1.5 bytes per pixel.
const bytesPerFrame = (width * height * 3) >> 1;
if (bytesPerFrame <= 0) return undefined;
// ── Encoder + muxer setup ─────────────────────────────── H.264 baseline @ Level 5.0 covers up to 1920×1080@30.
// The browser's `isConfigSupported` will reject anything beyond the platform encoder's reach; we treat that as a
// fall-through to the ffmpeg-encode path rather than a hard failure.
//
// `hardwareAcceleration: 'prefer-hardware'` asks for the platform encoder (VideoToolbox on macOS, MediaFoundation
// on Windows, MediaCodec on Android, …) but accepts the software fallback when none is available. We log the
// negotiated mode for visibility.
const encoderConfig: VideoEncoderConfig = {
codec: 'avc1.42E01E',
width,
height,
bitrate: estimateBGATranscodeBitrate(width, height, frameRate, options?.quality),
framerate: frameRate,
hardwareAcceleration: 'prefer-hardware',
avc: { format: 'avc' },
};
const support = await VideoEncoder.isConfigSupported(encoderConfig);
if (!support.supported) {
log.warn(`WebCodecs encoder rejected config for ${path}; falling back`, support);
return undefined;
}
const negotiated = support.config ?? encoderConfig;
const accelerationLabel = negotiated.hardwareAcceleration ?? 'no-preference';
log.info(`WebCodecs encoder negotiated: ${negotiated.codec} (${accelerationLabel})`);
// Loaded on demand so the muxer stays out of the main bundle; most BGA never reach this path.
const mediabunny = await import('mediabunny');
// 'in-memory' fastStart keeps everything buffered until `finalize()` writes a moov-at-front MP4 — same as libx264's
// `+faststart`.
output = new mediabunny.Output({
format: new mediabunny.Mp4OutputFormat({ fastStart: 'in-memory' }),
target: new mediabunny.BufferTarget(),
});
const videoSource = new mediabunny.EncodedVideoPacketSource('avc');
output.addVideoTrack(videoSource, { frameRate });
await output.start();
// The encoder's `output` callback is synchronous while `add` is async: chain the adds so packets reach the muxer in
// decode order, and keep the first failure to rethrow once the encoder has flushed.
encoder = new VideoEncoder({
output: (chunk, metadata) => {
const packet = mediabunny.EncodedPacket.fromEncodedChunk(chunk);
muxing = muxing.then(() => videoSource.add(packet, metadata));
},
error: (error) => {
log.warn(`WebCodecs encoder error for ${path}`, error);
},
});
encoder.configure(negotiated);
// ── Chunk loop ────────────────────────────────────────── Compute how many seconds fit in the per-chunk byte
// budget. We always round down to the nearest second so ffmpeg's `-t` argument cleanly matches a frame boundary,
// and clamp to `MIN_CHUNK_SECONDS` so seek + demux setup doesn't dominate the wall-clock cost on enormous inputs.
const bytesPerSecond = bytesPerFrame * frameRate;
const chunkSeconds = Math.max(MIN_CHUNK_SECONDS, Math.floor(MAX_CHUNK_BYTES / bytesPerSecond));
const keyframeInterval = Math.max(1, Math.round(frameRate * 2));
const microsPerFrame = Math.max(1, Math.round(1_000_000 / frameRate));
let frameIndex = 0;
let chunkCount = 0;
// The reported duration only sizes the first guess: a container can understate it (a header written before the
// encode finished), so chunks keep coming until ffmpeg returns an empty one, capped at twice the reported length
// plus a minute so a demuxer that never runs dry can't loop forever.
const lastStartSec = durationSec * 2 + 60;
for (let chunkStartSec = 0; chunkStartSec < lastStartSec; chunkStartSec += chunkSeconds) {
const thisChunkSec = chunkSeconds;
// `-ss BEFORE -i` does input-level seek and is accurate by default in modern ffmpeg (decode-and-discard between
// the prior keyframe and the seek target). For the first chunk we omit `-ss` entirely — some demuxers re-parse
// headers when a `-ss 0` is present which adds latency for no benefit.
const chunkArgs: string[] = ['-y'];
if (chunkStartSec > 0) chunkArgs.push('-ss', chunkStartSec.toFixed(3));
chunkArgs.push('-t', thisChunkSec.toFixed(3), '-i', inputName);
if (maxLongEdge) chunkArgs.push('-vf', buildScaleFilterArg(maxLongEdge));
chunkArgs.push('-c:v', 'rawvideo', '-pix_fmt', 'yuv420p', '-f', 'rawvideo', '-an', '-sn', '-dn', chunkName);
const chunkExit = await ffmpeg.exec(chunkArgs);
// Past the reported end, a demuxer may fail the seek rather than return nothing: that is the end too.
if (chunkExit !== 0 && chunkStartSec >= durationSec) break;
if (chunkExit !== 0) {
log.warn(
`ffmpeg chunk decode (WebCodecs path) exited with code ${chunkExit} at ${chunkStartSec.toFixed(2)}s for ${path}`,
);
return undefined;
}
const chunkRead = await ffmpeg.readFile(chunkName);
const chunkBytes = chunkRead instanceof Uint8Array ? chunkRead : new TextEncoder().encode(chunkRead);
// Always delete BEFORE iterating frames so MEMFS pressure peaks at one chunk's worth of YUV. The Uint8Array view
// we just took stays valid because @ffmpeg/ffmpeg copied bytes out of MEMFS into the JS heap during readFile.
try {
await ffmpeg.deleteFile(chunkName);
} catch {
// ignore
}
if (chunkBytes.byteLength === 0) {
// ffmpeg's `-t` with imprecise duration sometimes overshoots the input end and produces an empty chunk. Treat
// as EOF and stop.
break;
}
if (chunkBytes.byteLength % bytesPerFrame !== 0) {
log.warn(
`WebCodecs path: chunk byte length ${chunkBytes.byteLength} not divisible by ${bytesPerFrame} (frame size); falling back: ${path}`,
);
return undefined;
}
const framesInChunk = chunkBytes.byteLength / bytesPerFrame;
for (let i = 0; i < framesInChunk; i++) {
// Slice (not copy) the raw frame view — WebCodecs takes the buffer reference and the encoder consumes it before
// we move to the next frame.
const frameBytes = chunkBytes.subarray(i * bytesPerFrame, (i + 1) * bytesPerFrame);
const frame = new VideoFrame(frameBytes, {
format: 'I420',
codedWidth: width,
codedHeight: height,
timestamp: frameIndex * microsPerFrame,
duration: microsPerFrame,
});
encoder.encode(frame, { keyFrame: frameIndex % keyframeInterval === 0 });
frame.close();
// Backpressure: yield when the encoder queue grows past a few dozen frames so the GPU encoder can drain.
// Without this, on a fast wasm-decode + slow encoder pairing we'd pile up hundreds of frames in memory before
// any get muxed.
if (encoder.encodeQueueSize > 32) {
await waitForEncoderDrain(encoder, 4);
}
frameIndex++;
}
chunkCount++;
options.onProgress?.(Math.min(0.95, (0.95 * frameIndex) / (frameRate * durationSec)));
}
await encoder.flush();
encoder.close();
encoder = undefined;
await muxing;
await output.finalize();
const muxed = output.target.buffer;
output = undefined;
if (!muxed) return undefined;
const outBytes = new Uint8Array(muxed);
const elapsed = ((performance.now() - startedAt) / 1000).toFixed(2);
log.info(
`WebCodecs transcode ok: ${path} → ${outBytes.byteLength} bytes (${elapsed}s, ${frameIndex} frames @ ${width}×${height}, ${chunkCount} chunks of ≤${chunkSeconds}s)`,
);
return outBytes;
} catch (error) {
log.warn(`WebCodecs transcode threw for ${path}`, error);
return undefined;
} finally {
if (probeListener) {
try {
ffmpeg.off('log', probeListener);
} catch {
// ignore
}
}
if (encoder) {
try {
encoder.close();
} catch {
// ignore — encoder.close() throws if already closed
}
}
// An early return leaves a failed add unobserved; mark it handled (the transcode already reports undefined).
muxing.catch(() => {});
if (output) {
try {
await output.cancel();
} catch {
// ignore
}
}
try {
await ffmpeg.deleteFile(inputName);
} catch {
// ignore
}
try {
await ffmpeg.deleteFile(chunkName);
} catch {
// ignore
}
}
}
/**
* Pulls input geometry / frame rate / duration out of ffmpeg's stderr. The lines we want look like:
*
* `Duration: 00:02:02.00, start: 0.398189, bitrate: 5076 kb/s` `Stream #0:0(jpn): Video: vc1 ..., yuv420p, 1080x1080
* [...], 30 tbr, 1k tbn`
*
* `tbr` (frame rate) and `WxH` come from the `Stream` line; `Duration:` carries the total length we use to size the
* chunk loop. The rest of each line (codec, profile, SAR / DAR) is informative but doesn't affect the WebCodecs encoder
* configuration.
*
* Returns `undefined` if any of geometry / frame rate / duration could not be parsed. The WebCodecs path bails out in
* that case rather than guessing.
*/
export function parseFFmpegProbe(
lines: ReadonlyArray<string>,
): { width: number; height: number; frameRate: number; durationSec: number; inputFormat?: string } | undefined {
let width: number | undefined;
let height: number | undefined;
let frameRate: number | undefined;
let durationSec: number | undefined;
let inputFormat: string | undefined;
for (const line of lines) {
if (inputFormat === undefined) {
const input = line.match(/Input #0, ([\w,]+), from/u);
Eif (input) inputFormat = input[1];
}
if (durationSec === undefined) {
const duration = line.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/u);
if (duration) {
const hours = Number.parseInt(duration[1]!, 10);
const minutes = Number.parseInt(duration[2]!, 10);
const seconds = Number.parseFloat(duration[3]!);
Eif (Number.isFinite(hours) && Number.isFinite(minutes) && Number.isFinite(seconds)) {
durationSec = hours * 3600 + minutes * 60 + seconds;
}
}
}
if (!line.includes('Video:')) continue;
const dim = line.match(/(\d{2,5})x(\d{2,5})/u);
Eif (dim) {
width = Number.parseInt(dim[1]!, 10);
height = Number.parseInt(dim[2]!, 10);
}
const fps = line.match(/(\d+(?:\.\d+)?)\s*(tbr|fps)/u);
Eif (fps) {
const value = Number.parseFloat(fps[1]!);
Eif (Number.isFinite(value) && value > 0) {
frameRate = value;
}
}
}
if (!width || !height || !frameRate || !durationSec) return undefined;
return { width, height, frameRate, durationSec, ...(inputFormat !== undefined ? { inputFormat } : {}) };
}
/**
* ffmpeg's names for bare video elementary streams — a codec's bitstream with no container around it (`.mpg` files
* that are just an MPEG-1 sequence, raw H.264 / HEVC / MPEG-4 Part 2 / VC-1). They carry no timestamps or index:
* ffmpeg guesses their duration from a bitrate field and their frame rate from heuristics, and a seek lands wherever
* the bitrate guess says. A BMS BGA like that can report 1.2 s for a 113 s clip.
*/
const RAW_VIDEO_STREAM_FORMATS = new Set([
'mpegvideo',
'mpeg1video',
'mpeg2video',
'h264',
'hevc',
'm4v',
'vc1',
'cavsvideo',
]);
/**
* Whether ffmpeg read the input as a bare elementary stream (see {@link RAW_VIDEO_STREAM_FORMATS}). The chunked
* WebCodecs path depends on the reported duration, frame rate and on seeking, so such inputs take the single-pass
* libx264 transcode instead, which decodes every frame in order with the stream's own timing.
*/
export function isRawVideoStreamFormat(inputFormat: string | undefined): boolean {
return inputFormat !== undefined && inputFormat.split(',').some((name) => RAW_VIDEO_STREAM_FORMATS.has(name));
}
/**
* Yields control to the event loop until the encoder's queue shrinks under `target`. Without this throttle, a fast wasm
* decode loop can pile thousands of `VideoFrame`s into the encoder's queue and exhaust GPU video memory.
*/
async function waitForEncoderDrain(encoder: VideoEncoder, target: number): Promise<void> {
while (encoder.encodeQueueSize > target) {
await new Promise<void>((resolve) => {
setTimeout(resolve, 4);
});
}
}
/**
* Lazy-loaded singleton — the `FFmpeg` class boots a Worker that downloads + instantiates the ~30 MB `@ffmpeg/core`
* wasm. We keep the loaded instance around between calls so subsequent BGA videos transcode immediately instead of
* paying the cold- start hit on every chart change.
*/
let cachedFFmpeg: FFmpegInstance | undefined;
let cachedFFmpegPromise: Promise<FFmpegInstance> | undefined;
async function loadFFmpeg(): Promise<FFmpegInstance> {
if (cachedFFmpeg) return cachedFFmpeg;
if (cachedFFmpegPromise) return cachedFFmpegPromise;
cachedFFmpegPromise = (async () => {
// Lazy ESM imports keep the multi-megabyte wasm + worker bundle out of the initial page load — the user only pays
// the download cost when they actually pick a chart with an unsupported BGA video.
const [{ FFmpeg }, { toBlobURL }] = await Promise.all([import('@ffmpeg/ffmpeg'), import('@ffmpeg/util')]);
// We target the ESM entry from the host's `/ffmpeg-core/` static path. @ffmpeg/ffmpeg creates its outer worker as
// `type: "module"`, where `importScripts` is unavailable: the worker's load handler catches that and falls back to
// `await import(coreURL)`. Dynamic-importing the UMD bundle yields `{ default: undefined }` (its IIFE assigns to a
// module-local `var createFFmpegCore` rather than to `module.exports` in a way the dynamic import can see), which
// trips `ERROR_IMPORT_FAILURE`. The ESM bundle exports `createFFmpegCore` as `default` properly.
//
// We deliberately use `@ffmpeg/core` (single-threaded) over `@ffmpeg/core-mt`. The multi-threaded core 0.12.x has a
// long-standing wasm bug where libx264's indirect calls crash every pthread worker with `RuntimeError: function
// signature mismatch`, after which `ffmpeg.exec()` aborts with a non-Error throw that detonates inside the core's
// own catch with `Cannot read properties of undefined (reading 'startsWith')`. Single-threaded encoding takes ~tens
// of seconds for a typical BMS BGA but actually completes.
//
// The player's Vite config installs a custom plugin (`be-music:ffmpeg-core`) that serves the ESM core
// (`ffmpeg-core.js` / `.wasm`) at this stable URL prefix in dev and emits them as build assets in production.
const coreURL = FFMPEG_CORE_URL;
const wasmURL = FFMPEG_WASM_URL;
const ffmpeg = new FFmpeg();
// `toBlobURL` re-fetches the core JS / WASM URLs into blob URLs so the spawned module worker's `await
// import(coreURL)` succeeds even when the page sits behind a different origin (the worker's same-origin policy
// otherwise blocks the cross-origin file URLs Vite hands out under HMR).
const [coreBlobURL, wasmBlobURL] = await Promise.all([
toBlobURL(coreURL, 'text/javascript'),
toBlobURL(wasmURL, 'application/wasm'),
]);
// Surface ffmpeg's own log so we can see *what* the wasm side reports — the core's `exec()` wrapper hides errors
// without a JS-style `.message` (it only re-throws when the message starts with `"Aborted"` and self-detonates with
// a TypeError on `"unwind"` strings / OOMs), so the stderr log is often our only signal when something goes wrong.
ffmpeg.on('log', ({ type, message }: { type: string; message: string }) => {
log.debug(`ffmpeg ${type}: ${message}`);
});
await ffmpeg.load({ coreURL: coreBlobURL, wasmURL: wasmBlobURL });
cachedFFmpeg = ffmpeg as FFmpegInstance;
return cachedFFmpeg;
})().catch((error) => {
// Reset the promise cache on failure so a transient network blip doesn't permanently disable the fallback.
cachedFFmpegPromise = undefined;
throw error;
});
return cachedFFmpegPromise;
}
interface FFmpegInstance {
writeFile(path: string, data: Uint8Array): Promise<boolean>;
readFile(path: string): Promise<Uint8Array | string>;
exec(args: string[]): Promise<number>;
deleteFile(path: string): Promise<boolean>;
/**
* `@ffmpeg/ffmpeg` exposes an EventEmitter-style `on` / `off` for the underlying worker's `log` events. The WebCodecs
* encode path uses this to capture stderr lines mid-decode (input geometry, frame rate) without displacing the
* diagnostic listener `loadFFmpeg` already attaches.
*/
on(event: 'log', listener: (event: { type: string; message: string }) => void): void;
off(event: 'log', listener: (event: { type: string; message: string }) => void): void;
on(event: 'progress', listener: (event: { progress: number; time: number }) => void): void;
off(event: 'progress', listener: (event: { progress: number; time: number }) => void): void;
}
function stripVideoExtension(path: string): string {
const dotIndex = path.lastIndexOf('.');
if (dotIndex < 0) return path;
return path.slice(0, dotIndex);
}
function releaseVideoElement(video: HTMLVideoElement): void {
try {
video.pause();
video.removeAttribute('src');
video.load();
} catch {
// Defensive: detached / unsupported media elements can throw on load().
}
}
function waitForVideoMetadata(video: HTMLVideoElement, timeoutMs: number): Promise<void> {
return new Promise((resolve, reject) => {
const cleanup = (): void => {
video.removeEventListener('loadedmetadata', onLoaded);
video.removeEventListener('error', onError);
window.clearTimeout(timeoutHandle);
};
const onLoaded = (): void => {
cleanup();
resolve();
};
const onError = (): void => {
cleanup();
reject(new Error('video error'));
};
const timeoutHandle = window.setTimeout(() => {
cleanup();
reject(new Error('video metadata timeout'));
}, timeoutMs);
video.addEventListener('loadedmetadata', onLoaded);
video.addEventListener('error', onError);
});
}
/**
* Resolve once the `<video>` element has its first frame decoded — i.e. `readyState >=
* HAVE_CURRENT_DATA` (2). The renderer needs this BEFORE handing the element to a Pixi
* `VideoSource`: WebGPU's `copyExternalImageToTexture` rejects videos with no decoded
* frame ("back resource") and the WebGL path silently uploads a blank texture, both of
* which break the first-paint of any BGA video.
*
* Resolves immediately when the readyState is already past the threshold (= the browser
* decoded frame 0 during `loadedmetadata`'s autoplay-warmup, common on `preload="auto"`
* + small clips). Otherwise listens for `loadeddata`. Rejects on `error` or after
* `timeoutMs`.
*/
function waitForVideoFrameData(video: HTMLVideoElement, timeoutMs: number): Promise<void> {
if (video.readyState >= 2 /* HAVE_CURRENT_DATA */) return Promise.resolve();
return new Promise((resolve, reject) => {
const cleanup = (): void => {
video.removeEventListener('loadeddata', onLoaded);
video.removeEventListener('error', onError);
window.clearTimeout(timeoutHandle);
};
const onLoaded = (): void => {
cleanup();
resolve();
};
const onError = (): void => {
cleanup();
reject(new Error('video error'));
};
const timeoutHandle = window.setTimeout(() => {
cleanup();
reject(new Error('video frame data timeout'));
}, timeoutMs);
video.addEventListener('loadeddata', onLoaded);
video.addEventListener('error', onError);
});
}
function guessVideoMIMEType(path: string): string {
const lower = path.toLowerCase();
if (lower.endsWith('.mp4') || lower.endsWith('.m4v')) return 'video/mp4';
if (lower.endsWith('.webm')) return 'video/webm';
if (lower.endsWith('.ogv') || lower.endsWith('.ogg')) return 'video/ogg';
if (lower.endsWith('.mov')) return 'video/quicktime';
// Older BMS archives sometimes ship `.mpg` / `.mpeg` / `.avi` / `.wmv` — modern browsers won't decode those so the
// video element will fire `error` and `loadVideoTexture` returns `undefined`. We still tag a sensible MIME
// type so the rare browser-supported codec works.
if (lower.endsWith('.mpg') || lower.endsWith('.mpeg')) return 'video/mpeg';
return 'video/mp4';
}
/** RGBA8 pixels produced by a registered {@link ImageDecoder}. */
export interface DecodedImageData {
rgba: Uint8ClampedArray;
width: number;
height: number;
}
/**
* Synchronous decoder for an image format browsers can't decode natively. Returns `undefined` for unsupported variants
* so {@link loadTextureFromBytes} can fall through to the regular blob path.
*/
export type ImageDecoder = (bytes: Uint8Array) => DecodedImageData | undefined;
/** Lowercased file extension (with the leading dot) → decoder. Populated by skin families at module load. */
const imageDecoders = new Map<string, ImageDecoder>();
/**
* Registers `decoder` for asset paths ending in `extension` (e.g. `'.dds'`, case-insensitive). Lets a skin family plug
* a format it owns into the shared loader without this neutral module importing that family. A later registration for
* the same extension replaces the earlier one.
*/
export function registerImageDecoder(extension: string, decoder: ImageDecoder): void {
imageDecoders.set(extension.toLowerCase(), decoder);
}
function resolveImageDecoder(lowerPath: string): ImageDecoder | undefined {
for (const [extension, decoder] of imageDecoders) {
if (lowerPath.endsWith(extension)) return decoder;
}
return undefined;
}
export interface LoadTextureOptions {
/** EXBMP's alpha-aware transparent-color key, applied before Canvas premultiplication where raw pixels are available. */
bmsColorKey?: BmsARGB;
/** SWBGA transparent color compares decoded RGBA, including inserted opaque alpha. */
swBGAColorKey?: BmsARGB;
/** Skin-declared `#TRANSCOLOR` chroma key (rare on BGA assets, common on UI sprites). */
transparentColor?: { r: number; g: number; b: number };
/**
* Treat pure-black pixels as transparent. Mirrors the BMS BGA "layer" convention
* (`packages/player-terminal/src/bga-frame.ts`'s `isOpaquePixel` for `mode === 'layer'`): the foreground BGA layer is
* composited over the base with `(0, 0, 0)` acting as a chroma-key. Only enabled for layer-track decodes — base / POOR retain their black pixels because
* they're the bottommost BGA layer (nothing visible behind them).
*/
keyOutBlack?: boolean;
}
/**
* Loads any skin / BGA image asset (TGA, PNG, BMP, JPG, registered formats, …) into a PixiJS `Texture`. Branches by file extension because TGA
* isn't decoded by `createImageBitmap` in any browser.
*
* The legacy positional `transparentColor` argument is supported for backward compatibility — pass an
* `LoadTextureOptions` object for the full feature set (`keyOutBlack`, future flags).
*/
export async function loadTextureFromBytes(
path: string,
bytes: Uint8Array,
transparentColorOrOptions?: { r: number; g: number; b: number } | LoadTextureOptions,
): Promise<Texture | undefined> {
const options = normalizeLoadTextureOptions(transparentColorOrOptions);
const lower = path.toLowerCase();
if (
(options.bmsColorKey || options.swBGAColorKey) &&
bytes.length >= 8 &&
bytes[0] === 0x89 &&
bytes[1] === 0x50 &&
bytes[2] === 0x4e &&
bytes[3] === 0x47
) {
try {
const { decodePNGToRGBA8 } = await import('@be-music/shared-utils/png');
const image = decodePNGToRGBA8(bytes);
applyBGAColorKeys(image.data, options, image.hasAlphaChannel);
return loadTextureFromImageData(
new Uint8ClampedArray(image.data.buffer, image.data.byteOffset, image.data.byteLength),
image.width,
image.height,
path,
{ ...options, bmsColorKey: undefined, swBGAColorKey: undefined, keyOutBlack: false },
);
} catch {
return undefined;
}
}
const hasAlphaChannel = sourceHasAlphaChannel(bytes, lower);
if (lower.endsWith('.tga')) {
return decodeTGATexture(bytes, options, path);
}
const decoder = resolveImageDecoder(lower);
if (decoder) {
// Formats browsers can't decode natively (e.g. DDS, registered by the LR2 family) go through a registered
// in-tree decoder. It yields an RGBA buffer that we wrap in `ImageData` and feed `createImageBitmap`, so the rest
// of the texture pipeline (chroma key, nearest sampling, blob-url tracking) stays uniform with the PNG / BMP / JPG
// branches. A decoder returning `undefined` (unsupported variant) falls through to the blob path below, which then
// fails gracefully via `createImageBitmap`'s exception handling.
const decoded = decoder(bytes);
if (decoded) {
return loadTextureFromImageData(decoded.rgba, decoded.width, decoded.height, path, options, hasAlphaChannel);
}
}
Iif (lower.endsWith('.avi')) {
// Authored themes occasionally reference `.avi` for clear / fail lamp animations (LITONE4 ships them under
// `Play/parts/movie/`). The browser's `HTMLVideoElement` can play some AVI containers but the legacy codec mix
// (MS-MPEG4 / Cinepak / etc.) used by these themes isn't decodable in any modern browser without the ffmpeg
// transcode pipeline that the BGA loader uses — and that pipeline is built for chart-side BGA, not skin chrome.
// Returning `undefined` here makes the skin renderer skip the element, which is the desired behaviour for v1
// LITONE4 support (the lamp animations are decorative; the surrounding chrome paints fine without them).
return undefined;
}
// `bytes` is already a `Uint8Array`; `new Blob([bytes])` is sufficient. Wrapping it in another `new Uint8Array(...)`
// forces an extra copy of the entire byte buffer (the `Uint8Array(buffer)` ctor copies when the source is a typed
// array view) before the Blob makes its own internal copy — doubling the peak memory for skin / BGA bitmaps. See
// `tryLoadVideoTextureFromBytes` for the matching `ArrayBuffer` cast rationale.
const blob = new Blob([bytes as Uint8Array<ArrayBuffer>]);
return loadTextureFromBlob(blob, path, options, hasAlphaChannel);
}
/**
* Wraps a decoded RGBA8 buffer in a Pixi `Texture`. Mirrors {@link loadTextureFromBlob}'s post-decode behaviour
* (chroma key, nearest sampling, transparent-color handling) so decoder-sourced (e.g. DDS) textures look identical to
* PNG/BMP counterparts at the same authored size.
*
* `new ImageData(...)` allocates its own buffer copy when given a `Uint8ClampedArray`, so we avoid the
* `createImageBitmap(blob)` round-trip altogether — decoded bytes never become a blob, only a typed-array view.
*/
async function loadTextureFromImageData(
rgba: Uint8ClampedArray,
width: number,
height: number,
label: string,
options: LoadTextureOptions,
hasAlphaChannel = true,
): Promise<Texture | undefined> {
try {
// `new ImageData(rgba, width, height)` rejects a `Uint8ClampedArray` whose backing buffer is typed as
// `ArrayBufferLike` (the DOM lib only narrows to `ArrayBuffer`-backed views). Copy into a fresh buffer that's
// unambiguously typed as a regular `ArrayBuffer` — the bytes themselves are the same, just the type narrows.
const ownedBuffer = new ArrayBuffer(rgba.byteLength);
const pixels = new Uint8ClampedArray(ownedBuffer);
pixels.set(rgba);
if (options.bmsColorKey || options.swBGAColorKey) {
if (!hasAlphaChannel) for (let offset = 3; offset < pixels.length; offset += 4) pixels[offset] = 255;
applyBGAColorKeys(pixels, options, hasAlphaChannel);
}
const imageData = new ImageData(new Uint8ClampedArray(ownedBuffer), width, height);
const imageBitmap = await createImageBitmap(imageData);
let finalBitmap = imageBitmap;
Iif (options.transparentColor || (options.keyOutBlack && !options.bmsColorKey && !options.swBGAColorKey)) {
const keyedBitmap = await applyChromaKeyToBitmap(
imageBitmap,
options.bmsColorKey || options.swBGAColorKey
? { ...options, bmsColorKey: undefined, swBGAColorKey: undefined, keyOutBlack: false }
: options,
);
if (keyedBitmap) {
imageBitmap.close();
finalBitmap = keyedBitmap;
}
}
let texture: Texture;
try {
texture = Texture.from(finalBitmap);
} catch (error) {
finalBitmap.close();
throw error;
}
// Match the blob-path's pixel-art policy: nearest-neighbor sampling so the upscaled decoded chrome stays crisp
// (LR2 themes are typically authored at 1280×720 design space and scaled to the canvas).
texture.source.scaleMode = 'nearest';
texture.label = label;
texture.source.label = label;
return texture;
} catch (error) {
log.warn('decoded texture upload failed', { path: label, error });
return undefined;
}
}
/**
* Decodes an image asset (PNG, BMP, JPG, TGA, registered formats, …) into an `ImageBitmap`, for consumers that draw
* with the canvas APIs rather than Pixi (Be-Music Skins' song images). No chroma key is applied. `undefined` when the
* bytes don't decode; the caller owns the bitmap and `close()`s it when done.
*/
export async function loadImageBitmapFromBytes(path: string, bytes: Uint8Array): Promise<ImageBitmap | undefined> {
const lower = path.toLowerCase();
try {
Iif (lower.endsWith('.tga')) {
const imageData = decodeTGAImageData(bytes);
return imageData ? await createImageBitmap(imageData) : undefined;
}
const decoded = resolveImageDecoder(lower)?.(bytes);
Iif (decoded) {
// Copy into an `ArrayBuffer`-backed view: `ImageData` rejects views typed over `ArrayBufferLike`.
const pixels = new Uint8ClampedArray(new ArrayBuffer(decoded.rgba.byteLength));
pixels.set(decoded.rgba);
return await createImageBitmap(new ImageData(pixels, decoded.width, decoded.height));
}
return await createImageBitmap(new Blob([bytes as Uint8Array<ArrayBuffer>]));
} catch {
return undefined;
}
}
function normalizeLoadTextureOptions(
input: { r: number; g: number; b: number } | LoadTextureOptions | undefined,
): LoadTextureOptions {
if (!input) {
return {};
}
// The legacy positional `transparentColor` shape has flat `r/g/b` numbers; the new options shape has a nested
// `transparentColor` / `keyOutBlack`. Discriminate on `r` so call sites that still pass the bare color triple keep
// working without a typed cast.
Iif (typeof (input as { r?: unknown }).r === 'number') {
return { transparentColor: input as { r: number; g: number; b: number } };
}
return input as LoadTextureOptions;
}
async function loadTextureFromBlob(
blob: Blob,
label?: string,
options: LoadTextureOptions = {},
hasAlphaChannel = true,
): Promise<Texture | undefined> {
try {
const imageBitmap = await createImageBitmap(blob);
let finalBitmap = imageBitmap;
Eif (options.transparentColor || options.keyOutBlack || options.bmsColorKey || options.swBGAColorKey) {
const keyedBitmap = await applyChromaKeyToBitmap(imageBitmap, options, hasAlphaChannel);
Eif (keyedBitmap) {
imageBitmap.close();
finalBitmap = keyedBitmap;
}
}
let texture: Texture;
try {
texture = Texture.from(finalBitmap);
} catch (error) {
finalBitmap.close();
throw error;
}
// Force nearest-neighbor sampling on every loaded texture. LR2 skin / BGA assets are pixel-art; bilinear filtering
// blurs them when the design space is scaled up to the canvas. Mirrors the user-requested "disable all
// interpolation / AA" policy.
texture.source.scaleMode = 'nearest';
Eif (label) {
texture.label = label;
texture.source.label = label;
}
return texture;
} catch {
return undefined;
}
}
async function applyChromaKeyToBitmap(
imageBitmap: ImageBitmap,
options: LoadTextureOptions,
hasAlphaChannel = true,
): Promise<ImageBitmap | undefined> {
const canvas = document.createElement('canvas');
canvas.width = imageBitmap.width;
canvas.height = imageBitmap.height;
const context = canvas.getContext('2d');
Iif (!context) {
return undefined;
}
context.drawImage(imageBitmap, 0, 0);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const { data } = imageData;
applyBGAColorKeys(data, options, hasAlphaChannel);
const transparent = options.transparentColor;
const keyOutBlack =
options.keyOutBlack === true && options.bmsColorKey === undefined && options.swBGAColorKey === undefined;
for (let index = 0; index < data.length; index += 4) {
const r = data[index] ?? 0;
const g = data[index + 1] ?? 0;
const b = data[index + 2] ?? 0;
Iif (transparent && r === transparent.r && g === transparent.g && b === transparent.b) {
data[index + 3] = 0;
continue;
}
Iif (keyOutBlack && r === 0 && g === 0 && b === 0) {
data[index + 3] = 0;
}
}
context.putImageData(imageData, 0, 0);
return createImageBitmap(canvas);
}
async function decodeTGATexture(
bytes: Uint8Array,
options: LoadTextureOptions = {},
label?: string,
): Promise<Texture | undefined> {
const imageData = decodeTGAImageData(bytes, options);
Iif (!imageData) {
return undefined;
}
return loadTextureFromImageData(imageData.data, imageData.width, imageData.height, label ?? 'TGA', {});
}
/**
* Decodes an uncompressed or RLE true-colour / grayscale TGA into RGBA pixels, applying the chroma keys in `options`.
* `undefined` for truncated files and variants it doesn't handle (colour-mapped, 15/16-bit).
*/
function decodeTGAImageData(bytes: Uint8Array, options: LoadTextureOptions = {}): ImageData | undefined {
const transparentColor = options.transparentColor;
const keyOutBlack =
options.keyOutBlack === true && options.bmsColorKey === undefined && options.swBGAColorKey === undefined;
Iif (bytes.length < 18) {
return undefined;
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const idLength = bytes[0] ?? 0;
const colorMapType = bytes[1] ?? 0;
const imageType = bytes[2] ?? 0;
const width = view.getUint16(12, true);
const height = view.getUint16(14, true);
const bitsPerPixel = bytes[16] ?? 0;
const descriptor = bytes[17] ?? 0;
const bytesPerPixel = bitsPerPixel / 8;
const isRLE = imageType === 10 || imageType === 11;
const isTrueColor = imageType === 2 || imageType === 10;
const isGrayscale = imageType === 3 || imageType === 11;
Iif (
colorMapType !== 0 ||
width <= 0 ||
height <= 0 ||
!Number.isInteger(bytesPerPixel) ||
!((isTrueColor && (bitsPerPixel === 24 || bitsPerPixel === 32)) || (isGrayscale && bitsPerPixel === 8))
) {
return undefined;
}
const pixelCount = width * height;
const imageData = new ImageData(width, height);
const topOrigin = (descriptor & 0x20) !== 0;
const rightOrigin = (descriptor & 0x10) !== 0;
let sourceOffset = 18 + idLength;
let written = 0;
const writePixel = (source: number): boolean => {
Iif (source + bytesPerPixel > bytes.length || written >= pixelCount) {
return false;
}
const sourceX = written % width;
const sourceY = Math.floor(written / width);
const x = rightOrigin ? width - 1 - sourceX : sourceX;
const y = topOrigin ? sourceY : height - 1 - sourceY;
const target = (y * width + x) * 4;
Iif (isGrayscale) {
const value = bytes[source] ?? 0;
imageData.data[target] = value;
imageData.data[target + 1] = value;
imageData.data[target + 2] = value;
imageData.data[target + 3] = 255;
} else {
const r = bytes[source + 2] ?? 0;
const g = bytes[source + 1] ?? 0;
const b = bytes[source] ?? 0;
let a =
bitsPerPixel === 32 && (!(options.bmsColorKey || options.swBGAColorKey) || (descriptor & 15) !== 0)
? (bytes[source + 3] ?? 255)
: 255;
Iif (transparentColor && r === transparentColor.r && g === transparentColor.g && b === transparentColor.b) {
a = 0;
} else Iif (keyOutBlack && r === 0 && g === 0 && b === 0) {
a = 0;
}
imageData.data[target] = r;
imageData.data[target + 1] = g;
imageData.data[target + 2] = b;
imageData.data[target + 3] = a;
}
written += 1;
return true;
};
Iif (isRLE) {
while (written < pixelCount && sourceOffset < bytes.length) {
const packet = bytes[sourceOffset++] ?? 0;
const count = (packet & 0x7f) + 1;
if ((packet & 0x80) !== 0) {
const pixelOffset = sourceOffset;
sourceOffset += bytesPerPixel;
for (let index = 0; index < count; index += 1) {
if (!writePixel(pixelOffset)) {
return undefined;
}
}
} else {
for (let index = 0; index < count; index += 1) {
if (!writePixel(sourceOffset)) {
return undefined;
}
sourceOffset += bytesPerPixel;
}
}
}
} else {
while (written < pixelCount) {
Iif (!writePixel(sourceOffset)) {
return undefined;
}
sourceOffset += bytesPerPixel;
}
}
applyBGAColorKeys(imageData.data, options, bitsPerPixel === 32 && (descriptor & 15) !== 0);
return imageData;
}
/** Known container metadata; custom RGBA decoders otherwise expose an alpha-bearing pixel buffer. */
function sourceHasAlphaChannel(bytes: Uint8Array, path: string): boolean {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
if (bytes[0] === 0xff && bytes[1] === 0xd8) return false;
if (bytes.length >= 30 && bytes[0] === 0x42 && bytes[1] === 0x4d) {
return (
view.getUint16(28, true) === 32 &&
view.getUint32(14, true) >= 56 &&
bytes.length >= 70 &&
view.getUint32(66, true) !== 0
);
}
if (bytes.length >= 128 && view.getUint32(0, true) === 0x20534444)
return (view.getUint32(80, true) & 1) !== 0 && view.getUint32(104, true) !== 0;
if (path.endsWith('.tga') && bytes.length >= 18) return bytes[16] === 32 && (bytes[17]! & 15) !== 0;
return true;
}
function applyBGAColorKeys(data: Uint8Array | Uint8ClampedArray, options: LoadTextureOptions, hasAlpha: boolean): void {
if (options.bmsColorKey) applyBMSColorKey(data, options.bmsColorKey, hasAlpha);
if (options.swBGAColorKey) applyBMSColorKey(data, options.swBGAColorKey, true);
}
|