-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8mb.js
64 lines (57 loc) · 2.11 KB
/
8mb.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
const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const path = require('path');
function getFileSizeInMB(filePath) {
const stats = fs.statSync(filePath);
return stats.size / (1024 * 1024);
}
async function compressVideo(inputPath, outputPath, targetSizeMB) {
const targetBitrate = await calculateBitrate(inputPath, targetSizeMB, 0.85);
return new Promise((resolve, reject) => {
ffmpeg(inputPath)
.outputOptions([
`-b:v ${targetBitrate}k`,
`-bufsize ${targetBitrate}k`,
`-maxrate ${targetBitrate}k`,
`-preset slow`,
`-movflags +faststart`
])
.videoCodec('libx264')
.format('mp4')
.on('end', function () {
console.log('Compression finished.');
resolve();
})
.on('error', function (err) {
console.error('Error:', err);
reject(err);
})
.save(outputPath);
});
}
async function calculateBitrate(inputPath, targetSizeMB, safetyFactor = 1) {
return new Promise((resolve, reject) => {
ffmpeg.ffprobe(inputPath, function (err, metadata) {
if (err) {
reject(err);
return;
}
const duration = metadata.format.duration;
const targetSizeKilobits = targetSizeMB * 8 * 1024 * safetyFactor;
const targetBitrate = Math.floor(targetSizeKilobits / duration);
resolve(targetBitrate);
});
});
}
async function run() {
const inputVideoPath = path.join(__dirname, "/Local/Path/To/Video.mp4");
const baseName = path.basename(inputVideoPath, path.extname(inputVideoPath));
const outputVideoPath = path.join(__dirname, `Videos/${baseName} [8MB].mp4`);
try {
await compressVideo(inputVideoPath, outputVideoPath, 8);
console.log('Video compressed successfully.');
}catch (error) {
console.error('Failed to compress video:', error);
}
}
run();