FFMpegDownloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  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.ServerApplication.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 string[] _fontUrls = new[]
  25. {
  26. "https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1"
  27. };
  28. public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient, IFileSystem fileSystem)
  29. {
  30. _logger = logger;
  31. _appPaths = appPaths;
  32. _httpClient = httpClient;
  33. _zipClient = zipClient;
  34. _fileSystem = fileSystem;
  35. }
  36. public async Task<FFMpegInfo> GetFFMpegInfo(IProgress<double> progress)
  37. {
  38. var versionedDirectoryPath = Path.Combine(GetMediaToolsPath(true), FFMpegDownloadInfo.Version);
  39. var info = new FFMpegInfo
  40. {
  41. ProbePath = Path.Combine(versionedDirectoryPath, FFMpegDownloadInfo.FFProbeFilename),
  42. Path = Path.Combine(versionedDirectoryPath, FFMpegDownloadInfo.FFMpegFilename),
  43. Version = FFMpegDownloadInfo.Version
  44. };
  45. Directory.CreateDirectory(versionedDirectoryPath);
  46. var tasks = new List<Task>();
  47. double ffmpegPercent = 0;
  48. double fontPercent = 0;
  49. var syncLock = new object();
  50. if (!File.Exists(info.ProbePath) || !File.Exists(info.Path))
  51. {
  52. var ffmpegProgress = new ActionableProgress<double>();
  53. ffmpegProgress.RegisterAction(p =>
  54. {
  55. ffmpegPercent = p;
  56. lock (syncLock)
  57. {
  58. progress.Report((ffmpegPercent / 2) + (fontPercent / 2));
  59. }
  60. });
  61. tasks.Add(DownloadFFMpeg(info, ffmpegProgress));
  62. }
  63. else
  64. {
  65. ffmpegPercent = 100;
  66. progress.Report(50);
  67. }
  68. var fontProgress = new ActionableProgress<double>();
  69. fontProgress.RegisterAction(p =>
  70. {
  71. fontPercent = p;
  72. lock (syncLock)
  73. {
  74. progress.Report((ffmpegPercent / 2) + (fontPercent / 2));
  75. }
  76. });
  77. tasks.Add(DownloadFonts(versionedDirectoryPath, fontProgress));
  78. await Task.WhenAll(tasks).ConfigureAwait(false);
  79. return info;
  80. }
  81. private async Task DownloadFFMpeg(FFMpegInfo info, IProgress<double> progress)
  82. {
  83. foreach (var url in FFMpegDownloadInfo.FfMpegUrls)
  84. {
  85. progress.Report(0);
  86. try
  87. {
  88. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  89. {
  90. Url = url,
  91. CancellationToken = CancellationToken.None,
  92. Progress = progress
  93. }).ConfigureAwait(false);
  94. ExtractFFMpeg(tempFile, Path.GetDirectoryName(info.Path));
  95. return;
  96. }
  97. catch (HttpException)
  98. {
  99. }
  100. }
  101. throw new ApplicationException("Unable to download required components. Please try again later.");
  102. }
  103. private void ExtractFFMpeg(string tempFile, string targetFolder)
  104. {
  105. _logger.Debug("Extracting ffmpeg from {0}", tempFile);
  106. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  107. Directory.CreateDirectory(tempFolder);
  108. try
  109. {
  110. ExtractArchive(tempFile, tempFolder);
  111. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories).ToList();
  112. foreach (var file in files.Where(i =>
  113. {
  114. var filename = Path.GetFileName(i);
  115. return
  116. string.Equals(filename, FFMpegDownloadInfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  117. string.Equals(filename, FFMpegDownloadInfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  118. }))
  119. {
  120. File.Copy(file, Path.Combine(targetFolder, Path.GetFileName(file)), true);
  121. }
  122. }
  123. finally
  124. {
  125. DeleteFile(tempFile);
  126. }
  127. }
  128. private void ExtractArchive(string archivePath, string targetPath)
  129. {
  130. if (string.Equals(FFMpegDownloadInfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  131. {
  132. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  133. }
  134. else if (string.Equals(FFMpegDownloadInfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  135. {
  136. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  137. }
  138. }
  139. private void Extract7zArchive(string archivePath, string targetPath)
  140. {
  141. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  142. }
  143. private void DeleteFile(string path)
  144. {
  145. try
  146. {
  147. File.Delete(path);
  148. }
  149. catch (IOException ex)
  150. {
  151. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  152. }
  153. }
  154. /// <summary>
  155. /// Extracts the fonts.
  156. /// </summary>
  157. /// <param name="targetPath">The target path.</param>
  158. private async Task DownloadFonts(string targetPath, IProgress<double> progress)
  159. {
  160. try
  161. {
  162. var fontsDirectory = Path.Combine(targetPath, "fonts");
  163. Directory.CreateDirectory(fontsDirectory);
  164. const string fontFilename = "ARIALUNI.TTF";
  165. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  166. if (!File.Exists(fontFile))
  167. {
  168. await DownloadFontFile(fontsDirectory, fontFilename, progress).ConfigureAwait(false);
  169. }
  170. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  171. }
  172. catch (HttpException ex)
  173. {
  174. // Don't let the server crash because of this
  175. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  176. }
  177. catch (Exception ex)
  178. {
  179. // Don't let the server crash because of this
  180. _logger.ErrorException("Error writing ffmpeg font files", ex);
  181. }
  182. progress.Report(100);
  183. }
  184. /// <summary>
  185. /// Downloads the font file.
  186. /// </summary>
  187. /// <param name="fontsDirectory">The fonts directory.</param>
  188. /// <param name="fontFilename">The font filename.</param>
  189. /// <returns>Task.</returns>
  190. private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
  191. {
  192. var existingFile = Directory
  193. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  194. .FirstOrDefault();
  195. if (existingFile != null)
  196. {
  197. try
  198. {
  199. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  200. return;
  201. }
  202. catch (IOException ex)
  203. {
  204. // Log this, but don't let it fail the operation
  205. _logger.ErrorException("Error copying file", ex);
  206. }
  207. }
  208. string tempFile = null;
  209. foreach (var url in _fontUrls)
  210. {
  211. progress.Report(0);
  212. try
  213. {
  214. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  215. {
  216. Url = url,
  217. Progress = progress
  218. }).ConfigureAwait(false);
  219. break;
  220. }
  221. catch (Exception ex)
  222. {
  223. // The core can function without the font file, so handle this
  224. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  225. }
  226. }
  227. if (string.IsNullOrEmpty(tempFile))
  228. {
  229. return;
  230. }
  231. Extract7zArchive(tempFile, fontsDirectory);
  232. try
  233. {
  234. File.Delete(tempFile);
  235. }
  236. catch (IOException ex)
  237. {
  238. // Log this, but don't let it fail the operation
  239. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  240. }
  241. }
  242. /// <summary>
  243. /// Writes the font config file.
  244. /// </summary>
  245. /// <param name="fontsDirectory">The fonts directory.</param>
  246. /// <returns>Task.</returns>
  247. private async Task WriteFontConfigFile(string fontsDirectory)
  248. {
  249. const string fontConfigFilename = "fonts.conf";
  250. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  251. if (!File.Exists(fontConfigFile))
  252. {
  253. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  254. var bytes = Encoding.UTF8.GetBytes(contents);
  255. using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  256. FileShare.Read, true))
  257. {
  258. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  259. }
  260. }
  261. }
  262. /// <summary>
  263. /// Gets the media tools path.
  264. /// </summary>
  265. /// <param name="create">if set to <c>true</c> [create].</param>
  266. /// <returns>System.String.</returns>
  267. private string GetMediaToolsPath(bool create)
  268. {
  269. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  270. Directory.CreateDirectory(path);
  271. return path;
  272. }
  273. }
  274. }