FFMpegDownloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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)
  101. {
  102. }
  103. }
  104. throw new ApplicationException("Unable to download required components. Please try again later.");
  105. }
  106. private void ExtractFFMpeg(string tempFile, string targetFolder)
  107. {
  108. _logger.Debug("Extracting ffmpeg from {0}", tempFile);
  109. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  110. Directory.CreateDirectory(tempFolder);
  111. try
  112. {
  113. ExtractArchive(tempFile, tempFolder);
  114. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories).ToList();
  115. foreach (var file in files.Where(i =>
  116. {
  117. var filename = Path.GetFileName(i);
  118. return
  119. string.Equals(filename, FFMpegDownloadInfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  120. string.Equals(filename, FFMpegDownloadInfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  121. }))
  122. {
  123. File.Copy(file, Path.Combine(targetFolder, Path.GetFileName(file)), true);
  124. #if __MonoCS__
  125. //Linux: File permission to 666, and user's execute bit
  126. if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
  127. {
  128. Syscall.chmod(Path.Combine(targetFolder, Path.GetFileName(file)), FilePermissions.DEFFILEMODE | FilePermissions.S_IXUSR);
  129. }
  130. #endif
  131. }
  132. }
  133. finally
  134. {
  135. DeleteFile(tempFile);
  136. }
  137. }
  138. private void ExtractArchive(string archivePath, string targetPath)
  139. {
  140. if (string.Equals(FFMpegDownloadInfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  141. {
  142. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  143. }
  144. else if (string.Equals(FFMpegDownloadInfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  145. {
  146. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  147. }
  148. }
  149. private void Extract7zArchive(string archivePath, string targetPath)
  150. {
  151. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  152. }
  153. private void DeleteFile(string path)
  154. {
  155. try
  156. {
  157. File.Delete(path);
  158. }
  159. catch (IOException ex)
  160. {
  161. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  162. }
  163. }
  164. /// <summary>
  165. /// Extracts the fonts.
  166. /// </summary>
  167. /// <param name="targetPath">The target path.</param>
  168. private async Task DownloadFonts(string targetPath, IProgress<double> progress)
  169. {
  170. try
  171. {
  172. var fontsDirectory = Path.Combine(targetPath, "fonts");
  173. Directory.CreateDirectory(fontsDirectory);
  174. const string fontFilename = "ARIALUNI.TTF";
  175. var fontFile = Path.Combine(fontsDirectory, fontFilename);
  176. if (!File.Exists(fontFile))
  177. {
  178. await DownloadFontFile(fontsDirectory, fontFilename, progress).ConfigureAwait(false);
  179. }
  180. await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
  181. }
  182. catch (HttpException ex)
  183. {
  184. // Don't let the server crash because of this
  185. _logger.ErrorException("Error downloading ffmpeg font files", ex);
  186. }
  187. catch (Exception ex)
  188. {
  189. // Don't let the server crash because of this
  190. _logger.ErrorException("Error writing ffmpeg font files", ex);
  191. }
  192. progress.Report(100);
  193. }
  194. /// <summary>
  195. /// Downloads the font file.
  196. /// </summary>
  197. /// <param name="fontsDirectory">The fonts directory.</param>
  198. /// <param name="fontFilename">The font filename.</param>
  199. /// <returns>Task.</returns>
  200. private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
  201. {
  202. var existingFile = Directory
  203. .EnumerateFiles(_appPaths.ProgramDataPath, fontFilename, SearchOption.AllDirectories)
  204. .FirstOrDefault();
  205. if (existingFile != null)
  206. {
  207. try
  208. {
  209. File.Copy(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
  210. return;
  211. }
  212. catch (IOException ex)
  213. {
  214. // Log this, but don't let it fail the operation
  215. _logger.ErrorException("Error copying file", ex);
  216. }
  217. }
  218. string tempFile = null;
  219. foreach (var url in _fontUrls)
  220. {
  221. progress.Report(0);
  222. try
  223. {
  224. tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  225. {
  226. Url = url,
  227. Progress = progress
  228. }).ConfigureAwait(false);
  229. break;
  230. }
  231. catch (Exception ex)
  232. {
  233. // The core can function without the font file, so handle this
  234. _logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
  235. }
  236. }
  237. if (string.IsNullOrEmpty(tempFile))
  238. {
  239. return;
  240. }
  241. Extract7zArchive(tempFile, fontsDirectory);
  242. try
  243. {
  244. File.Delete(tempFile);
  245. }
  246. catch (IOException ex)
  247. {
  248. // Log this, but don't let it fail the operation
  249. _logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
  250. }
  251. }
  252. /// <summary>
  253. /// Writes the font config file.
  254. /// </summary>
  255. /// <param name="fontsDirectory">The fonts directory.</param>
  256. /// <returns>Task.</returns>
  257. private async Task WriteFontConfigFile(string fontsDirectory)
  258. {
  259. const string fontConfigFilename = "fonts.conf";
  260. var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
  261. if (!File.Exists(fontConfigFile))
  262. {
  263. var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
  264. var bytes = Encoding.UTF8.GetBytes(contents);
  265. using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileMode.Create, FileAccess.Write,
  266. FileShare.Read, true))
  267. {
  268. await fileStream.WriteAsync(bytes, 0, bytes.Length);
  269. }
  270. }
  271. }
  272. /// <summary>
  273. /// Gets the media tools path.
  274. /// </summary>
  275. /// <param name="create">if set to <c>true</c> [create].</param>
  276. /// <returns>System.String.</returns>
  277. private string GetMediaToolsPath(bool create)
  278. {
  279. var path = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  280. Directory.CreateDirectory(path);
  281. return path;
  282. }
  283. }
  284. }