FFMpegLoader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Model.IO;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using Mono.Unix.Native;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using CommonIO;
  16. namespace MediaBrowser.Server.Startup.Common.FFMpeg
  17. {
  18. public class FFMpegLoader
  19. {
  20. private readonly IHttpClient _httpClient;
  21. private readonly IApplicationPaths _appPaths;
  22. private readonly ILogger _logger;
  23. private readonly IZipClient _zipClient;
  24. private readonly IFileSystem _fileSystem;
  25. private readonly NativeEnvironment _environment;
  26. private readonly FFMpegInstallInfo _ffmpegInstallInfo;
  27. private readonly string[] _fontUrls =
  28. {
  29. "https://github.com/MediaBrowser/MediaBrowser.Resources/raw/master/ffmpeg/ARIALUNI.7z"
  30. };
  31. public FFMpegLoader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient, IFileSystem fileSystem, NativeEnvironment environment, FFMpegInstallInfo ffmpegInstallInfo)
  32. {
  33. _logger = logger;
  34. _appPaths = appPaths;
  35. _httpClient = httpClient;
  36. _zipClient = zipClient;
  37. _fileSystem = fileSystem;
  38. _environment = environment;
  39. _ffmpegInstallInfo = ffmpegInstallInfo;
  40. }
  41. public async Task<FFMpegInfo> GetFFMpegInfo(NativeEnvironment environment, StartupOptions options, IProgress<double> progress)
  42. {
  43. var customffMpegPath = options.GetOption("-ffmpeg");
  44. var customffProbePath = options.GetOption("-ffprobe");
  45. if (!string.IsNullOrWhiteSpace(customffMpegPath) && !string.IsNullOrWhiteSpace(customffProbePath))
  46. {
  47. return new FFMpegInfo
  48. {
  49. ProbePath = customffProbePath,
  50. EncoderPath = customffMpegPath,
  51. Version = "external"
  52. };
  53. }
  54. var downloadInfo = _ffmpegInstallInfo;
  55. var version = downloadInfo.Version;
  56. if (string.Equals(version, "0", StringComparison.OrdinalIgnoreCase))
  57. {
  58. return new FFMpegInfo();
  59. }
  60. if (string.Equals(version, "path", StringComparison.OrdinalIgnoreCase))
  61. {
  62. return new FFMpegInfo
  63. {
  64. ProbePath = downloadInfo.FFProbeFilename,
  65. EncoderPath = downloadInfo.FFMpegFilename,
  66. Version = version
  67. };
  68. }
  69. var rootEncoderPath = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  70. var versionedDirectoryPath = Path.Combine(rootEncoderPath, version);
  71. var info = new FFMpegInfo
  72. {
  73. ProbePath = Path.Combine(versionedDirectoryPath, downloadInfo.FFProbeFilename),
  74. EncoderPath = Path.Combine(versionedDirectoryPath, downloadInfo.FFMpegFilename),
  75. Version = version
  76. };
  77. _fileSystem.CreateDirectory(versionedDirectoryPath);
  78. var excludeFromDeletions = new List<string> { versionedDirectoryPath };
  79. if (!_fileSystem.FileExists(info.ProbePath) || !_fileSystem.FileExists(info.EncoderPath))
  80. {
  81. // ffmpeg not present. See if there's an older version we can start with
  82. var existingVersion = GetExistingVersion(info, rootEncoderPath);
  83. // No older version. Need to download and block until complete
  84. if (existingVersion == null)
  85. {
  86. await DownloadFFMpeg(downloadInfo, versionedDirectoryPath, progress).ConfigureAwait(false);
  87. }
  88. else
  89. {
  90. info = existingVersion;
  91. versionedDirectoryPath = Path.GetDirectoryName(info.EncoderPath);
  92. excludeFromDeletions.Add(versionedDirectoryPath);
  93. }
  94. }
  95. if (_environment.OperatingSystem == OperatingSystem.Windows)
  96. {
  97. await DownloadFonts(versionedDirectoryPath).ConfigureAwait(false);
  98. }
  99. DeleteOlderFolders(Path.GetDirectoryName(versionedDirectoryPath), excludeFromDeletions);
  100. // Allow just one of these to be overridden, if desired.
  101. if (!string.IsNullOrWhiteSpace(customffMpegPath))
  102. {
  103. info.EncoderPath = customffMpegPath;
  104. }
  105. if (!string.IsNullOrWhiteSpace(customffProbePath))
  106. {
  107. info.EncoderPath = customffProbePath;
  108. }
  109. return info;
  110. }
  111. private void DeleteOlderFolders(string path, IEnumerable<string> excludeFolders)
  112. {
  113. var folders = Directory.GetDirectories(path)
  114. .Where(i => !excludeFolders.Contains(i, StringComparer.OrdinalIgnoreCase))
  115. .ToList();
  116. foreach (var folder in folders)
  117. {
  118. DeleteFolder(folder);
  119. }
  120. }
  121. private void DeleteFolder(string path)
  122. {
  123. try
  124. {
  125. _fileSystem.DeleteDirectory(path, true);
  126. }
  127. catch (Exception ex)
  128. {
  129. _logger.ErrorException("Error deleting {0}", ex, path);
  130. }
  131. }
  132. private FFMpegInfo GetExistingVersion(FFMpegInfo info, string rootEncoderPath)
  133. {
  134. var encoderFilename = Path.GetFileName(info.EncoderPath);
  135. var probeFilename = Path.GetFileName(info.ProbePath);
  136. foreach (var directory in Directory.EnumerateDirectories(rootEncoderPath, "*", SearchOption.TopDirectoryOnly)
  137. .ToList())
  138. {
  139. var allFiles = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).ToList();
  140. var encoder = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), encoderFilename, StringComparison.OrdinalIgnoreCase));
  141. var probe = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), probeFilename, StringComparison.OrdinalIgnoreCase));
  142. if (!string.IsNullOrWhiteSpace(encoder) &&
  143. !string.IsNullOrWhiteSpace(probe))
  144. {
  145. return new FFMpegInfo
  146. {
  147. EncoderPath = encoder,
  148. ProbePath = probe,
  149. Version = Path.GetFileName(Path.GetDirectoryName(probe))
  150. };
  151. }
  152. }
  153. return null;
  154. }
  155. private async Task DownloadFFMpeg(FFMpegInstallInfo downloadinfo, string directory, IProgress<double> progress)
  156. {
  157. foreach (var url in downloadinfo.DownloadUrls)
  158. {
  159. progress.Report(0);
  160. try
  161. {
  162. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  163. {
  164. Url = url,
  165. CancellationToken = CancellationToken.None,
  166. Progress = progress
  167. }).ConfigureAwait(false);
  168. ExtractFFMpeg(downloadinfo, tempFile, directory);
  169. return;
  170. }
  171. catch (Exception ex)
  172. {
  173. _logger.ErrorException("Error downloading {0}", ex, url);
  174. }
  175. }
  176. if (downloadinfo.DownloadUrls.Length == 0)
  177. {
  178. throw new ApplicationException("ffmpeg unvailable. Please install it and start the server with two command line arguments: -ffmpeg \"{PATH}\" and -ffprobe \"{PATH}\"");
  179. }
  180. throw new ApplicationException("Unable to download required components. Please try again later.");
  181. }
  182. private void ExtractFFMpeg(FFMpegInstallInfo downloadinfo, string tempFile, string targetFolder)
  183. {
  184. _logger.Info("Extracting ffmpeg from {0}", tempFile);
  185. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  186. _fileSystem.CreateDirectory(tempFolder);
  187. try
  188. {
  189. ExtractArchive(downloadinfo, tempFile, tempFolder);
  190. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories)
  191. .ToList();
  192. foreach (var file in files.Where(i =>
  193. {
  194. var filename = Path.GetFileName(i);
  195. return
  196. string.Equals(filename, downloadinfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  197. string.Equals(filename, downloadinfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  198. }))
  199. {
  200. var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
  201. _fileSystem.CopyFile(file, targetFile, true);
  202. SetFilePermissions(targetFile);
  203. }
  204. }
  205. finally
  206. {
  207. DeleteFile(tempFile);
  208. }
  209. }
  210. private void SetFilePermissions(string path)
  211. {
  212. // Linux: File permission to 666, and user's execute bit
  213. if (_environment.OperatingSystem == OperatingSystem.Bsd || _environment.OperatingSystem == OperatingSystem.Linux || _environment.OperatingSystem == OperatingSystem.Osx)
  214. {
  215. _logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path);
  216. Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH);
  217. }
  218. }
  219. private void ExtractArchive(FFMpegInstallInfo downloadinfo, string archivePath, string targetPath)
  220. {
  221. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  222. if (string.Equals(downloadinfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  223. {
  224. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  225. }
  226. else if (string.Equals(downloadinfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  227. {
  228. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  229. }
  230. }
  231. private void Extract7zArchive(string archivePath, string targetPath)
  232. {
  233. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  234. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  235. }
  236. private void DeleteFile(string path)
  237. {
  238. try
  239. {
  240. _fileSystem.DeleteFile(path);
  241. }
  242. catch (IOException ex)
  243. {
  244. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  245. }
  246. }
  247. /// <summary>
  248. /// Extracts the fonts.
  249. /// </summary>
  250. /// <param name="targetPath">The target path.</param>
  251. /// <returns>Task.</returns>
  252. private async Task DownloadFonts(string targetPath)
  253. {
  254. try
  255. {
  256. var fontsDirectory = Path.Combine(targetPath, "fonts");
  257. _fileSystem.CreateDirectory(fontsDirectory);
  258. const string fontFilename = "ARIALUNI.TTF";
  259. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  260. if (_fileSystem.FileExists(fontFile))
  261. {
  262. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  263. }
  264. else
  265. {
  266. // Kick this off, but no need to wait on it
  267. Task.Run(async () =>
  268. {
  269. await DownloadFontFile(fontsDirectory, fontFilename, new Progress<double>()).ConfigureAwait(false);
  270. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  271. });
  272. }
  273. }
  274. catch (HttpException ex)
  275. {
  276. // Don't let the server crash because of this
  277. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  278. }
  279. catch (Exception ex)
  280. {
  281. // Don't let the server crash because of this
  282. _logger.ErrorException("Error writing ffmpeg font files", ex);
  283. }
  284. }
  285. /// <summary>
  286. /// Downloads the font file.
  287. /// </summary>
  288. /// <param name="fontsDirectory">The fonts directory.</param>
  289. /// <param name="fontFilename">The font filename.</param>
  290. /// <returns>Task.</returns>
  291. private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
  292. {
  293. var existingFile = Directory
  294. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  295. .FirstOrDefault();
  296. if (existingFile != null)
  297. {
  298. try
  299. {
  300. _fileSystem.CopyFile(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  301. return;
  302. }
  303. catch (IOException ex)
  304. {
  305. // Log this, but don't let it fail the operation
  306. _logger.ErrorException("Error copying file", ex);
  307. }
  308. }
  309. string tempFile = null;
  310. foreach (var url in _fontUrls)
  311. {
  312. progress.Report(0);
  313. try
  314. {
  315. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  316. {
  317. Url = url,
  318. Progress = progress
  319. }).ConfigureAwait(false);
  320. break;
  321. }
  322. catch (Exception ex)
  323. {
  324. // The core can function without the font file, so handle this
  325. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  326. }
  327. }
  328. if (string.IsNullOrEmpty(tempFile))
  329. {
  330. return;
  331. }
  332. Extract7zArchive(tempFile, fontsDirectory);
  333. try
  334. {
  335. _fileSystem.DeleteFile(tempFile);
  336. }
  337. catch (IOException ex)
  338. {
  339. // Log this, but don't let it fail the operation
  340. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  341. }
  342. }
  343. /// <summary>
  344. /// Writes the font config file.
  345. /// </summary>
  346. /// <param name="fontsDirectory">The fonts directory.</param>
  347. /// <returns>Task.</returns>
  348. private async Task WriteFontConfigFile(string fontsDirectory)
  349. {
  350. const string fontConfigFilename = "fonts.conf";
  351. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  352. if (!_fileSystem.FileExists(fontConfigFile))
  353. {
  354. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  355. var bytes = Encoding.UTF8.GetBytes(contents);
  356. using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  357. FileShare.Read, true))
  358. {
  359. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  360. }
  361. }
  362. }
  363. }
  364. }