FFMpegDownloader.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using SharpCompress.Archive.SevenZip;
  7. using SharpCompress.Common;
  8. using SharpCompress.Reader;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.ServerApplication.Implementations
  17. {
  18. public class FFMpegDownloader
  19. {
  20. private readonly IHttpClient _httpClient;
  21. private readonly IApplicationPaths _appPaths;
  22. private readonly ILogger _logger;
  23. private const string Version = "ffmpeg20130904";
  24. private readonly string[] _fontUrls = new[]
  25. {
  26. "https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1"
  27. };
  28. private readonly string[] _ffMpegUrls = new[]
  29. {
  30. "https://raw.github.com/MediaBrowser/MediaBrowser/master/MediaBrowser.ServerApplication/Implementations/ffmpeg-20130904-git-f974289-win32-static.7z",
  31. "http://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-20130904-git-f974289-win32-static.7z",
  32. "https://www.dropbox.com/s/a81cb2ob23fwcfs/ffmpeg-20130904-git-f974289-win32-static.7z?dl=1"
  33. };
  34. public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient)
  35. {
  36. _logger = logger;
  37. _appPaths = appPaths;
  38. _httpClient = httpClient;
  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. using (var archive = SevenZipArchive.Open(archivePath))
  115. {
  116. using (var reader = archive.ExtractAllEntries())
  117. {
  118. reader.WriteAllToDirectory(targetPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
  119. }
  120. }
  121. }
  122. private void DeleteFile(string path)
  123. {
  124. try
  125. {
  126. File.Delete(path);
  127. }
  128. catch (IOException ex)
  129. {
  130. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  131. }
  132. }
  133. /// <summary>
  134. /// Extracts the fonts.
  135. /// </summary>
  136. /// <param name="targetPath">The target path.</param>
  137. private async Task DownloadFonts(string targetPath)
  138. {
  139. try
  140. {
  141. var fontsDirectory = Path.Combine(targetPath, "fonts");
  142. if (!Directory.Exists(fontsDirectory))
  143. {
  144. Directory.CreateDirectory(fontsDirectory);
  145. }
  146. const string fontFilename = "ARIALUNI.TTF";
  147. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  148. if (!File.Exists(fontFile))
  149. {
  150. await DownloadFontFile(fontsDirectory, fontFilename).ConfigureAwait(false);
  151. }
  152. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  153. }
  154. catch (HttpException ex)
  155. {
  156. // Don't let the server crash because of this
  157. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  158. }
  159. catch (Exception ex)
  160. {
  161. // Don't let the server crash because of this
  162. _logger.ErrorException("Error writing ffmpeg font files", ex);
  163. }
  164. }
  165. /// <summary>
  166. /// Downloads the font file.
  167. /// </summary>
  168. /// <param name="fontsDirectory">The fonts directory.</param>
  169. /// <param name="fontFilename">The font filename.</param>
  170. /// <returns>Task.</returns>
  171. private async Task DownloadFontFile(string fontsDirectory, string fontFilename)
  172. {
  173. var existingFile = Directory
  174. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  175. .FirstOrDefault();
  176. if (existingFile != null)
  177. {
  178. try
  179. {
  180. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  181. return;
  182. }
  183. catch (IOException ex)
  184. {
  185. // Log this, but don't let it fail the operation
  186. _logger.ErrorException("Error copying file", ex);
  187. }
  188. }
  189. string tempFile = null;
  190. foreach (var url in _fontUrls)
  191. {
  192. try
  193. {
  194. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  195. {
  196. Url = url,
  197. Progress = new Progress<double>()
  198. }).ConfigureAwait(false);
  199. break;
  200. }
  201. catch (Exception ex)
  202. {
  203. // The core can function without the font file, so handle this
  204. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  205. }
  206. }
  207. if (string.IsNullOrEmpty(tempFile))
  208. {
  209. return;
  210. }
  211. Extract7zArchive(tempFile, fontsDirectory);
  212. try
  213. {
  214. File.Delete(tempFile);
  215. }
  216. catch (IOException ex)
  217. {
  218. // Log this, but don't let it fail the operation
  219. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  220. }
  221. }
  222. /// <summary>
  223. /// Writes the font config file.
  224. /// </summary>
  225. /// <param name="fontsDirectory">The fonts directory.</param>
  226. /// <returns>Task.</returns>
  227. private async Task WriteFontConfigFile(string fontsDirectory)
  228. {
  229. const string fontConfigFilename = "fonts.conf";
  230. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  231. if (!File.Exists(fontConfigFile))
  232. {
  233. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  234. var bytes = Encoding.UTF8.GetBytes(contents);
  235. using (var fileStream = new FileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  236. FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize,
  237. FileOptions.Asynchronous))
  238. {
  239. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  240. }
  241. }
  242. }
  243. /// <summary>
  244. /// Gets the media tools path.
  245. /// </summary>
  246. /// <param name="create">if set to <c>true</c> [create].</param>
  247. /// <returns>System.String.</returns>
  248. private string GetMediaToolsPath(bool create)
  249. {
  250. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  251. if (create && !Directory.Exists(path))
  252. {
  253. Directory.CreateDirectory(path);
  254. }
  255. return path;
  256. }
  257. }
  258. public class FFMpegInfo
  259. {
  260. public string Path { get; set; }
  261. public string ProbePath { get; set; }
  262. public string Version { get; set; }
  263. }
  264. }