aboutsummaryrefslogtreecommitdiff
path: root/web/script/player/download.ts
blob: 2549600683a6718e5d08c8a950365578bd6fe6ed (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
/*
    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) 2023 metamuffin <metamuffin.org>
*/
/// <reference lib="dom" />
import { OVar } from "../jshelper/mod.ts";

interface Measurement { time: number, duration: number, size: number }
export class SegmentDownloader {
    private measurements: Measurement[] = []

    public bandwidth = new OVar(Infinity)

    constructor() { }

    async download(url: string): Promise<ArrayBuffer> {
        const dl_start = performance.now();
        const res = await fetch(url)
        const dl_header = performance.now();
        if (!res.ok) throw new Error("aaaaa");
        const buf = await res.arrayBuffer()
        const dl_body = performance.now();

        if (buf.byteLength > 100 * 1000) {
            const m = {
                time: dl_start,
                duration: (dl_body - dl_header) / 1000,
                size: buf.byteLength
            }
            this.measurements.push(m)
            this.update_bandwidth()
        }
        return buf;
    }

    update_bandwidth() {
        while (this.measurements.length > 32)
            this.measurements.splice(0, 1)
        const total_size = this.measurements.reduce((a, v) => v.size + a, 0)
        const total_duration = this.measurements.reduce((a, v) => v.duration + a, 0)
        const average = total_size / total_duration
        this.bandwidth.value = average
    }
}