FFMpegDownloader.cs 9.6 KB

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