All files / player-terminal/src bga-frame-source.ts

100% Statements 80/80
95.55% Branches 43/45
100% Functions 18/18
100% Lines 77/77

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                                                                              653x 653x 653x 297x 297x 295x 295x   297x   653x       180x                       1601x 861x         740x 1601x                 300x                                 5x                                       311x 290x         16x               357x 61x 61x 61x 192x 192x   128x   64x 64x   192x 192x   61x     13x   14x   1157x 110x 110x 110x     192x       110x           773x 1x           772x 573x           199x 1x           198x 198x 198x 198x 344x 344x 272x 272x   72x       198x 198x                   342x 342x 200x   142x 10x   132x       132x 112x   20x 132x 132x 10x   10x 132x 132x             54x 27x         27x 13x   14x 14x    
import type { BGACue } from '@be-music/chart-model';
import { DEFAULT_IMAGE_RESIZE_ALGORITHM, type ImageResizeAlgorithm } from '@be-music/player-engine/display';
import {
  TERMINAL_PIXEL_ASPECT_X,
  TERMINAL_PIXEL_ASPECT_Y,
  type ANSIFrame,
  resizeANSIFrameWithAspectMode,
} from './bga-frame.ts';
 
export interface TimedANSIFrame {
  seconds: number;
  frame: ANSIFrame;
}
 
interface StaticFrameSource {
  kind: 'static';
  frame: ANSIFrame;
}
 
export interface VideoFrameSource {
  kind: 'video';
  frames: TimedANSIFrame[];
  durationSeconds?: number;
  ensureStreaming?: () => void;
}
 
export type FrameSource = StaticFrameSource | VideoFrameSource;
 
export interface FrameSelection {
  frame?: ANSIFrame;
  index: number;
}
 
export function resizeFrameSourceMap(
  sourceMap: Map<string, FrameSource>,
  width: number,
  height: number,
  resizeAlgorithm: ImageResizeAlgorithm = DEFAULT_IMAGE_RESIZE_ALGORITHM,
): Map<string, FrameSource> {
  const map = new Map<string, FrameSource>();
  const cache = new WeakMap<FrameSource, FrameSource>();
  for (const [key, source] of sourceMap) {
    let resized = cache.get(source);
    if (!resized) {
      resized = resizeFrameSource(source, width, height, resizeAlgorithm);
      cache.set(source, resized);
    }
    map.set(key, resized);
  }
  return map;
}
 
export function createStaticFrameSource(frame: ANSIFrame): FrameSource {
  return {
    kind: 'static',
    frame,
  };
}
 
export function resolveFrameSelection(
  sourceFramesByKey: ReadonlyMap<string, FrameSource>,
  missingFrame: ANSIFrame,
  key: string,
  seconds: number,
): FrameSelection {
  if (!key) {
    return {
      frame: undefined,
      index: -1,
    };
  }
  const source = sourceFramesByKey.get(key) ?? createStaticFrameSource(missingFrame);
  return selectFrameFromSource(source, seconds);
}
 
export function resizeFrameSource(
  source: FrameSource,
  width: number,
  height: number,
  resizeAlgorithm: ImageResizeAlgorithm = DEFAULT_IMAGE_RESIZE_ALGORITHM,
): FrameSource {
  return resizeFrameSourceWithAspectMode(
    source,
    width,
    height,
    TERMINAL_PIXEL_ASPECT_X,
    TERMINAL_PIXEL_ASPECT_Y,
    'contain',
    resizeAlgorithm,
  );
}
 
export function resizeFrameSourceCover(
  source: FrameSource,
  width: number,
  height: number,
  resizeAlgorithm: ImageResizeAlgorithm = DEFAULT_IMAGE_RESIZE_ALGORITHM,
): FrameSource {
  return resizeFrameSourceWithAspectMode(
    source,
    width,
    height,
    TERMINAL_PIXEL_ASPECT_X,
    TERMINAL_PIXEL_ASPECT_Y,
    'cover',
    resizeAlgorithm,
  );
}
 
export function resizeFrameSourceWithAspectMode(
  source: FrameSource,
  width: number,
  height: number,
  aspectX: number,
  aspectY: number,
  mode: 'contain' | 'cover',
  resizeAlgorithm: ImageResizeAlgorithm = DEFAULT_IMAGE_RESIZE_ALGORITHM,
): FrameSource {
  return mapFrameSource(source, (frame) =>
    resizeANSIFrameWithAspectMode(frame, width, height, aspectX, aspectY, mode, resizeAlgorithm),
  );
}
 
/** How many transformed frames a mapped video keeps; the rest are transformed again when they are shown again. */
export const MAPPED_FRAME_CACHE_SIZE = 8;
 
/**
 * Transform static frames once, and streamed frames when they are shown, preserving the stream's clock and lazy
 * startup. A mapped video keeps only its {@link MAPPED_FRAME_CACHE_SIZE} most recently shown frames, so a chain of maps
 * (colour key, `#BGA` crop, resize) holds no copy of the whole movie beside the decoded one.
 */
export function mapFrameSource(source: FrameSource, transform: (frame: ANSIFrame) => ANSIFrame): FrameSource {
  if (source.kind === 'static') return { kind: 'static', frame: transform(source.frame) };
  const mappedFrames: TimedANSIFrame[] = [];
  const recent = new Map<number, ANSIFrame>();
  const frameAt = (index: number, upstream: TimedANSIFrame): ANSIFrame => {
    let frame = recent.get(index);
    if (frame) {
      // Most recently shown last, so the oldest is first to go.
      recent.delete(index);
    } else {
      frame = transform(upstream.frame);
      if (recent.size >= MAPPED_FRAME_CACHE_SIZE) recent.delete(recent.keys().next().value!);
    }
    recent.set(index, frame);
    return frame;
  };
  return {
    kind: 'video',
    get durationSeconds() {
      return source.durationSeconds;
    },
    ensureStreaming: () => source.ensureStreaming?.(),
    get frames() {
      for (let index = mappedFrames.length; index < source.frames.length; index += 1) {
        const upstream = source.frames[index]!;
        const at = index;
        mappedFrames.push({
          seconds: upstream.seconds,
          get frame() {
            return frameAt(at, upstream);
          },
        });
      }
      return mappedFrames;
    },
  };
}
 
export function selectFrameFromSource(source: FrameSource | undefined, seconds: number): FrameSelection {
  if (!source) {
    return {
      frame: undefined,
      index: -1,
    };
  }
 
  if (source.kind === 'static') {
    return {
      frame: source.frame,
      index: 0,
    };
  }
 
  if (source.frames.length === 0) {
    return {
      frame: undefined,
      index: -1,
    };
  }
 
  let low = 0;
  let high = source.frames.length - 1;
  let answer = 0;
  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    if (source.frames[mid].seconds <= seconds) {
      answer = mid;
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
 
  const bounded = Math.max(0, Math.min(source.frames.length - 1, answer));
  return {
    frame: source.frames[bounded].frame,
    index: bounded,
  };
}
 
export function resolveTimelinePlaybackEndSeconds(
  timeline: ReadonlyArray<BGACue>,
  sourcesByKey: ReadonlyMap<string, FrameSource>,
): number {
  const lastCue = timeline.at(-1);
  if (!lastCue) {
    return 0;
  }
  if (!lastCue.key) {
    return lastCue.seconds;
  }
  return lastCue.seconds + resolveFrameSourceDurationSeconds(sourcesByKey.get(lastCue.key));
}
 
function resolveFrameSourceDurationSeconds(source: FrameSource | undefined): number {
  if (!source || source.kind === 'static') {
    return 0;
  }
  const streamDuration = source.durationSeconds ?? 0;
  const lastFrameSeconds = source.frames.at(-1)?.seconds ?? 0;
  if (source.frames.length < 2) {
    return Math.max(streamDuration, lastFrameSeconds);
  }
  const previousFrameSeconds = source.frames.at(-2)?.seconds ?? 0;
  const estimatedTailSeconds = Math.max(0, lastFrameSeconds - previousFrameSeconds);
  return Math.max(streamDuration, lastFrameSeconds + estimatedTailSeconds);
}
 
export function startStreamingFrameSourceMap(
  sourceMap: ReadonlyMap<string, FrameSource>,
  seen: Set<FrameSource>,
): void {
  for (const source of sourceMap.values()) {
    startStreamingFrameSource(source, seen);
  }
}
 
function startStreamingFrameSource(source: FrameSource | undefined, seen: Set<FrameSource>): void {
  if (!source || source.kind === 'static' || seen.has(source)) {
    return;
  }
  seen.add(source);
  source.ensureStreaming?.();
}