All files / player-browser/src/skin/be-music chart-images.ts

97.46% Statements 77/79
95% Branches 38/40
100% Functions 10/10
97.22% Lines 70/72

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              33x           33x       21x 21x 21x                                           10x 10x 10x 10x     10x 10x     10x 10x         3x     32x 32x 30x 30x 30x   11x 11x 11x   19x 15x 15x 32x 3x 3x   12x 12x 12x         9x 9x 4x   2x 2x 2x 2x 2x 2x 2x 2x         2x 2x         6x 6x 6x 6x 6x       6x 5x 5x                     12x 12x       11x 2x 2x   9x 9x 1x 1x   8x 8x 8x       8x 10x 2x 2x                   2x 2x    
import { loadAssetBytes, resolveChartImageAsset } from '../../collection/collection.ts';
import type { LibraryChart } from '@be-music/player-scene-model';
import type { BrowserAssetSource } from '../../collection/types.ts';
import { loadImageBitmapFromBytes } from '../../media/textures.ts';
import { logger } from '../../logger.ts';
import type { BeMusicChartImageKind, BeMusicChartImageLookup } from './types.ts';
 
const log = logger('be-music-chart-images');
 
/**
 * How many decoded song images a cache keeps before closing the least recently used one. Comfortably above what one
 * screen shows (a select list's banners plus the focused song's stage file and back image).
 */
export const DEFAULT_SONG_IMAGE_CAPACITY = 32;
 
/** The chart-relative path of a named loading, banner, background or pre-play title image. */
export function resolveChartImagePath(chartEntry: LibraryChart, kind: BeMusicChartImageKind): string | undefined {
  const metadata = chartEntry.chart.metadata;
  const path = metadata[kind];
  return path !== undefined && path.trim().length > 0 ? path : undefined;
}
 
export interface ChartImageCacheOptions {
  /** The asset source holding `song`'s files, or `undefined` when the host has none for it. */
  resolveSource(chartEntry: LibraryChart): BrowserAssetSource | undefined;
  /** Called after an image finished loading, so the screen can be redrawn (select bumps its `revision`). */
  onLoaded?: () => void;
  /** Most images kept decoded at once. Default {@link DEFAULT_SONG_IMAGE_CAPACITY}. */
  capacity?: number;
  /** Reads and decodes one image. Defaults to the chart-asset loader plus `createImageBitmap`; tests swap it. */
  load?: (source: BrowserAssetSource, chartEntry: LibraryChart, path: string) => Promise<ImageBitmap | undefined>;
}
 
/**
 * Decoded song images for Be-Music Skins, behind the synchronous {@link lookup} the frames hand out as `chartImage`. A
 * miss starts loading the image and answers `undefined`; once it decodes, `onLoaded` fires and later lookups return it.
 * Images that are missing or fail to decode are remembered so they aren't retried every frame. At most `capacity`
 * bitmaps are kept: the least recently looked-up one is `close()`d to make room, and {@link dispose} closes the rest.
 * A skin should therefore look an image up on every draw rather than keep the bitmap.
 */
export class ChartImageCache {
  private readonly images = new Map<string, ImageBitmap>();
  private readonly imageURLs = new WeakMap<ImageBitmap, string | undefined>();
  private readonly pending = new Set<string>();
  private readonly unavailable = new Set<string>();
  private readonly options: ChartImageCacheOptions;
  private readonly capacity: number;
  private generation = 0;
  private disposed = false;
 
  constructor(options: ChartImageCacheOptions) {
    this.options = options;
    this.capacity = Math.max(1, Math.floor(options.capacity ?? DEFAULT_SONG_IMAGE_CAPACITY));
  }
 
  /** Number of decoded images held right now. */
  get size(): number {
    return this.images.size;
  }
 
  readonly lookup: BeMusicChartImageLookup = (chartEntry, kind) => {
    if (this.disposed) return undefined;
    const key = `${chartEntry.sourceId}\u0000${chartEntry.chartPath}\u0000${kind}`;
    const cached = this.images.get(key);
    if (cached) {
      // Re-insert so the map's insertion order doubles as the recency order the eviction walks.
      this.images.delete(key);
      this.images.set(key, cached);
      return cached;
    }
    if (this.pending.has(key) || this.unavailable.has(key)) return undefined;
    const path = resolveChartImagePath(chartEntry, kind);
    const source = path !== undefined ? this.options.resolveSource(chartEntry) : undefined;
    if (path === undefined || source === undefined) {
      this.unavailable.add(key);
      return undefined;
    }
    this.pending.add(key);
    void this.load(key, source, chartEntry, path, this.generation);
    return undefined;
  };
 
  /** The same decoded artwork for a DOM image. Canvas conversion also supports formats decoded by our adapters. */
  lookupURL(chartEntry: LibraryChart, kind: BeMusicChartImageKind): string | undefined {
    const image = this.lookup(chartEntry, kind);
    if (!image) return undefined;
    if (this.imageURLs.has(image)) return this.imageURLs.get(image);
    let url: string | undefined;
    try {
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      Eif (context) {
        context.drawImage(image, 0, 0);
        url = canvas.toDataURL('image/png');
      }
    } catch (error) {
      log.debug('chart image cannot be presented on DOM', error);
    }
    this.imageURLs.set(image, url);
    return url;
  }
 
  /** Closes every image and forgets what was missing (e.g. after the song collection was replaced). */
  clear(): void {
    this.generation += 1;
    for (const image of this.images.values()) image.close();
    this.images.clear();
    this.pending.clear();
    this.unavailable.clear();
  }
 
  dispose(): void {
    if (this.disposed) return;
    this.clear();
    this.disposed = true;
  }
 
  private async load(
    key: string,
    source: BrowserAssetSource,
    chartEntry: LibraryChart,
    path: string,
    generation: number,
  ): Promise<void> {
    let image: ImageBitmap | undefined;
    try {
      image = await (this.options.load ?? loadSongImage)(source, chartEntry, path);
    } catch (error) {
      log.debug('song image failed to load', { path, error });
    }
    if (this.disposed || generation !== this.generation) {
      image?.close();
      return;
    }
    this.pending.delete(key);
    if (!image) {
      this.unavailable.add(key);
      return;
    }
    this.images.set(key, image);
    this.evict();
    this.options.onLoaded?.();
  }
 
  private evict(): void {
    for (const [key, image] of this.images) {
      if (this.images.size <= this.capacity) return;
      this.images.delete(key);
      image.close();
    }
  }
}
 
async function loadSongImage(
  source: BrowserAssetSource,
  chartEntry: LibraryChart,
  path: string,
): Promise<ImageBitmap | undefined> {
  const bytes = await loadAssetBytes(resolveChartImageAsset(source, chartEntry.chartPath, path));
  return bytes ? loadImageBitmapFromBytes(path, bytes) : undefined;
}