-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
63 lines (51 loc) · 2.19 KB
/
main.cpp
File metadata and controls
63 lines (51 loc) · 2.19 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
#include <iostream>
#include <memory>
#include <cstdio>
#include <string>
#include <format>
#include <cstdlib>
std::string validUsageString = "compressor <input video file> <size in mb>";
/**
* execute a command and get the number output
* only for windows
*
* @param cmd The command to execute.
* @return The result of the command execution as a double.
*/
double getDoubleFrom(const char* cmd) {
std::unique_ptr<FILE, decltype(&_pclose)> pipe(_popen(cmd, "r"), &_pclose);
double result = 0.0;
fscanf(pipe.get(), "%lf", &result); // ignoring a lot of error handling here
return result;
}
int main(int argc, char* argv[]) {
std::string filename;
double targetSize;
if (argc != 3) {
std::cout << "Invalid inputs" << std::endl;
std::cout << validUsageString << std::endl;
return 1;
}
try{
filename = argv[1];
targetSize = std::stod(argv[2]); // in MB
if (targetSize <= 0) {
std::cout << "Invalid inputs" << std::endl;
std::cout << validUsageString << std::endl;
return 1;
}
}
catch(...){
std::cout << "Invalid inputs" << std::endl;
std::cout << validUsageString << std::endl;
return 1;
}
double audioBitrate = getDoubleFrom(std::format("ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate -of default=noprint_wrappers=1:nokey=1 \"{}\"", filename).c_str()) / 1000.0; // convert to kbps
double fileDuration = getDoubleFrom(std::format("ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"{}\"", filename).c_str()); // in seconds
double videoBitrate = ((targetSize * 8192.0) / fileDuration) - audioBitrate;
std::system(std::format("ffmpeg -y -i \"{}\" -c:v libx264 -b:v {}k -pass 1 -an -f null -", filename, static_cast<int>(videoBitrate)).c_str());
std::system(std::format("ffmpeg -y -i \"{}\" -c:v libx264 -b:v {}k -pass 2 -c:a aac -b:a {}k {}_compressed.mp4", filename, static_cast<int>(videoBitrate), static_cast<int>(audioBitrate), filename.substr(0, filename.find_last_of('.'))).c_str());
std::remove("ffmpeg2pass-0.log");
std::remove("ffmpeg2pass-0.log.mbtree");
return 0;
}