FFMpegDownloader.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. 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. Directory.CreateDirectory(versionedDirectoryPath);
  71. var excludeFromDeletions = new List<string> { versionedDirectoryPath };
  72. if (!File.Exists(info.ProbePath) || !File.Exists(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. return info;
  95. }
  96. private void DeleteOlderFolders(string path, IEnumerable<string> excludeFolders)
  97. {
  98. var folders = Directory.GetDirectories(path)
  99. .Where(i => !excludeFolders.Contains(i, StringComparer.OrdinalIgnoreCase))
  100. .ToList();
  101. foreach (var folder in folders)
  102. {
  103. DeleteFolder(folder);
  104. }
  105. }
  106. private void DeleteFolder(string path)
  107. {
  108. try
  109. {
  110. _fileSystem.DeleteDirectory(path, true);
  111. }
  112. catch (Exception ex)
  113. {
  114. _logger.ErrorException("Error deleting {0}", ex, path);
  115. }
  116. }
  117. private FFMpegInfo GetExistingVersion(FFMpegInfo info, string rootEncoderPath)
  118. {
  119. var encoderFilename = Path.GetFileName(info.EncoderPath);
  120. var probeFilename = Path.GetFileName(info.ProbePath);
  121. foreach (var directory in Directory.EnumerateDirectories(rootEncoderPath, "*", SearchOption.TopDirectoryOnly)
  122. .ToList())
  123. {
  124. var allFiles = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).ToList();
  125. var encoder = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), encoderFilename, StringComparison.OrdinalIgnoreCase));
  126. var probe = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), probeFilename, StringComparison.OrdinalIgnoreCase));
  127. if (!string.IsNullOrWhiteSpace(encoder) &&
  128. !string.IsNullOrWhiteSpace(probe))
  129. {
  130. return new FFMpegInfo
  131. {
  132. EncoderPath = encoder,
  133. ProbePath = probe,
  134. Version = Path.GetFileName(Path.GetDirectoryName(probe))
  135. };
  136. }
  137. }
  138. return null;
  139. }
  140. private async void DownloadFFMpegInBackground(FFMpegDownloadInfo downloadinfo, string directory)
  141. {
  142. try
  143. {
  144. await DownloadFFMpeg(downloadinfo, directory, new Progress<double>()).ConfigureAwait(false);
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.ErrorException("Error downloading ffmpeg", ex);
  149. }
  150. }
  151. private async Task DownloadFFMpeg(FFMpegDownloadInfo downloadinfo, string directory, IProgress<double> progress)
  152. {
  153. foreach (var url in downloadinfo.DownloadUrls)
  154. {
  155. progress.Report(0);
  156. try
  157. {
  158. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  159. {
  160. Url = url,
  161. CancellationToken = CancellationToken.None,
  162. Progress = progress
  163. }).ConfigureAwait(false);
  164. ExtractFFMpeg(downloadinfo, tempFile, directory);
  165. return;
  166. }
  167. catch (Exception ex)
  168. {
  169. _logger.ErrorException("Error downloading {0}", ex, url);
  170. }
  171. }
  172. if (downloadinfo.DownloadUrls.Length == 0)
  173. {
  174. throw new ApplicationException("ffmpeg unvailable. Please install it and start the server with two command line arguments: -ffmpeg \"{PATH}\" and -ffprobe \"{PATH}\"");
  175. }
  176. else
  177. {
  178. throw new ApplicationException("Unable to download required components. Please try again later.");
  179. }
  180. }
  181. private void ExtractFFMpeg(FFMpegDownloadInfo downloadinfo, string tempFile, string targetFolder)
  182. {
  183. _logger.Info("Extracting ffmpeg from {0}", tempFile);
  184. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  185. Directory.CreateDirectory(tempFolder);
  186. try
  187. {
  188. ExtractArchive(downloadinfo, tempFile, tempFolder);
  189. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories)
  190. .ToList();
  191. foreach (var file in files.Where(i =>
  192. {
  193. var filename = Path.GetFileName(i);
  194. return
  195. string.Equals(filename, downloadinfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  196. string.Equals(filename, downloadinfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  197. }))
  198. {
  199. var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
  200. File.Copy(file, targetFile, true);
  201. SetFilePermissions(targetFile);
  202. }
  203. }
  204. finally
  205. {
  206. DeleteFile(tempFile);
  207. }
  208. }
  209. private void SetFilePermissions(string path)
  210. {
  211. // Linux: File permission to 666, and user's execute bit
  212. if (_environment.OperatingSystem == OperatingSystem.Bsd || _environment.OperatingSystem == OperatingSystem.Linux || _environment.OperatingSystem == OperatingSystem.Osx)
  213. {
  214. _logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path);
  215. Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH);
  216. }
  217. }
  218. private void ExtractArchive(FFMpegDownloadInfo downloadinfo, string archivePath, string targetPath)
  219. {
  220. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  221. if (string.Equals(downloadinfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  222. {
  223. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  224. }
  225. else if (string.Equals(downloadinfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  226. {
  227. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  228. }
  229. }
  230. private void Extract7zArchive(string archivePath, string targetPath)
  231. {
  232. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  233. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  234. }
  235. private void DeleteFile(string path)
  236. {
  237. try
  238. {
  239. _fileSystem.DeleteFile(path);
  240. }
  241. catch (IOException ex)
  242. {
  243. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  244. }
  245. }
  246. /// <summary>
  247. /// Extracts the fonts.
  248. /// </summary>
  249. /// <param name="targetPath">The target path.</param>
  250. /// <returns>Task.</returns>
  251. private async Task DownloadFonts(string targetPath)
  252. {
  253. try
  254. {
  255. var fontsDirectory = Path.Combine(targetPath, "fonts");
  256. Directory.CreateDirectory(fontsDirectory);
  257. const string fontFilename = "ARIALUNI.TTF";
  258. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  259. if (File.Exists(fontFile))
  260. {
  261. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  262. }
  263. else
  264. {
  265. // Kick this off, but no need to wait on it
  266. Task.Run(async () =>
  267. {
  268. await DownloadFontFile(fontsDirectory, fontFilename, new Progress<double>()).ConfigureAwait(false);
  269. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  270. });
  271. }
  272. }
  273. catch (HttpException ex)
  274. {
  275. // Don't let the server crash because of this
  276. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  277. }
  278. catch (Exception ex)
  279. {
  280. // Don't let the server crash because of this
  281. _logger.ErrorException("Error writing ffmpeg font files", ex);
  282. }
  283. }
  284. /// <summary>
  285. /// Downloads the font file.
  286. /// </summary>
  287. /// <param name="fontsDirectory">The fonts directory.</param>
  288. /// <param name="fontFilename">The font filename.</param>
  289. /// <returns>Task.</returns>
  290. private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
  291. {
  292. var existingFile = Directory
  293. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  294. .FirstOrDefault();
  295. if (existingFile != null)
  296. {
  297. try
  298. {
  299. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  300. return;
  301. }
  302. catch (IOException ex)
  303. {
  304. // Log this, but don't let it fail the operation
  305. _logger.ErrorException("Error copying file", ex);
  306. }
  307. }
  308. string tempFile = null;
  309. foreach (var url in _fontUrls)
  310. {
  311. progress.Report(0);
  312. try
  313. {
  314. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  315. {
  316. Url = url,
  317. Progress = progress
  318. }).ConfigureAwait(false);
  319. break;
  320. }
  321. catch (Exception ex)
  322. {
  323. // The core can function without the font file, so handle this
  324. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  325. }
  326. }
  327. if (string.IsNullOrEmpty(tempFile))
  328. {
  329. return;
  330. }
  331. Extract7zArchive(tempFile, fontsDirectory);
  332. try
  333. {
  334. _fileSystem.DeleteFile(tempFile);
  335. }
  336. catch (IOException ex)
  337. {
  338. // Log this, but don't let it fail the operation
  339. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  340. }
  341. }
  342. /// <summary>
  343. /// Writes the font config file.
  344. /// </summary>
  345. /// <param name="fontsDirectory">The fonts directory.</param>
  346. /// <returns>Task.</returns>
  347. private async Task WriteFontConfigFile(string fontsDirectory)
  348. {
  349. const string fontConfigFilename = "fonts.conf";
  350. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  351. if (!File.Exists(fontConfigFile))
  352. {
  353. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  354. var bytes = Encoding.UTF8.GetBytes(contents);
  355. using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  356. FileShare.Read, true))
  357. {
  358. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  359. }
  360. }
  361. }
  362. }
  363. }