2
0

FFMpegDownloader.cs 13 KB

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