FFMpegLoader.cs 15 KB

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