FFMpegLoader.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. return;
  183. }
  184. foreach (var url in downloadinfo.DownloadUrls)
  185. {
  186. progress.Report(0);
  187. try
  188. {
  189. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  190. {
  191. Url = url,
  192. CancellationToken = CancellationToken.None,
  193. Progress = progress
  194. }).ConfigureAwait(false);
  195. ExtractFFMpeg(downloadinfo, tempFile, directory);
  196. return;
  197. }
  198. catch (Exception ex)
  199. {
  200. _logger.ErrorException("Error downloading {0}", ex, url);
  201. }
  202. }
  203. if (downloadinfo.DownloadUrls.Length == 0)
  204. {
  205. throw new ApplicationException("ffmpeg unvailable. Please install it and start the server with two command line arguments: -ffmpeg \"{PATH}\" and -ffprobe \"{PATH}\"");
  206. }
  207. throw new ApplicationException("Unable to download required components. Please try again later.");
  208. }
  209. private void ExtractFFMpeg(FFMpegInstallInfo downloadinfo, string tempFile, string targetFolder)
  210. {
  211. _logger.Info("Extracting ffmpeg from {0}", tempFile);
  212. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  213. _fileSystem.CreateDirectory(tempFolder);
  214. try
  215. {
  216. ExtractArchive(downloadinfo, tempFile, tempFolder);
  217. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories)
  218. .ToList();
  219. foreach (var file in files.Where(i =>
  220. {
  221. var filename = Path.GetFileName(i);
  222. return
  223. string.Equals(filename, downloadinfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  224. string.Equals(filename, downloadinfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  225. }))
  226. {
  227. var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
  228. _fileSystem.CopyFile(file, targetFile, true);
  229. SetFilePermissions(targetFile);
  230. }
  231. }
  232. finally
  233. {
  234. DeleteFile(tempFile);
  235. }
  236. }
  237. private void SetFilePermissions(string path)
  238. {
  239. // Linux: File permission to 666, and user's execute bit
  240. if (_environment.OperatingSystem == OperatingSystem.Bsd || _environment.OperatingSystem == OperatingSystem.Linux || _environment.OperatingSystem == OperatingSystem.Osx)
  241. {
  242. _logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path);
  243. Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH);
  244. }
  245. }
  246. private void ExtractArchive(FFMpegInstallInfo downloadinfo, string archivePath, string targetPath)
  247. {
  248. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  249. if (string.Equals(downloadinfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  250. {
  251. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  252. }
  253. else if (string.Equals(downloadinfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  254. {
  255. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  256. }
  257. }
  258. private void Extract7zArchive(string archivePath, string targetPath)
  259. {
  260. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  261. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  262. }
  263. private void DeleteFile(string path)
  264. {
  265. try
  266. {
  267. _fileSystem.DeleteFile(path);
  268. }
  269. catch (IOException ex)
  270. {
  271. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  272. }
  273. }
  274. /// <summary>
  275. /// Extracts the fonts.
  276. /// </summary>
  277. /// <param name="targetPath">The target path.</param>
  278. /// <returns>Task.</returns>
  279. private async Task DownloadFonts(string targetPath)
  280. {
  281. try
  282. {
  283. var fontsDirectory = Path.Combine(targetPath, "fonts");
  284. _fileSystem.CreateDirectory(fontsDirectory);
  285. const string fontFilename = "ARIALUNI.TTF";
  286. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  287. if (_fileSystem.FileExists(fontFile))
  288. {
  289. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  290. }
  291. else
  292. {
  293. // Kick this off, but no need to wait on it
  294. Task.Run(async () =>
  295. {
  296. await DownloadFontFile(fontsDirectory, fontFilename, new Progress<double>()).ConfigureAwait(false);
  297. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  298. });
  299. }
  300. }
  301. catch (HttpException ex)
  302. {
  303. // Don't let the server crash because of this
  304. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  305. }
  306. catch (Exception ex)
  307. {
  308. // Don't let the server crash because of this
  309. _logger.ErrorException("Error writing ffmpeg font files", ex);
  310. }
  311. }
  312. /// <summary>
  313. /// Downloads the font file.
  314. /// </summary>
  315. /// <param name="fontsDirectory">The fonts directory.</param>
  316. /// <param name="fontFilename">The font filename.</param>
  317. /// <returns>Task.</returns>
  318. private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
  319. {
  320. var existingFile = Directory
  321. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  322. .FirstOrDefault();
  323. if (existingFile != null)
  324. {
  325. try
  326. {
  327. _fileSystem.CopyFile(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  328. return;
  329. }
  330. catch (IOException ex)
  331. {
  332. // Log this, but don't let it fail the operation
  333. _logger.ErrorException("Error copying file", ex);
  334. }
  335. }
  336. string tempFile = null;
  337. foreach (var url in _fontUrls)
  338. {
  339. progress.Report(0);
  340. try
  341. {
  342. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  343. {
  344. Url = url,
  345. Progress = progress
  346. }).ConfigureAwait(false);
  347. break;
  348. }
  349. catch (Exception ex)
  350. {
  351. // The core can function without the font file, so handle this
  352. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  353. }
  354. }
  355. if (string.IsNullOrEmpty(tempFile))
  356. {
  357. return;
  358. }
  359. Extract7zArchive(tempFile, fontsDirectory);
  360. try
  361. {
  362. _fileSystem.DeleteFile(tempFile);
  363. }
  364. catch (IOException ex)
  365. {
  366. // Log this, but don't let it fail the operation
  367. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  368. }
  369. }
  370. /// <summary>
  371. /// Writes the font config file.
  372. /// </summary>
  373. /// <param name="fontsDirectory">The fonts directory.</param>
  374. /// <returns>Task.</returns>
  375. private async Task WriteFontConfigFile(string fontsDirectory)
  376. {
  377. const string fontConfigFilename = "fonts.conf";
  378. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  379. if (!_fileSystem.FileExists(fontConfigFile))
  380. {
  381. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  382. var bytes = Encoding.UTF8.GetBytes(contents);
  383. using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  384. FileShare.Read, true))
  385. {
  386. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  387. }
  388. }
  389. }
  390. }
  391. }