aboutsummaryrefslogtreecommitdiff
path: root/web/script/player/track/mse.ts
blob: 199aa140e0d8659f8e463253c9a0c8e997d6a856 (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/
import { OVar } from "../../jshelper/mod.ts";
import { test_media_capability, track_to_content_type } from "../mediacaps.ts";
import { BufferRange, Player } from "../player.ts";
import { PlayerTrack, AppendRange, TARGET_BUFFER_DURATION, MIN_BUFFER_DURATION } from "./mod.ts";
import { e } from "../../jshelper/src/element.ts";
import { FormatInfo, FragmentIndex, StreamContainer, TrackInfo } from "../types_stream.ts";

interface UsableFormat { format_index: number, usable_index: number, format: FormatInfo, container: StreamContainer }

export class MSEPlayerTrack extends PlayerTrack {
  public source_buffer!: SourceBuffer;
  private current_load?: AppendRange;
  private loading = new Set<number>();
  private append_queue: AppendRange[] = [];
  public index?: FragmentIndex
  public active_format = new OVar<UsableFormat | undefined>(undefined);
  public usable_formats: UsableFormat[] = []

  constructor(
    private player: Player,
    private base_url: string,
    private segment_index: number,
    track_index: number,
    public trackinfo: TrackInfo,
  ) {
    super(track_index);
    this.init()
  }

  async init() {
    this.buffered.value = [{ start: 0, end: this.player.duration.value, status: "loading" }]
    try {
      const res = await fetch(`${this.base_url}?fragmentindex&segment=${this.segment_index}&track=${this.track_index}`, { headers: { "Accept": "application/json" } });
      if (!res.ok) return this.player.error.value = "Cannot download index.", undefined;
      let index!: FragmentIndex & { error: string; };
      try { index = await res.json(); }
      catch (_) { this.player.set_pers("Error: Failed to fetch node"); }
      if (index.error) return this.player.set_pers("server error: " + index.error), undefined;
      this.index = index
    } catch (e) {
      if (e instanceof TypeError) {
        this.player.set_pers("Cannot download index: Network Error");
      } else throw e;
    }
    this.buffered.value = []

    console.log(this.trackinfo);

    for (let i = 0; i < this.trackinfo.formats.length; i++) {
      const format = this.trackinfo.formats[i];
      for (const container of format.containers) {
        if (container != "webm" && container != "mpeg4") continue;
        if (await test_media_capability(format, container))
          this.usable_formats.push({ container, format, format_index: i, usable_index: this.usable_formats.length })
      }
    }
    if (!this.usable_formats.length)
      return this.player.logger?.log("No availble format is supported by this device. The track can't be played back.")
    this.active_format.value = this.usable_formats[0]

    const ct = track_to_content_type(this.active_format.value!.format, this.active_format.value!.container);
    this.source_buffer = this.player.media_source.addSourceBuffer(ct);
    this.abort.signal.addEventListener("abort", () => {
      console.log(`destroy source buffer for track ${this.track_index}`);
      this.player.media_source.removeSourceBuffer(this.source_buffer);
    });
    this.source_buffer.mode = "segments";
    this.source_buffer.addEventListener("updateend", () => {
      if (this.abort.signal.aborted) return;
      if (this.current_load) {
        this.loading.delete(this.current_load.index);
        const cb = this.current_load.cb;
        this.current_load = undefined;
        cb()
      } else {
        console.warn("updateend but nothing is loading")
      }
      this.update_buf_ranges();
      this.tick_append();
    });
    this.source_buffer.addEventListener("error", e => {
      console.error("sourcebuffer error", e);
    });
    this.source_buffer.addEventListener("abort", e => {
      console.error("sourcebuffer abort", e);
    });

    this.update(this.player.video.currentTime)
  }

  update_buf_ranges() {
    if (!this.index) return;
    const ranges: BufferRange[] = [];
    for (let i = 0; i < this.source_buffer.buffered.length; i++) {
      ranges.push({
        start: this.source_buffer.buffered.start(i),
        end: this.source_buffer.buffered.end(i),
        status: "buffered"
      });
    }
    for (const r of this.loading) {
      ranges.push({ ...this.index[r], status: "loading" });
    }
    this.buffered.value = ranges;
  }

  override async update(target: number) {
    if (!this.index) return;
    this.update_buf_ranges(); // TODO required?

    const blocking = [];
    for (let i = 0; i < this.index.length; i++) {
      const frag = this.index[i];
      if (frag.end < target) continue;
      if (frag.start >= target + TARGET_BUFFER_DURATION) break;
      if (!this.check_buf_collision(frag.start, frag.end)) continue;
      if (frag.start <= target + MIN_BUFFER_DURATION)
        blocking.push(this.load(i));
      else
        this.load(i);
    }
    await Promise.all(blocking);
  }
  check_buf_collision(start: number, end: number) {
    const EPSILON = 0.01;
    for (const r of this.buffered.value)
      if (r.end - EPSILON > start && r.start < end - EPSILON)
        return false;
    return true;
  }

  async load(index: number) {
    this.loading.add(index);
    // TODO update format selection
    const url = `${this.base_url}?fragment&segment=${this.segment_index}&track=${this.track_index}&format=${this.active_format.value!.format_index}&index=${index}&container=${this.active_format.value!.container}`;
    const buf = await this.player.downloader.download(url);
    await new Promise<void>(cb => {
      if (!this.index) return;
      if (this.abort.signal.aborted) return;
      this.append_queue.push({ buf, ...this.index[index], index, cb });
      this.tick_append();
    });
  }
  tick_append() {
    if (this.source_buffer.updating || this.current_load) return;
    if (this.append_queue.length) {
      const frag = this.append_queue[0];
      this.append_queue.splice(0, 1);
      this.current_load = frag;
      // TODO why is appending so unreliable?! sometimes it does not add it
      this.source_buffer.changeType(track_to_content_type(this.active_format.value!.format, this.active_format.value!.container));
      this.source_buffer.timestampOffset = this.active_format.value?.format.remux ? 0 : frag.start
      console.log(`append track at ${this.source_buffer.timestampOffset} ${this.trackinfo.kind} ${this.track_index}`);
      this.source_buffer.appendBuffer(frag.buf);
    }
  }

  public debug(): OVar<HTMLElement> {
    const rtype = (t: string, b: BufferRange[]) => {
      const c = b.filter(r => r.status == t);
      // ${c.length} range${c.length != 1 ? "s" : ""}
      return `${c.reduce((a, v) => a + v.end - v.start, 0).toFixed(2)}s`
    }
    return this.active_format.liftA2(this.buffered, (p, b) =>
      e("pre",
        p ?
          `mse track ${this.track_index}: format ${p.format_index} (${p.format.remux ? "remux" : "transcode"})`
          + `\n\ttype: ${track_to_content_type(p.format, p.container)} br=${p.format.bitrate}`
          + `\n\tbuffered: ${rtype("buffered", b)} / queued: ${rtype("queued", b)} / loading: ${rtype("loading", b)}`
          : ""
      ) as HTMLElement
    )
  }
}