FFMpegDownloader.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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.IO;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.ServerApplication.Implementations
  16. {
  17. public class FFMpegDownloader
  18. {
  19. private readonly IHttpClient _httpClient;
  20. private readonly IApplicationPaths _appPaths;
  21. private readonly ILogger _logger;
  22. private const string Version = "ffmpeg20130904";
  23. private const string FontUrl = "https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1";
  24. private readonly string[] _ffMpegUrls = new[]
  25. {
  26. "http://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-20130904-git-f974289-win32-static.7z",
  27. "https://www.dropbox.com/s/a81cb2ob23fwcfs/ffmpeg-20130904-git-f974289-win32-static.7z?dl=1"
  28. };
  29. public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient)
  30. {
  31. _logger = logger;
  32. _appPaths = appPaths;
  33. _httpClient = httpClient;
  34. }
  35. public async Task<FFMpegInfo> GetFFMpegInfo()
  36. {
  37. var versionedDirectoryPath = Path.Combine(GetMediaToolsPath(true), Version);
  38. var info = new FFMpegInfo
  39. {
  40. ProbePath = Path.Combine(versionedDirectoryPath, "ffprobe.exe"),
  41. Path = Path.Combine(versionedDirectoryPath, "ffmpeg.exe"),
  42. Version = Version
  43. };
  44. if (!Directory.Exists(versionedDirectoryPath))
  45. {
  46. Directory.CreateDirectory(versionedDirectoryPath);
  47. }
  48. if (!File.Exists(info.ProbePath) || !File.Exists(info.Path))
  49. {
  50. await DownloadFFMpeg(info).ConfigureAwait(false);
  51. }
  52. try
  53. {
  54. await DownloadFonts(versionedDirectoryPath).ConfigureAwait(false);
  55. }
  56. catch (Exception ex)
  57. {
  58. _logger.ErrorException("Error getting ffmpeg font files", ex);
  59. }
  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. }
  77. private Task<string> DownloadFFMpeg(FFMpegInfo info, string url)
  78. {
  79. return _httpClient.GetTempFile(new HttpRequestOptions
  80. {
  81. Url = url,
  82. CancellationToken = CancellationToken.None,
  83. Progress = new Progress<double>(),
  84. // Make it look like a browser
  85. // Try to hide that we're direct linking
  86. UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.47 Safari/537.36"
  87. });
  88. }
  89. private void ExtractFFMpeg(string tempFile, string targetFolder)
  90. {
  91. _logger.Debug("Extracting ffmpeg from {0}", tempFile);
  92. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  93. if (!Directory.Exists(tempFolder))
  94. {
  95. Directory.CreateDirectory(tempFolder);
  96. }
  97. try
  98. {
  99. Extract7zArchive(tempFile, tempFolder);
  100. var files = Directory.EnumerateFiles(tempFolder, "*.exe", SearchOption.AllDirectories).ToList();
  101. foreach (var file in files)
  102. {
  103. File.Copy(file, Path.Combine(targetFolder, Path.GetFileName(file)));
  104. }
  105. }
  106. finally
  107. {
  108. DeleteFile(tempFile);
  109. }
  110. }
  111. private void Extract7zArchive(string archivePath, string targetPath)
  112. {
  113. using (var archive = SevenZipArchive.Open(archivePath))
  114. {
  115. using (var reader = archive.ExtractAllEntries())
  116. {
  117. reader.WriteAllToDirectory(targetPath, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
  118. }
  119. }
  120. }
  121. private void DeleteFile(string path)
  122. {
  123. try
  124. {
  125. File.Delete(path);
  126. }
  127. catch (IOException ex)
  128. {
  129. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  130. }
  131. }
  132. /// <summary>
  133. /// Extracts the fonts.
  134. /// </summary>
  135. /// <param name="targetPath">The target path.</param>
  136. private async Task DownloadFonts(string targetPath)
  137. {
  138. var fontsDirectory = Path.Combine(targetPath, "fonts");
  139. if (!Directory.Exists(fontsDirectory))
  140. {
  141. Directory.CreateDirectory(fontsDirectory);
  142. }
  143. const string fontFilename = "ARIALUNI.TTF";
  144. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  145. if (!File.Exists(fontFile))
  146. {
  147. await DownloadFontFile(fontsDirectory, fontFilename).ConfigureAwait(false);
  148. }
  149. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  150. }
  151. /// <summary>
  152. /// Downloads the font file.
  153. /// </summary>
  154. /// <param name="fontsDirectory">The fonts directory.</param>
  155. /// <param name="fontFilename">The font filename.</param>
  156. /// <returns>Task.</returns>
  157. private async Task DownloadFontFile(string fontsDirectory, string fontFilename)
  158. {
  159. var existingFile = Directory
  160. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  161. .FirstOrDefault();
  162. if (existingFile != null)
  163. {
  164. try
  165. {
  166. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  167. return;
  168. }
  169. catch (IOException ex)
  170. {
  171. // Log this, but don't let it fail the operation
  172. _logger.ErrorException("Error copying file", ex);
  173. }
  174. }
  175. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  176. {
  177. Url = FontUrl,
  178. Progress = new Progress<double>()
  179. });
  180. Extract7zArchive(tempFile, fontsDirectory);
  181. try
  182. {
  183. File.Delete(tempFile);
  184. }
  185. catch (IOException ex)
  186. {
  187. // Log this, but don't let it fail the operation
  188. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  189. }
  190. }
  191. /// <summary>
  192. /// Writes the font config file.
  193. /// </summary>
  194. /// <param name="fontsDirectory">The fonts directory.</param>
  195. /// <returns>Task.</returns>
  196. private async Task WriteFontConfigFile(string fontsDirectory)
  197. {
  198. const string fontConfigFilename = "fonts.conf";
  199. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  200. if (!File.Exists(fontConfigFile))
  201. {
  202. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  203. var bytes = Encoding.UTF8.GetBytes(contents);
  204. using (var fileStream = new FileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  205. FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize,
  206. FileOptions.Asynchronous))
  207. {
  208. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// Gets the media tools path.
  214. /// </summary>
  215. /// <param name="create">if set to <c>true</c> [create].</param>
  216. /// <returns>System.String.</returns>
  217. private string GetMediaToolsPath(bool create)
  218. {
  219. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  220. if (create && !Directory.Exists(path))
  221. {
  222. Directory.CreateDirectory(path);
  223. }
  224. return path;
  225. }
  226. }
  227. public class FFMpegInfo
  228. {
  229. public string Path { get; set; }
  230. public string ProbePath { get; set; }
  231. public string Version { get; set; }
  232. }
  233. }