FFMpegDownloader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Progress;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. #if __MonoCS__
  16. using Mono.Unix.Native;
  17. #endif
  18. namespace MediaBrowser.ServerApplication.FFMpeg
  19. {
  20. public class FFMpegDownloader
  21. {
  22. private readonly IHttpClient _httpClient;
  23. private readonly IApplicationPaths _appPaths;
  24. private readonly ILogger _logger;
  25. private readonly IZipClient _zipClient;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly string[] _fontUrls = new[]
  28. {
  29. "https://www.dropbox.com/s/pj847twf7riq0j7/ARIALUNI.7z?dl=1"
  30. };
  31. public FFMpegDownloader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient, IFileSystem fileSystem)
  32. {
  33. _logger = logger;
  34. _appPaths = appPaths;
  35. _httpClient = httpClient;
  36. _zipClient = zipClient;
  37. _fileSystem = fileSystem;
  38. }
  39. public async Task<FFMpegInfo> GetFFMpegInfo(IProgress<double> progress)
  40. {
  41. var versionedDirectoryPath = Path.Combine(GetMediaToolsPath(true), FFMpegDownloadInfo.Version);
  42. var info = new FFMpegInfo
  43. {
  44. ProbePath = Path.Combine(versionedDirectoryPath, FFMpegDownloadInfo.FFProbeFilename),
  45. Path = Path.Combine(versionedDirectoryPath, FFMpegDownloadInfo.FFMpegFilename),
  46. Version = FFMpegDownloadInfo.Version
  47. };
  48. Directory.CreateDirectory(versionedDirectoryPath);
  49. var tasks = new List<Task>();
  50. double ffmpegPercent = 0;
  51. double fontPercent = 0;
  52. var syncLock = new object();
  53. if (!File.Exists(info.ProbePath) || !File.Exists(info.Path))
  54. {
  55. var ffmpegProgress = new ActionableProgress<double>();
  56. ffmpegProgress.RegisterAction(p =>
  57. {
  58. ffmpegPercent = p;
  59. lock (syncLock)
  60. {
  61. progress.Report((ffmpegPercent / 2) + (fontPercent / 2));
  62. }
  63. });
  64. tasks.Add(DownloadFFMpeg(info, ffmpegProgress));
  65. }
  66. else
  67. {
  68. ffmpegPercent = 100;
  69. progress.Report(50);
  70. }
  71. var fontProgress = new ActionableProgress<double>();
  72. fontProgress.RegisterAction(p =>
  73. {
  74. fontPercent = p;
  75. lock (syncLock)
  76. {
  77. progress.Report((ffmpegPercent / 2) + (fontPercent / 2));
  78. }
  79. });
  80. tasks.Add(DownloadFonts(versionedDirectoryPath, fontProgress));
  81. await Task.WhenAll(tasks).ConfigureAwait(false);
  82. return info;
  83. }
  84. private async Task DownloadFFMpeg(FFMpegInfo info, IProgress<double> progress)
  85. {
  86. foreach (var url in FFMpegDownloadInfo.FfMpegUrls)
  87. {
  88. progress.Report(0);
  89. try
  90. {
  91. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  92. {
  93. Url = url,
  94. CancellationToken = CancellationToken.None,
  95. Progress = progress
  96. }).ConfigureAwait(false);
  97. ExtractFFMpeg(tempFile, Path.GetDirectoryName(info.Path));
  98. return;
  99. }
  100. catch (HttpException ex)
  101. {
  102. _logger.ErrorException("Error downloading {0}", ex, url);
  103. }
  104. catch (Exception ex)
  105. {
  106. _logger.ErrorException("Error unpacking {0}", ex, url);
  107. }
  108. }
  109. throw new ApplicationException("Unable to download required components. Please try again later.");
  110. }
  111. private void ExtractFFMpeg(string tempFile, string targetFolder)
  112. {
  113. _logger.Debug("Extracting ffmpeg from {0}", tempFile);
  114. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  115. Directory.CreateDirectory(tempFolder);
  116. try
  117. {
  118. ExtractArchive(tempFile, tempFolder);
  119. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories).ToList();
  120. foreach (var file in files.Where(i =>
  121. {
  122. var filename = Path.GetFileName(i);
  123. return
  124. string.Equals(filename, FFMpegDownloadInfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  125. string.Equals(filename, FFMpegDownloadInfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  126. }))
  127. {
  128. File.Copy(file, Path.Combine(targetFolder, Path.GetFileName(file)), true);
  129. #if __MonoCS__
  130. //Linux: File permission to 666, and user's execute bit
  131. if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
  132. {
  133. Syscall.chmod(Path.Combine(targetFolder, Path.GetFileName(file)), FilePermissions.DEFFILEMODE | FilePermissions.S_IXUSR);
  134. }
  135. #endif
  136. }
  137. }
  138. finally
  139. {
  140. DeleteFile(tempFile);
  141. }
  142. }
  143. private void ExtractArchive(string archivePath, string targetPath)
  144. {
  145. if (string.Equals(FFMpegDownloadInfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  146. {
  147. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  148. }
  149. else if (string.Equals(FFMpegDownloadInfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  150. {
  151. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  152. }
  153. }
  154. private void Extract7zArchive(string archivePath, string targetPath)
  155. {
  156. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  157. }
  158. private void DeleteFile(string path)
  159. {
  160. try
  161. {
  162. File.Delete(path);
  163. }
  164. catch (IOException ex)
  165. {
  166. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  167. }
  168. }
  169. /// <summary>
  170. /// Extracts the fonts.
  171. /// </summary>
  172. /// <param name="targetPath">The target path.</param>
  173. private async Task DownloadFonts(string targetPath, IProgress<double> progress)
  174. {
  175. try
  176. {
  177. var fontsDirectory = Path.Combine(targetPath, "fonts");
  178. Directory.CreateDirectory(fontsDirectory);
  179. const string fontFilename = "ARIALUNI.TTF";
  180. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  181. if (!File.Exists(fontFile))
  182. {
  183. await DownloadFontFile(fontsDirectory, fontFilename, progress).ConfigureAwait(false);
  184. }
  185. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  186. }
  187. catch (HttpException ex)
  188. {
  189. // Don't let the server crash because of this
  190. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  191. }
  192. catch (Exception ex)
  193. {
  194. // Don't let the server crash because of this
  195. _logger.ErrorException("Error writing ffmpeg font files", ex);
  196. }
  197. progress.Report(100);
  198. }
  199. /// <summary>
  200. /// Downloads the font file.
  201. /// </summary>
  202. /// <param name="fontsDirectory">The fonts directory.</param>
  203. /// <param name="fontFilename">The font filename.</param>
  204. /// <returns>Task.</returns>
  205. private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
  206. {
  207. var existingFile = Directory
  208. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  209. .FirstOrDefault();
  210. if (existingFile != null)
  211. {
  212. try
  213. {
  214. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  215. return;
  216. }
  217. catch (IOException ex)
  218. {
  219. // Log this, but don't let it fail the operation
  220. _logger.ErrorException("Error copying file", ex);
  221. }
  222. }
  223. string tempFile = null;
  224. foreach (var url in _fontUrls)
  225. {
  226. progress.Report(0);
  227. try
  228. {
  229. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  230. {
  231. Url = url,
  232. Progress = progress
  233. }).ConfigureAwait(false);
  234. break;
  235. }
  236. catch (Exception ex)
  237. {
  238. // The core can function without the font file, so handle this
  239. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  240. }
  241. }
  242. if (string.IsNullOrEmpty(tempFile))
  243. {
  244. return;
  245. }
  246. Extract7zArchive(tempFile, fontsDirectory);
  247. try
  248. {
  249. File.Delete(tempFile);
  250. }
  251. catch (IOException ex)
  252. {
  253. // Log this, but don't let it fail the operation
  254. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  255. }
  256. }
  257. /// <summary>
  258. /// Writes the font config file.
  259. /// </summary>
  260. /// <param name="fontsDirectory">The fonts directory.</param>
  261. /// <returns>Task.</returns>
  262. private async Task WriteFontConfigFile(string fontsDirectory)
  263. {
  264. const string fontConfigFilename = "fonts.conf";
  265. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  266. if (!File.Exists(fontConfigFile))
  267. {
  268. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  269. var bytes = Encoding.UTF8.GetBytes(contents);
  270. using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  271. FileShare.Read, true))
  272. {
  273. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  274. }
  275. }
  276. }
  277. /// <summary>
  278. /// Gets the media tools path.
  279. /// </summary>
  280. /// <param name="create">if set to <c>true</c> [create].</param>
  281. /// <returns>System.String.</returns>
  282. private string GetMediaToolsPath(bool create)
  283. {
  284. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  285. Directory.CreateDirectory(path);
  286. return path;
  287. }
  288. }
  289. }