FFMpegDownloader.cs 13 KB

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