FFMpegDownloader.cs 17 KB

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