-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
110 lines (96 loc) · 3.06 KB
/
index.js
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
const { spawn } = require('child_process');
const { statSync, existsSync } = require('fs');
const { readdir, copyFile, unlink } = require('fs/promises');
const { exit } = require('process');
const { resolve, dirname, join } = require('path');
const FFMPEG_REGEX = /frame=([0-9]+)fps=((?:[0-9]+)|(?:[0-9]+\.[0-9]+))q=(-*[0-9]+\.[0-9]+)size=((?:[0-9]+[a-zA-Z]{2})|N\/A)time=(-*[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{2})bitrate=((?:-*[0-9]+\.[0-9]+)|N\/A).*speed=([0-9]+\.[0-9]+)x/;
const DIRECTORY = dirname(process.argv[0]);
const TEMP_FILE = join(DIRECTORY, 'temp.mp4');
if (process.argv.length == 2) {
console.log("no args")
exit(0);
}
async function main() {
for(let i = 2; i < process.argv.length; i++){
let currentArg = process.argv[i];
if (!existsSync(currentArg)) {
console.log(`"${currentArg}" - file/directory not found`);
continue;
}
let isDir = statSync(currentArg).isDirectory();
if (isDir) {
for await (let fileName of getFiles(currentArg)) {
await convertMedia(fileName);
}
} else {
await convertMedia(currentArg);
}
}
console.log("all done");
setTimeout(() => {}, 5000);
//process.stdin.resume();
}
main();
async function convertMedia(fileName){
return new Promise(async (res, rej) => {
console.log(fileName);
let code = await optimiseMedia(fileName);
if (code != 0) {
console.log("an error occured when reading file, probably ffmpeg doesn't understand format");
return res();
}
console.log("done!");
await moveMedia(fileName);
res();
});
}
function optimiseMedia(path) {
//stuff
return new Promise((res) => {
const execution = spawn(
'ffmpeg',
[
'-y',
'-i', path,
'-map', '0',
'-c:v', 'libx264',
'-crf:v', '18',
'-preset:v', 'slow',
'-c:a', 'libopus',
'-b:a', '128k',
'-ac', '2',
TEMP_FILE
],
{
stdio: [
'ignore',
'ignore',
'pipe'
]
}
);
execution.stderr.on('data', data => {
let stuff = FFMPEG_REGEX.exec(data.toString().replace(/\s/g, ''));
if(stuff == null) return;
process.stdout.write(`\rtime: ${stuff[5]} - fps: ${stuff[2]} - totalsize: ${stuff[4]} `);
});
execution.on('exit', code => {
res(code);
})
});
}
async function moveMedia(path) {
await copyFile(TEMP_FILE, path);
await unlink(TEMP_FILE);
}
async function* getFiles(dir) {
const dirents = await readdir(dir, { withFileTypes: true });
for (const dirent of dirents) {
const res = resolve(dir, dirent.name);
if (dirent.isDirectory()) {
yield* getFiles(res);
} else {
yield res;
}
}
}