FFMpegDownloader.cs 14 KB

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