FFMpegDownloader.cs 14 KB

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