FFMpegDownloader.cs 16 KB

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