FFMpegDownloader.cs 9.9 KB

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