All files / player-browser/src/media/bga-stream stream.ts

13.08% Statements 25/191
6.18% Branches 6/97
7.89% Functions 3/38
13.58% Lines 22/162

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                                    119x                                                           119x   119x                                                                                                                                                                                                                                                                                                                                                                                                                 119x                                                     119x                             119x 119x                                                                                                               7x 8x 3x 3x 3x 8x 8x   3x               4x 4x 4x 3x 3x 2x   1x    
/**
 * Main-thread side of the streaming BGA transcode: starts the workers, collects the fMP4 bytes they post, and hands
 * them to every `<video>` playing the stream (see `media-source.ts`).
 *
 * A stream keeps all of its bytes, so a video attached late — the same BGA on another track — is fed from the start,
 * and a video that seeks back finds them again. Compressed, they are a few megabytes for a typical BGA.
 */
import { logger } from '../../logger.ts';
import {
  FFMPEG_CORE_URL,
  FFMPEG_WASM_URL,
  readAVCCodecString,
  type BGAStreamOutput,
  type BGATranscodeQuality,
} from './ffmpeg-args.ts';
import { canShareFlowControl, createFlowCounter } from './flow.ts';
import type { BGADecodeStartMessage, BGAEncodeStartMessage, BGAStreamWorkerMessage } from './protocol.ts';
 
const log = logger('bga-video');
 
/** What the host's worker factories return; a DOM `Worker` fits. */
export interface BGAVideoWorker {
  postMessage(message: unknown, transfer?: Transferable[]): void;
  terminate(): void;
  onmessage: ((event: MessageEvent) => void) | null;
  onerror: ((event: ErrorEvent) => void) | null;
}
 
/**
 * Host-bundled workers for the streaming transcode. Their entries call `runBGAVideoDecodeWorker()` and
 * `runBGAVideoEncodeWorker()` from `@be-music/player-browser/compute`.
 */
export interface BGAVideoWorkerFactories {
  createDecodeWorker(): BGAVideoWorker;
  createEncodeWorker(): BGAVideoWorker;
}
 
let workerFactories: BGAVideoWorkerFactories | undefined;
 
/**
 * Installs the workers of the streaming BGA transcode. Without them, a BGA video the browser can't play is transcoded
 * whole before it plays.
 */
export function configureBGAVideoWorkers(factories: BGAVideoWorkerFactories | undefined): void {
  workerFactories = factories;
}
 
/** Transcodes that run at once; later ones wait for a slot. Each decodes on a core of its own. */
const MAX_RUNNING_STREAMS = 2;
/** How far into the stream to look for the init segment's `avcC` box. */
const CODEC_SCAN_BYTES = 256 * 1024;
 
export type BGAVideoStreamState = 'running' | 'done' | 'failed' | 'cancelled';
 
export interface BGAVideoStreamOptions {
  maxLongEdge?: number;
  /** How much bitrate the encode spends, `standard` by default. */
  quality?: BGATranscodeQuality;
  /**
   * Encode with WebCodecs where it can — it needs a cross-origin isolated page for the flow control (`flow.ts`) —
   * otherwise (or when it fails) the core's libx264 encodes.
   */
  useWebCodecs: boolean;
}
 
/**
 * One transcode in progress or finished. Subscribers are called after every change; the transcode is cancelled once
 * the last one unsubscribes.
 */
export class BGAVideoStream {
  /** The fMP4 bytes so far, in order. */
  public readonly chunks: Uint8Array[] = [];
  public state: BGAVideoStreamState = 'running';
  /** `avc1.*` codec string from the init segment, once it has arrived. */
  public codec: string | undefined;
  /** Rejects if the stream fails or is cancelled before producing any bytes; never resolves. */
  public readonly failure: Promise<never>;
 
  private readonly listeners = new Set<() => void>();
  private rejectFailure: (error: Error) => void = () => {};
  private stopAttempt: (() => void) | undefined;
  private chunkBytes = 0;
  private readonly source: Blob;
  private readonly path: string;
  private readonly options: BGAVideoStreamOptions;
 
  public constructor(source: Blob, path: string, options: BGAVideoStreamOptions) {
    this.source = source;
    this.path = path;
    this.options = options;
    this.failure = new Promise<never>((_, reject) => {
      this.rejectFailure = reject;
    });
    // Nobody may be waiting on it.
    this.failure.catch(() => {});
  }
 
  public subscribe(listener: () => void): () => void {
    this.listeners.add(listener);
    return () => {
      if (!this.listeners.delete(listener)) return;
      if (this.listeners.size === 0) this.cancel();
    };
  }
 
  public get settled(): boolean {
    return this.state !== 'running';
  }
 
  /** Runs the transcode; settles when it ends, however it ends. */
  public async run(): Promise<void> {
    const release = await acquireSlot();
    try {
      if (this.settled) return;
      const startedAt = performance.now();
      const assets = await loadCoreAssets();
      const modes: BGAStreamOutput[] =
        this.options.useWebCodecs && 'VideoEncoder' in globalThis && canShareFlowControl() ? ['raw', 'h264'] : ['h264'];
      for (const mode of modes) {
        if (this.settled) return;
        const result = await this.attempt(mode, assets);
        if (this.settled) return;
        if (result.ok) {
          const elapsed = ((performance.now() - startedAt) / 1000).toFixed(2);
          log.info(
            `stream transcode ok (${mode === 'raw' ? 'WebCodecs' : 'libx264'}): ${this.path} → ${this.chunkBytes} bytes` +
              `${result.frames ? `, ${result.frames} frames` : ''} in ${elapsed}s`,
          );
          return this.finish('done');
        }
        log.warn(`stream transcode (${mode}) failed: ${this.path}: ${result.message}`, result.log ?? '');
        // A failure after some output can't restart: what arrived plays, and the video stops where it ends.
        if (this.chunks.length > 0) return this.finish('done');
      }
      this.finish('failed');
    } catch (error) {
      log.warn(`stream transcode threw: ${this.path}`, error);
      this.finish(this.chunks.length > 0 ? 'done' : 'failed');
    } finally {
      release();
    }
  }
 
  public cancel(): void {
    if (this.settled) return;
    this.finish('cancelled');
  }
 
  private attempt(
    mode: BGAStreamOutput,
    assets: CoreAssets,
  ): Promise<{ ok: true; frames: number } | { ok: false; message: string; log?: string[] }> {
    const factories = workerFactories;
    if (!factories) return Promise.resolve({ ok: false, message: 'no workers configured' });
    return new Promise((resolve) => {
      const workers: BGAVideoWorker[] = [];
      let settled = false;
      const settle = (result: Parameters<typeof resolve>[0]): void => {
        if (settled) return;
        settled = true;
        this.stopAttempt = undefined;
        for (const worker of workers) worker.terminate();
        resolve(result);
      };
      this.stopAttempt = () => settle({ ok: false, message: 'cancelled' });
      try {
        const decoder = factories.createDecodeWorker();
        workers.push(decoder);
        const start: BGADecodeStartMessage = {
          type: 'start',
          coreURL: assets.coreURL,
          wasmModule: assets.wasmModule,
          // A blob crosses to the worker as a handle: its data is neither copied nor read here.
          input: this.source,
          inputName: `bga-input${pickInputExtension(this.path)}`,
          mode,
          ...(this.options.maxLongEdge !== undefined ? { maxLongEdge: this.options.maxLongEdge } : {}),
          ...(this.options.quality !== undefined ? { quality: this.options.quality } : {}),
        };
        let producer = decoder;
        if (mode === 'raw') {
          const encoder = factories.createEncodeWorker();
          workers.push(encoder);
          producer = encoder;
          const channel = new MessageChannel();
          const flow = createFlowCounter();
          start.framePort = channel.port1;
          start.flow = flow;
          const encodeStart: BGAEncodeStartMessage = {
            type: 'start',
            framePort: channel.port2,
            flow,
            ...(this.options.quality !== undefined ? { quality: this.options.quality } : {}),
          };
          encoder.postMessage(encodeStart, [channel.port2]);
          // The decoder reports only failures here: its frames went to the encoder, which reports the output.
          decoder.onmessage = (event) => {
            const message = event.data as BGAStreamWorkerMessage;
            if (message.type === 'error') settle({ ok: false, message: message.message, log: message.log });
          };
          decoder.onerror = (event) => {
            event.preventDefault();
            // Let the encoder finish what it has (the decoder can't send `end` any more).
            encoder.postMessage({ type: 'end' });
            log.warn(`decode worker crashed: ${this.path}`, event.message);
          };
        }
        producer.onmessage = (event) => {
          const message = event.data as BGAStreamWorkerMessage;
          if (message.type === 'chunk') this.append(new Uint8Array(message.data));
          else if (message.type === 'done') settle({ ok: true, frames: message.frames });
          else settle({ ok: false, message: message.message, log: message.log });
        };
        producer.onerror = (event) => {
          event.preventDefault();
          settle({ ok: false, message: event.message || 'worker error' });
        };
        decoder.postMessage(start, start.framePort ? [start.framePort] : []);
      } catch (error) {
        settle({ ok: false, message: error instanceof Error ? error.message : String(error) });
      }
    });
  }
 
  private append(chunk: Uint8Array): void {
    if (this.settled || chunk.byteLength === 0) return;
    this.chunks.push(chunk);
    this.chunkBytes += chunk.byteLength;
    if (this.codec === undefined && this.chunkBytes - chunk.byteLength < CODEC_SCAN_BYTES) {
      this.codec = readAVCCodecString(concatChunks(this.chunks));
    }
    this.notify();
  }
 
  private finish(state: Exclude<BGAVideoStreamState, 'running'>): void {
    if (this.settled) return;
    this.state = state;
    this.stopAttempt?.();
    if (state !== 'done') {
      forgetStream(this);
      if (this.chunks.length === 0) this.rejectFailure(new Error(`BGA stream ${state}: ${this.path}`));
    }
    this.notify();
  }
 
  private notify(): void {
    for (const listener of this.listeners) listener();
  }
}
 
/** One stream per source file and transcode settings, so the same BGA on several tracks transcodes once. */
const streams = new WeakMap<Blob, Map<string, BGAVideoStream>>();
 
/** Whether {@link openBGAVideoStream} can run here: the host installed its workers and the browser has MSE. */
export function canStreamBGAVideo(): boolean {
  return workerFactories !== undefined && resolveMediaSourceClass() !== undefined;
}
 
/**
 * The stream transcoding `source`, started on first use. Subscribe to it before awaiting anything, or a stream nobody
 * holds may be cancelled by its last other subscriber leaving.
 */
export function openBGAVideoStream(source: Blob, path: string, options: BGAVideoStreamOptions): BGAVideoStream {
  const key = `${options.maxLongEdge ?? 0}:${options.useWebCodecs ? 'webcodecs' : 'libx264'}:${options.quality ?? 'standard'}`;
  let byOptions = streams.get(source);
  if (!byOptions) {
    byOptions = new Map();
    streams.set(source, byOptions);
  }
  const existing = byOptions.get(key);
  if (existing) return existing;
  const stream = new BGAVideoStream(source, path, options);
  byOptions.set(key, stream);
  streamKeys.set(stream, { source, key });
  void stream.run();
  return stream;
}
 
const streamKeys = new WeakMap<BGAVideoStream, { source: Blob; key: string }>();
 
function forgetStream(stream: BGAVideoStream): void {
  const entry = streamKeys.get(stream);
  if (!entry) return;
  const byOptions = streams.get(entry.source);
  if (byOptions?.get(entry.key) === stream) byOptions.delete(entry.key);
}
 
/** `ManagedMediaSource` where the browser has it (iPhone Safari has nothing else), else `MediaSource`. */
export function resolveMediaSourceClass(): typeof MediaSource | undefined {
  const scope = globalThis as { ManagedMediaSource?: typeof MediaSource; MediaSource?: typeof MediaSource };
  return scope.ManagedMediaSource ?? scope.MediaSource;
}
 
let running = 0;
const waiting: (() => void)[] = [];
 
function acquireSlot(): Promise<() => void> {
  return new Promise((resolve) => {
    const grant = (): void => {
      running++;
      let released = false;
      resolve(() => {
        if (released) return;
        released = true;
        running--;
        waiting.shift()?.();
      });
    };
    if (running < MAX_RUNNING_STREAMS) grant();
    else waiting.push(grant);
  });
}
 
interface CoreAssets {
  coreURL: string;
  wasmModule: WebAssembly.Module;
}
 
let coreAssets: Promise<CoreAssets> | undefined;
 
/** The core script as a blob URL (module workers import it) and its wasm compiled once for every worker. */
function loadCoreAssets(): Promise<CoreAssets> {
  coreAssets ??= (async () => {
    const [script, wasmModule] = await Promise.all([fetchOK(FFMPEG_CORE_URL).then((res) => res.blob()), compileWasm()]);
    const coreURL = URL.createObjectURL(new Blob([script], { type: 'text/javascript' }));
    return { coreURL, wasmModule };
  })().catch((error: unknown) => {
    // A network blip shouldn't disable streaming for the rest of the session.
    coreAssets = undefined;
    throw error;
  });
  return coreAssets;
}
 
async function compileWasm(): Promise<WebAssembly.Module> {
  try {
    return await WebAssembly.compileStreaming(fetchOK(FFMPEG_WASM_URL));
  } catch {
    // `compileStreaming` needs an `application/wasm` response; some hosts send another type.
    return WebAssembly.compile(await (await fetchOK(FFMPEG_WASM_URL)).arrayBuffer());
  }
}
 
async function fetchOK(url: string): Promise<Response> {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`failed to fetch ${url}: ${response.status}`);
  return response;
}
 
export function concatChunks(chunks: readonly Uint8Array[]): Uint8Array {
  if (chunks.length === 1) return chunks[0]!;
  const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
  const out = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    out.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return out;
}
 
/**
 * Keeps the source's extension so ffmpeg picks the right demuxer (`.mpg` → mpegps, `.avi` → avi, `.wmv` → asf, …),
 * from a short allowlist so no user-controlled string reaches the virtual file system.
 */
export function pickInputExtension(path: string): string {
  const lower = path.toLowerCase();
  const dotIndex = lower.lastIndexOf('.');
  if (dotIndex < 0) return '.mpg';
  const ext = lower.slice(dotIndex);
  if (['.mpg', '.mpeg', '.avi', '.wmv', '.mov', '.mp4', '.webm', '.mkv', '.ogv', '.ogg'].includes(ext)) {
    return ext;
  }
  return '.mpg';
}