ExternalTools.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include "ExternalTools.h"
  16. #include "installer/extractors/MovieCamera.h"
  17. #include <QtCore/QProcess>
  18. #include <QtCore/QString>
  19. #include <QtCore/QStringList>
  20. #include <algorithm>
  21. #include <boost/filesystem.hpp>
  22. #include <cctype>
  23. #include <cstdio>
  24. #include <fstream>
  25. #include <cstdlib>
  26. namespace fs = boost::filesystem;
  27. namespace{
  28. std::string Lower(std::string text){
  29. std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c){return std::tolower(c);});
  30. return text;
  31. }
  32. std::vector<std::string> Split(const std::string& text, char separator){
  33. std::vector<std::string> parts;
  34. std::string current;
  35. for (char c : text){
  36. if (c == separator){
  37. parts.push_back(current);
  38. current.clear();
  39. }
  40. else current += c;
  41. }
  42. parts.push_back(current);
  43. return parts;
  44. }
  45. /**
  46. * Checks that a path is a file that can be run.
  47. */
  48. bool IsExecutable(const std::string& path, const ExternalTools::Environment& env){
  49. boost::system::error_code ec;
  50. if (!fs::is_regular_file(path, ec)) return false;
  51. if (!env.windows){
  52. // The permission to run it, for the owner, the group or others.
  53. const fs::perms permissions = fs::status(path, ec).permissions();
  54. return !ec && (permissions & (fs::owner_exe | fs::group_exe | fs::others_exe)) != 0;
  55. }
  56. // In Windows a file is executable by its extension.
  57. const std::string extension = Lower(fs::path(path).extension().string());
  58. for (const std::string& allowed : Split(Lower(env.pathext), ';')){
  59. if (!allowed.empty() && allowed == extension) return true;
  60. }
  61. return false;
  62. }
  63. /**
  64. * Gets the files in a directory that could be a program with a name.
  65. */
  66. std::vector<std::string> InDirectory(
  67. const std::string& directory, const std::string& name, const ExternalTools::Environment& env
  68. ){
  69. std::vector<std::string> found;
  70. if (directory.empty()) return found;
  71. const fs::path base = fs::path(directory) / name;
  72. if (!env.windows){
  73. if (IsExecutable(base.string(), env)) found.push_back(base.string());
  74. return found;
  75. }
  76. // The name with each of the executable extensions, in the order of PATHEXT.
  77. for (const std::string& extension : Split(env.pathext, ';')){
  78. if (extension.empty()) continue;
  79. const std::string candidate = base.string() + extension;
  80. if (IsExecutable(candidate, env)) found.push_back(candidate);
  81. // Windows file names are case insensitive: the file may be called "FFMPEG.EXE".
  82. else{
  83. boost::system::error_code ec;
  84. for (fs::directory_iterator it(directory, ec), end; !ec && it != end; it.increment(ec)){
  85. const std::string file = it->path().filename().string();
  86. if (Lower(file) == Lower(name + extension) && IsExecutable(it->path().string(), env)){
  87. found.push_back(it->path().string());
  88. break;
  89. }
  90. }
  91. }
  92. }
  93. return found;
  94. }
  95. std::string FirstLine(const std::string& text){
  96. const std::size_t end = text.find_first_of("\r\n");
  97. return end == std::string::npos ? text : text.substr(0, end);
  98. }
  99. /**
  100. * Runs the candidates of a program until one is usable.
  101. */
  102. ExternalTools::Tool FindTool(
  103. const std::string& name, const std::string& saved, const ExternalTools::Locations& locations,
  104. const ExternalTools::Environment& env, ExternalTools::Tool (*probe)(const std::string&)
  105. ){
  106. const std::vector<std::string> candidates
  107. = ExternalTools::Candidates(name, saved, locations.directories, env);
  108. ExternalTools::Tool first_failure;
  109. for (const std::string& candidate : candidates){
  110. ExternalTools::Tool tool = probe(candidate);
  111. if (tool.usable) return tool;
  112. if (first_failure.path.empty()) first_failure = tool;
  113. }
  114. if (!first_failure.path.empty()) return first_failure;
  115. ExternalTools::Tool missing;
  116. missing.problem = name + " was not found";
  117. return missing;
  118. }
  119. /**
  120. * Gets the text of a failed run for a message.
  121. */
  122. std::string Describe(const ExternalTools::RunResult& result){
  123. if (!result.started) return "it could not be started";
  124. if (!result.finished) return "it did not finish";
  125. std::string text = "exit code " + std::to_string(result.exit_code);
  126. const std::string line = FirstLine(result.output);
  127. if (!line.empty()) text += ": " + line;
  128. return text;
  129. }
  130. }
  131. namespace ExternalTools{
  132. Environment Environment::FromSystem(){
  133. Environment env;
  134. const char* path = std::getenv("PATH");
  135. const char* pathext = std::getenv("PATHEXT");
  136. env.path = path ? path : "";
  137. #ifdef _WIN32
  138. env.windows = true;
  139. env.pathext = pathext ? pathext : ".COM;.EXE;.BAT;.CMD";
  140. #else
  141. env.windows = false;
  142. env.pathext = pathext ? pathext : "";
  143. #endif
  144. return env;
  145. }
  146. Locations& CurrentLocations(){
  147. static Locations locations;
  148. return locations;
  149. }
  150. std::vector<std::string> Candidates(
  151. const std::string& name, const std::string& saved_path, const std::vector<std::string>& directories,
  152. const Environment& env
  153. ){
  154. std::vector<std::string> candidates;
  155. const auto add = [&candidates](const std::string& path){
  156. if (std::find(candidates.begin(), candidates.end(), path) == candidates.end()) candidates.push_back(path);
  157. };
  158. if (!saved_path.empty() && IsExecutable(saved_path, env)) add(saved_path);
  159. for (const std::string& directory : directories)
  160. for (const std::string& file : InDirectory(directory, name, env)) add(file);
  161. for (const std::string& directory : Split(env.path, env.windows ? ';' : ':')){
  162. // Empty entries mean "the current directory", and searching there is a security risk.
  163. if (directory.empty() || !fs::path(directory).is_absolute()) continue;
  164. for (const std::string& file : InDirectory(directory, name, env)) add(file);
  165. }
  166. return candidates;
  167. }
  168. std::string ShortVersion(const Tool& tool){
  169. const std::string lower = Lower(tool.version);
  170. const std::size_t word = lower.find("version ");
  171. if (word == std::string::npos) return tool.version;
  172. const std::size_t start = word + 8;
  173. const std::size_t end = tool.version.find_first_of(" \t", start);
  174. return tool.version.substr(start, end == std::string::npos ? std::string::npos : end - start);
  175. }
  176. RunResult Run(const std::string& program, const std::vector<std::string>& arguments, int timeout_ms){
  177. RunResult result;
  178. QStringList list;
  179. for (const std::string& argument : arguments) list << QString::fromStdString(argument);
  180. QProcess process;
  181. process.setProcessChannelMode(QProcess::MergedChannels);
  182. process.start(QString::fromStdString(program), list);
  183. result.started = process.waitForStarted(10000);
  184. if (!result.started) return result;
  185. result.finished = process.waitForFinished(timeout_ms);
  186. if (!result.finished){
  187. process.kill();
  188. process.waitForFinished(5000);
  189. }
  190. result.output = QString::fromLocal8Bit(process.readAll()).toStdString();
  191. result.exit_code = process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
  192. return result;
  193. }
  194. Tool ProbeFfmpeg(const std::string& path){
  195. Tool tool;
  196. tool.path = path;
  197. const RunResult version = Run(path, {"-version"}, 15000);
  198. if (!version.started || !version.finished || version.exit_code != 0
  199. || Lower(version.output).find("ffmpeg version") == std::string::npos){
  200. tool.problem = path + " is not FFmpeg (" + Describe(version) + ")";
  201. return tool;
  202. }
  203. tool.version = FirstLine(version.output);
  204. // The music and the sounds are ogg files, which need the Vorbis encoder.
  205. const RunResult encoders = Run(path, {"-hide_banner", "-encoders"}, 15000);
  206. if (encoders.output.find("libvorbis") == std::string::npos){
  207. tool.problem = tool.version + " can't write ogg files: it was built without libvorbis";
  208. return tool;
  209. }
  210. tool.usable = true;
  211. return tool;
  212. }
  213. Tool ProbeTimidity(const std::string& path){
  214. Tool tool;
  215. tool.path = path;
  216. const RunResult version = Run(path, {"-v"}, 15000);
  217. if (!version.started || !version.finished || Lower(version.output).find("timidity") == std::string::npos){
  218. tool.problem = path + " is not TiMidity (" + Describe(version) + ")";
  219. return tool;
  220. }
  221. tool.version = FirstLine(version.output);
  222. tool.usable = true;
  223. return tool;
  224. }
  225. Tool FindFfmpeg(const Locations& locations, const Environment& env){
  226. return FindTool("ffmpeg", locations.ffmpeg, locations, env, ProbeFfmpeg);
  227. }
  228. Tool FindTimidity(const Locations& locations, const Environment& env){
  229. return FindTool("timidity", locations.timidity, locations, env, ProbeTimidity);
  230. }
  231. std::vector<std::string> FfmpegArguments(const std::string& input, const std::string& output){
  232. // Bit exact: without it the Ogg stream serial number is random, so every installation writes different
  233. // files.
  234. return {
  235. "-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-fflags", "+bitexact", "-flags:a", "+bitexact",
  236. output
  237. };
  238. }
  239. std::vector<std::string> FfmpegStdinArguments(const std::string& output){
  240. return FfmpegArguments("-", output);
  241. }
  242. std::vector<std::string> FfmpegMidiArguments(const std::string& output){
  243. // Below -50 dB is silence, and 0.3 seconds of it are kept so the end doesn't sound cut.
  244. return {
  245. "-hide_banner", "-loglevel", "panic", "-y", "-i", "-", "-af",
  246. "areverse,silenceremove=start_periods=1:start_duration=0:start_threshold=-50dB"
  247. ":start_silence=0.3:detection=peak,areverse", "-fflags", "+bitexact", "-flags:a", "+bitexact",
  248. output
  249. };
  250. }
  251. std::vector<std::string> TimidityArguments(const std::string& midi){
  252. return {"--quiet=3", midi, "-Ow", "-o", "-"};
  253. }
  254. namespace{
  255. std::string FrameName(const int frame){
  256. char number[16];
  257. snprintf(number, sizeof(number), "%05d", frame);
  258. return std::string(number) + ".jpg";
  259. }
  260. }
  261. bool ConvertToOgg(
  262. const std::string& ffmpeg, const std::string& input, const std::string& output, std::string* error
  263. ){
  264. const RunResult result = Run(ffmpeg, FfmpegArguments(input, output), -1);
  265. boost::system::error_code ec;
  266. if (result.started && result.finished && result.exit_code == 0 && fs::file_size(output, ec) > 0 && !ec)
  267. return true;
  268. fs::remove(output, ec);
  269. if (error) *error = "ffmpeg failed: " + Describe(result);
  270. return false;
  271. }
  272. bool ConvertMovie(
  273. const std::string& ffmpeg, const std::string& input, const std::string& directory,
  274. const std::string& name, const std::vector<uint8_t>& camera, std::string* error
  275. ){
  276. boost::system::error_code ec;
  277. fs::remove_all(directory, ec);
  278. fs::create_directories(directory, ec);
  279. // The movies of the original game have 15 frames per second.
  280. const float frames_per_second = 15.0f;
  281. const RunResult frames = Run(
  282. ffmpeg,
  283. {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-an", "-q:v", "3",
  284. "-start_number", "0", directory + "/%05d.jpg"},
  285. -1
  286. );
  287. int frame_count = 0;
  288. while (fs::exists(directory + "/" + FrameName(frame_count), ec)) ++ frame_count;
  289. if (!frames.started || !frames.finished || frames.exit_code != 0 || frame_count == 0){
  290. fs::remove_all(directory, ec);
  291. if (error) *error = "ffmpeg failed: " + Describe(frames);
  292. return false;
  293. }
  294. // The sound. Some movies have none.
  295. const std::string ogg = directory + "/" + name + ".ogg";
  296. const RunResult sound = Run(
  297. ffmpeg,
  298. {"-hide_banner", "-loglevel", "panic", "-y", "-i", input, "-vn", "-fflags", "+bitexact", "-flags:a",
  299. "+bitexact", ogg},
  300. -1
  301. );
  302. if (!sound.started || !sound.finished || sound.exit_code != 0 || fs::file_size(ogg, ec) == 0 || ec)
  303. fs::remove(ogg, ec);
  304. std::ofstream info(directory + "/movie.xml");
  305. info << "<movie frames=\"" << frame_count << "\" fps=\"" << frames_per_second << "\"";
  306. const int first_camera_frame = MovieCamera::FirstCameraFrame(camera);
  307. if (first_camera_frame >= 0){
  308. info << " camera_frame=\"" << first_camera_frame << "\"";
  309. std::ofstream camera_file(directory + "/camera.cam", std::ios::binary);
  310. camera_file.write(reinterpret_cast<const char*>(camera.data()), camera.size());
  311. }
  312. info << "/>\n";
  313. return true;
  314. }
  315. namespace{
  316. /**
  317. * Renders a MIDI with TiMidity and encodes it with ffmpeg, without a shell.
  318. */
  319. bool RenderMidi(
  320. const std::string& timidity, const std::string& ffmpeg,
  321. const std::vector<std::string>& ffmpeg_arguments, const std::string& midi,
  322. const std::string& output, std::string* error
  323. ){
  324. QProcess render;
  325. QProcess encode;
  326. // render | encode, without a shell.
  327. render.setStandardOutputProcess(&encode);
  328. render.setStandardErrorFile(QProcess::nullDevice());
  329. encode.setStandardOutputFile(QProcess::nullDevice());
  330. encode.setStandardErrorFile(QProcess::nullDevice());
  331. const auto to_list = [](const std::vector<std::string>& arguments){
  332. QStringList list;
  333. for (const std::string& argument : arguments) list << QString::fromStdString(argument);
  334. return list;
  335. };
  336. // The source is started first, as Qt documents for piped processes.
  337. render.start(QString::fromStdString(timidity), to_list(TimidityArguments(midi)));
  338. encode.start(QString::fromStdString(ffmpeg), to_list(ffmpeg_arguments));
  339. const bool render_started = render.waitForStarted(10000);
  340. const bool encode_started = encode.waitForStarted(10000);
  341. bool ok = false;
  342. std::string reason;
  343. if (!render_started || !encode_started){
  344. render.kill();
  345. encode.kill();
  346. render.waitForFinished(2000);
  347. encode.waitForFinished(2000);
  348. reason = std::string("could not start ") + (!render_started ? "timidity" : "ffmpeg");
  349. }
  350. else{
  351. render.waitForFinished(-1);
  352. encode.waitForFinished(-1);
  353. if (render.exitStatus() != QProcess::NormalExit || render.exitCode() != 0)
  354. reason = "timidity failed with exit code " + std::to_string(render.exitCode());
  355. else if (encode.exitStatus() != QProcess::NormalExit || encode.exitCode() != 0)
  356. reason = "ffmpeg failed with exit code " + std::to_string(encode.exitCode());
  357. else ok = true;
  358. }
  359. boost::system::error_code ec;
  360. if (ok && !(fs::file_size(output, ec) > 0 && !ec)){
  361. ok = false;
  362. reason = "no audio was produced";
  363. }
  364. if (!ok){
  365. fs::remove(output, ec);
  366. if (error) *error = reason;
  367. }
  368. return ok;
  369. }
  370. }
  371. bool ConvertMidiToOgg(
  372. const std::string& timidity, const std::string& ffmpeg, const std::string& midi, const std::string& output,
  373. std::string* error
  374. ){
  375. // The silence at the end is removed. If that leaves nothing (a track that is all silence)
  376. // the track is encoded as it is.
  377. if (RenderMidi(timidity, ffmpeg, FfmpegMidiArguments(output), midi, output, error)) return true;
  378. return RenderMidi(timidity, ffmpeg, FfmpegStdinArguments(output), midi, output, error);
  379. }
  380. }