aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/Player/Video.ts
blob: 78b3b8fc953bc76bcaddcf559b649996b442cc2b (plain) (blame)
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
export type FrameTime = {
  milliseconds: number,
  seconds: number,
  frames: number
}
export abstract class Video {
  public constructor(public canvas: HTMLCanvasElement) { };
  public abstract renderFrame(time: FrameTime): Promise<void> | void;
  /** (re-)Initializes the Video object. Also called on window resizes. */
  public abstract init(): void | Promise<void>;
  private _isInit = false;
  /** The frames per second to render at */
  public abstract get fps(): number;
  /** Length in frames */
  public abstract get length(): number;
  /** A URL (and matching filename) to an ffmpeg-compatible audio file */
  public audioUrl?: readonly [filename: string, fileUrl: string];
  /** Resizes the canvas to a predetermined render resolution - must only be called in init() - do not overwrite */
  public resize(x: number, y: number) {
    if (!this._isInit) throw new Error('Must only call resize() in init.')
    this.canvas.width = x;
    this.canvas.height = y;
    const parentW = this.canvas.parentElement!.clientWidth,
      parentH = this.canvas.parentElement!.clientHeight
    if (x <= parentW && y <= parentH) {
      this.canvas.style.width = `${x}px`;
      this.canvas.style.height = `${y}px`;
    } else if (x <= parentW && y > parentH) {
      this.canvas.style.width = `${x / y * parentH}px`;
      this.canvas.style.height = `${parentH}px`;
    } else if (y <= parentH && x > parentW) {
      this.canvas.style.width = `${parentW}px`;
      this.canvas.style.height = `${y / x * parentW}px`;
    } else {
      if ((parentW / x) * y > parentH) {
        this.canvas.style.width = `${(parentH / y) * x}px`
        this.canvas.style.height = `${parentH}px`
      } else {
        this.canvas.style.width = `${parentW}px`
        this.canvas.style.height = `${(parentW / x) * y}px`
      }
    }
  }
  /** The width of the video, in pixels */
  public get w() {
    return this.canvas.width;
  }
  /** The height of the video, in pixels */
  public get h() {
    return this.canvas.height;
  }
  /** Use to cleanup any mess you made - do not remove the canvas, it may be reused. */
  public cleanup() { };
}
export type VideoConstructor = new (...params: ConstructorParameters<typeof Video>) => Video