FFMpegLoader.cs 16 KB

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