FFMpegDownloader.cs 16 KB

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