From 748653528674583d8116315ab45c73973ffa1890 Mon Sep 17 00:00:00 2001 From: flt6 <1404262047@qq.com> Date: Sun, 4 Feb 2024 23:57:29 +0800 Subject: [PATCH] process_video --- process_video/process.cpp | 105 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 process_video/process.cpp diff --git a/process_video/process.cpp b/process_video/process.cpp new file mode 100644 index 0000000..2a06141 --- /dev/null +++ b/process_video/process.cpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + const std::string DEVNULL = "NUL"; +#else + const std::string DEVNULL = "/dev/null"; +#endif + + +using namespace std; +namespace fs = std::filesystem; + +void runCommand(const string& command,const bool output=false) { + int ret; + if (!output) + ret = system((command + " > " + DEVNULL + " 2>&1").c_str()); + else + ret = system(command.c_str()); + if (ret != 0) { + cerr << "Command '" << command << "' failed." << endl; + exit(-1); + } +} + +int main(int argc, char* argv[]) { + try { + runCommand("ffprobe -version"); + runCommand("ffmpeg -version"); + } catch (const exception& e) { + cerr << "'ffmpeg' or 'ffprobe' not installed." << endl; + exit(-1); + } + + fs::path src; + if (argc == 3) { + string arg1 = argv[1]; + if (arg1.front() == '"' && arg1.back() == '"') + src = fs::path(string(argv[2]).substr(1, string(argv[2]).size() - 2)); + else + src = fs::path(argv[2]); + } else { + src = fs::path("/.NOT_EXIST_FILE."); + } + + while (!fs::exists(src)) { + string ipt; + cout << "Enter the path to the source file: "; + getline(cin, ipt); + if (ipt.front() == '"' && ipt.back() == '"') + src = fs::path(ipt.substr(1, ipt.size() - 2)); + else + src = fs::path(ipt); + } + + string targetTime; + while (true) { + cout << "Enter the target time: "; + getline(cin, targetTime); + if (all_of(targetTime.begin(), targetTime.end(), ::isdigit)) + break; + } + float targetTimeFloat = stof(targetTime); + + string outputFile; + cout << "Output file (Default out.mp4): "; + getline(cin, outputFile); + if (outputFile.empty()) outputFile = "out.mp4"; + + string extraCMD; + cout << "Extra cmd: "; + getline(cin, extraCMD); + + stringstream command; + command << "ffprobe -i " << src << " -show_entries format=duration -v quiet -of csv=p=0"; + FILE* pipe = popen(command.str().c_str(), "r"); + if (!pipe) { + cerr << "Error while invoking ffprobe." << endl; + return -1; + } + float srcTime; + if (fscanf(pipe, "%f", &srcTime) != 1) { + cerr << "Error reading output from ffprobe." << endl; + pclose(pipe); + return -1; + } + pclose(pipe); + + float rate = targetTimeFloat / srcTime; + + command.str(""); + command << "ffmpeg -hide_banner -t " << srcTime << " -i " << src << " -vf setpts=PTS*" << rate + << " -r 30 -t " << targetTimeFloat << " " << extraCMD << " " << outputFile; + runCommand(command.str(),true); + + return 0; +}