FFMpegDownloader.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 Extract7zArchive(string archivePath, string targetPath)
  117. {
  118. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  119. }
  120. private void DeleteFile(string path)
  121. {
  122. try
  123. {
  124. File.Delete(path);
  125. }
  126. catch (IOException ex)
  127. {
  128. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  129. }
  130. }
  131. /// <summary>
  132. /// Extracts the fonts.
  133. /// </summary>
  134. /// <param name="targetPath">The target path.</param>
  135. private async Task DownloadFonts(string targetPath)
  136. {
  137. try
  138. {
  139. var fontsDirectory = Path.Combine(targetPath, "fonts");
  140. Directory.CreateDirectory(fontsDirectory);
  141. const string fontFilename = "ARIALUNI.TTF";
  142. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  143. if (!File.Exists(fontFile))
  144. {
  145. await DownloadFontFile(fontsDirectory, fontFilename).ConfigureAwait(false);
  146. }
  147. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  148. }
  149. catch (HttpException ex)
  150. {
  151. // Don't let the server crash because of this
  152. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  153. }
  154. catch (Exception ex)
  155. {
  156. // Don't let the server crash because of this
  157. _logger.ErrorException("Error writing ffmpeg font files", ex);
  158. }
  159. }
  160. /// <summary>
  161. /// Downloads the font file.
  162. /// </summary>
  163. /// <param name="fontsDirectory">The fonts directory.</param>
  164. /// <param name="fontFilename">The font filename.</param>
  165. /// <returns>Task.</returns>
  166. private async Task DownloadFontFile(string fontsDirectory, string fontFilename)
  167. {
  168. var existingFile = Directory
  169. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  170. .FirstOrDefault();
  171. if (existingFile != null)
  172. {
  173. try
  174. {
  175. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  176. return;
  177. }
  178. catch (IOException ex)
  179. {
  180. // Log this, but don't let it fail the operation
  181. _logger.ErrorException("Error copying file", ex);
  182. }
  183. }
  184. string tempFile = null;
  185. foreach (var url in _fontUrls)
  186. {
  187. try
  188. {
  189. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  190. {
  191. Url = url,
  192. Progress = new Progress<double>()
  193. }).ConfigureAwait(false);
  194. break;
  195. }
  196. catch (Exception ex)
  197. {
  198. // The core can function without the font file, so handle this
  199. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  200. }
  201. }
  202. if (string.IsNullOrEmpty(tempFile))
  203. {
  204. return;
  205. }
  206. Extract7zArchive(tempFile, fontsDirectory);
  207. try
  208. {
  209. File.Delete(tempFile);
  210. }
  211. catch (IOException ex)
  212. {
  213. // Log this, but don't let it fail the operation
  214. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  215. }
  216. }
  217. /// <summary>
  218. /// Writes the font config file.
  219. /// </summary>
  220. /// <param name="fontsDirectory">The fonts directory.</param>
  221. /// <returns>Task.</returns>
  222. private async Task WriteFontConfigFile(string fontsDirectory)
  223. {
  224. const string fontConfigFilename = "fonts.conf";
  225. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  226. if (!File.Exists(fontConfigFile))
  227. {
  228. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  229. var bytes = Encoding.UTF8.GetBytes(contents);
  230. using (var fileStream = new FileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  231. FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize,
  232. FileOptions.Asynchronous))
  233. {
  234. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  235. }
  236. }
  237. }
  238. /// <summary>
  239. /// Gets the media tools path.
  240. /// </summary>
  241. /// <param name="create">if set to <c>true</c> [create].</param>
  242. /// <returns>System.String.</returns>
  243. private string GetMediaToolsPath(bool create)
  244. {
  245. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  246. Directory.CreateDirectory(path);
  247. return path;
  248. }
  249. }
  250. }