FFMpegDownloader.cs 15 KB

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