FFMpegLoader.cs 17 KB

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