FFMpegDownloader.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 IFileSystem _fileSystem;
  23. private readonly string[] _fontUrls = new[]
  24. {
  25. "https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1"
  26. };
  27. public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient, IFileSystem fileSystem)
  28. {
  29. _logger = logger;
  30. _appPaths = appPaths;
  31. _httpClient = httpClient;
  32. _zipClient = zipClient;
  33. _fileSystem = fileSystem;
  34. }
  35. public async Task<FFMpegInfo> GetFFMpegInfo()
  36. {
  37. var versionedDirectoryPath = Path.Combine(GetMediaToolsPath(true), FFMpegDownloadInfo.Version);
  38. var info = new FFMpegInfo
  39. {
  40. ProbePath = Path.Combine(versionedDirectoryPath, FFMpegDownloadInfo.FFProbeFilename),
  41. Path = Path.Combine(versionedDirectoryPath, FFMpegDownloadInfo.FFMpegFilename),
  42. Version = FFMpegDownloadInfo.Version
  43. };
  44. Directory.CreateDirectory(versionedDirectoryPath);
  45. var tasks = new List<Task>();
  46. if (!File.Exists(info.ProbePath) || !File.Exists(info.Path))
  47. {
  48. tasks.Add(DownloadFFMpeg(info));
  49. }
  50. tasks.Add(DownloadFonts(versionedDirectoryPath));
  51. await Task.WhenAll(tasks).ConfigureAwait(false);
  52. return info;
  53. }
  54. private async Task DownloadFFMpeg(FFMpegInfo info)
  55. {
  56. foreach (var url in FFMpegDownloadInfo.FfMpegUrls)
  57. {
  58. try
  59. {
  60. var tempFile = await DownloadFFMpeg(info, url).ConfigureAwait(false);
  61. ExtractFFMpeg(tempFile, Path.GetDirectoryName(info.Path));
  62. return;
  63. }
  64. catch (HttpException)
  65. {
  66. }
  67. }
  68. throw new ApplicationException("Unable to download required components. Please try again later.");
  69. }
  70. private Task<string> DownloadFFMpeg(FFMpegInfo info, string url)
  71. {
  72. return _httpClient.GetTempFile(new HttpRequestOptions
  73. {
  74. Url = url,
  75. CancellationToken = CancellationToken.None,
  76. Progress = new Progress<double>()
  77. });
  78. }
  79. private void ExtractFFMpeg(string tempFile, string targetFolder)
  80. {
  81. _logger.Debug("Extracting ffmpeg from {0}", tempFile);
  82. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  83. Directory.CreateDirectory(tempFolder);
  84. try
  85. {
  86. ExtractArchive(tempFile, tempFolder);
  87. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories).ToList();
  88. foreach (var file in files.Where(i =>
  89. {
  90. var filename = Path.GetFileName(i);
  91. return
  92. string.Equals(filename, FFMpegDownloadInfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  93. string.Equals(filename, FFMpegDownloadInfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  94. }))
  95. {
  96. File.Copy(file, Path.Combine(targetFolder, Path.GetFileName(file)), true);
  97. }
  98. }
  99. finally
  100. {
  101. DeleteFile(tempFile);
  102. }
  103. }
  104. private void ExtractArchive(string archivePath, string targetPath)
  105. {
  106. if (string.Equals(FFMpegDownloadInfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  107. {
  108. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  109. }
  110. else if (string.Equals(FFMpegDownloadInfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  111. {
  112. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  113. }
  114. }
  115. private void Extract7zArchive(string archivePath, string targetPath)
  116. {
  117. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  118. }
  119. private void DeleteFile(string path)
  120. {
  121. try
  122. {
  123. File.Delete(path);
  124. }
  125. catch (IOException ex)
  126. {
  127. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  128. }
  129. }
  130. /// <summary>
  131. /// Extracts the fonts.
  132. /// </summary>
  133. /// <param name="targetPath">The target path.</param>
  134. private async Task DownloadFonts(string targetPath)
  135. {
  136. try
  137. {
  138. var fontsDirectory = Path.Combine(targetPath, "fonts");
  139. Directory.CreateDirectory(fontsDirectory);
  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 = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  230. FileShare.Read, true))
  231. {
  232. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  233. }
  234. }
  235. }
  236. /// <summary>
  237. /// Gets the media tools path.
  238. /// </summary>
  239. /// <param name="create">if set to <c>true</c> [create].</param>
  240. /// <returns>System.String.</returns>
  241. private string GetMediaToolsPath(bool create)
  242. {
  243. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  244. Directory.CreateDirectory(path);
  245. return path;
  246. }
  247. }
  248. }