File size: 5,755 Bytes
11fcc5a
de4b571
11fcc5a
 
de4b571
11fcc5a
de4b571
 
 
 
 
 
 
 
11fcc5a
de4b571
 
 
11fcc5a
 
 
 
 
 
 
 
 
 
 
 
de4b571
11fcc5a
 
 
de4b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11fcc5a
de4b571
 
 
11fcc5a
 
de4b571
 
11fcc5a
 
de4b571
 
11fcc5a
 
 
 
 
 
de4b571
 
 
 
11fcc5a
 
de4b571
11fcc5a
de4b571
 
 
 
 
 
 
 
11fcc5a
de4b571
 
 
 
 
 
 
11fcc5a
de4b571
 
 
 
11fcc5a
 
de4b571
11fcc5a
de4b571
 
 
 
11fcc5a
 
 
 
 
de4b571
 
 
 
 
 
 
 
 
 
 
 
11fcc5a
de4b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import * as Storage from "$lib/storage";
import LibAV, { type LibAV as LibAVInstance } from "@imput/libav.js-remux-cli";
import EncodeLibAV from "@imput/libav.js-encode-cli";

import type { FfprobeData } from "fluent-ffmpeg";
import type { FFmpegProgressCallback, FFmpegProgressEvent, FFmpegProgressStatus, RenderParams } from "$lib/types/libav";

export default class LibAVWrapper {
    libav: Promise<LibAVInstance> | null;
    concurrency: number;
    onProgress?: FFmpegProgressCallback;

    constructor(onProgress?: FFmpegProgressCallback) {
        this.libav = null;
        this.concurrency = Math.min(4, navigator.hardwareConcurrency || 0);
        this.onProgress = onProgress;
    }

    init(options?: LibAV.LibAVOpts) {
        const variant = options?.variant || 'remux';
        let constructor: typeof LibAV.LibAV;

        if (variant === 'remux') {
            constructor = LibAV.LibAV;
        } else if (variant === 'encode') {
            constructor = EncodeLibAV.LibAV;
        } else {
            throw "invalid variant";
        }

        if (this.concurrency && !this.libav) {
            this.libav = constructor({
                ...options,
                variant: undefined,
                base: '/_libav'
            });
        }
    }

    async terminate() {
        if (this.libav) {
            const libav = await this.libav;
            libav.terminate();
        }
    }

    async probe(blob: Blob) {
        if (!this.libav) throw new Error("LibAV wasn't initialized");
        const libav = await this.libav;

        await libav.mkreadaheadfile('input', blob);

        try {
            await libav.ffprobe([
                '-v', 'quiet',
                '-print_format', 'json',
                '-show_format',
                '-show_streams',
                'input',
                '-o', 'output.json'
            ]);

            const copy = await libav.readFile('output.json');
            const text = new TextDecoder().decode(copy);
            await libav.unlink('output.json');

            return JSON.parse(text) as FfprobeData;
        } finally {
            await libav.unlinkreadaheadfile('input');
        }
    }

    async render({ files, output, args }: RenderParams) {
        if (!this.libav) throw new Error("LibAV wasn't initialized");
        const libav = await this.libav;

        if (!(output.format && output.type)) {
            throw new Error("output's format or type is missing");
        }

        const outputName = `output.${output.format}`;
        const ffInputs = [];

        try {
            for (let i = 0; i < files.length; i++) {
                const file = files[i];

                await libav.mkreadaheadfile(`input${i}`, file);
                ffInputs.push('-i', `input${i}`);
            }

            await libav.mkwriterdev(outputName);
            await libav.mkwriterdev('progress.txt');

            const totalInputSize = files.reduce((a, b) => a + b.size, 0);
            const storage = await Storage.init(totalInputSize);

            libav.onwrite = async (name, pos, data) => {
                if (name === 'progress.txt') {
                    try {
                        return this.#emitProgress(data);
                    } catch (e) {
                        console.error(e);
                    }
                } else if (name !== outputName) return;

                await storage.write(data, pos);
            };

            await libav.ffmpeg([
                '-nostdin', '-y',
                '-loglevel', 'error',
                '-progress', 'progress.txt',
                '-threads', this.concurrency.toString(),
                ...ffInputs,
                ...args,
                outputName
            ]);

            const file = Storage.retype(await storage.res(), output.type);
            if (file.size === 0) return;

            return file;
        } finally {
            try {
                await libav.unlink(outputName);
                await libav.unlink('progress.txt');

                await Promise.allSettled(
                    files.map((_, i) =>
                        libav.unlinkreadaheadfile(`input${i}`)
                    ));
            } catch { /* catch & ignore */ }
        }
    }

    #emitProgress(data: Uint8Array | Int8Array) {
        if (!this.onProgress) return;

        const copy = new Uint8Array(data);
        const text = new TextDecoder().decode(copy);
        const entries = Object.fromEntries(
            text.split('\n')
                .filter(a => a)
                .map(a => a.split('='))
        );

        const status: FFmpegProgressStatus = (() => {
            const { progress } = entries;

            if (progress === 'continue' || progress === 'end') {
                return progress;
            }

            return "unknown";
        })();

        const tryNumber = (str: string, transform?: (n: number) => number) => {
            if (str) {
                const num = Number(str);
                if (!isNaN(num)) {
                    if (transform)
                        return transform(num);
                    else
                        return num;
                }
            }
        }

        const progress: FFmpegProgressEvent = {
            status,
            frame: tryNumber(entries.frame),
            fps: tryNumber(entries.fps),
            total_size: tryNumber(entries.total_size),
            dup_frames: tryNumber(entries.dup_frames),
            drop_frames: tryNumber(entries.drop_frames),
            speed: tryNumber(entries.speed?.trim()?.replace('x', '')),
            out_time_sec: tryNumber(entries.out_time_us, n => Math.floor(n / 1e6))
        };

        this.onProgress(progress);
    }
}