FFMpegLoader.cs 16 KB

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