Repository navigation
Expand file tree
/
Copy pathFFmpegCls.tsx
More file actions
80 lines (72 loc) · 2.59 KB
/
Copy pathFFmpegCls.tsx
File metadata and controls
80 lines (72 loc) · 2.59 KB
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
import { FFmpeg as FFmpegCore } from "@ffmpeg/ffmpeg";
import { toBlobURL, fetchFile } from "@ffmpeg/util";
class ffmpegCls {
private ffmpeg: FFmpegCore;
loaded: boolean;
on: Function;
off:Function;
constructor() {
this.ffmpeg = new FFmpegCore();
this.loaded = false;
this.on = this.ffmpeg.on.bind(this.ffmpeg)
this.off = this.ffmpeg.off.bind(this.ffmpeg)
}
/*
* terminate the ffmpeg and restart it.
*/
async reload(){
if (this.loaded){this.ffmpeg.terminate();this.loaded = false}
return await this.load()
}
/**
* Load the FFmpeg library.
*/
async load(): Promise<void> {
let is_firefox = navigator.userAgent.toLowerCase().includes('firefox');
let core_path = is_firefox ? "core-mt" : "core"
// const base_url = `./js/${core_path}`
const base_url = `https://unpkg.com/@ffmpeg/${core_path}@0.12.2/dist/umd`
console.log("loading ffmpeg from",core_path,"is_firefox:",is_firefox)
// the documention say "toBlobURL is used to bypass CORS issue, urls with the same
// domain can be used directly.", but ffmpeg.wasm crash without toBlobURL for some reason
let coreblob = await toBlobURL(
`${base_url}/ffmpeg-core.js`,
"text/javascript",
)
let wasmblob = await toBlobURL(
`${base_url}/ffmpeg-core.wasm`,
"application/wasm",
)
let workerblob = undefined;
if (is_firefox) {
workerblob = await toBlobURL(
`${base_url}/ffmpeg-core.worker.js`, "text/javascript"
);
}
await this.ffmpeg.load({
coreURL: coreblob,
wasmURL: wasmblob,
workerURL: workerblob
});
this.loaded = true;
}
/**
* Execute an FFmpeg command and return the output as a File with Blob URL.
* @param inputFile - Input file path or URL.
* @param args - Array of FFmpeg arguments.
* @returns a file with Blob URL of the output.
*/
async exec(inputFileName: string, OutputMimeType: string, inputBlob: string, outputFile: string, args: string[]): Promise<File> {
if (!this.loaded) {
throw new Error("FFmpeg not loaded yet. Call the 'load' method.");
}
await this.ffmpeg.writeFile(inputFileName, await fetchFile(inputBlob));
const commandList = ["-hide_banner", "-i", inputFileName, ...args, outputFile].filter(el => (el !== '')) // remove empty strings
console.log(`running ffmpeg command [${commandList}]`)
await this.ffmpeg.exec(commandList);
const data = await this.ffmpeg.readFile(outputFile);
const blob = new Blob([data], { type: OutputMimeType });
return new File([blob], outputFile, { type: OutputMimeType })
}
}
export default ffmpegCls;