FFMpegDownloader.cs 9.9 KB

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