FFMpegLoader.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Model.IO;
  4. using MediaBrowser.Model.Logging;
  5. using Mono.Unix.Native;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using CommonIO;
  13. namespace MediaBrowser.Server.Startup.Common.FFMpeg
  14. {
  15. public class FFMpegLoader
  16. {
  17. private readonly IHttpClient _httpClient;
  18. private readonly IApplicationPaths _appPaths;
  19. private readonly ILogger _logger;
  20. private readonly IZipClient _zipClient;
  21. private readonly IFileSystem _fileSystem;
  22. private readonly NativeEnvironment _environment;
  23. private readonly FFMpegInstallInfo _ffmpegInstallInfo;
  24. public FFMpegLoader(ILogger logger, IApplicationPaths appPaths, IHttpClient httpClient, IZipClient zipClient, IFileSystem fileSystem, NativeEnvironment environment, FFMpegInstallInfo ffmpegInstallInfo)
  25. {
  26. _logger = logger;
  27. _appPaths = appPaths;
  28. _httpClient = httpClient;
  29. _zipClient = zipClient;
  30. _fileSystem = fileSystem;
  31. _environment = environment;
  32. _ffmpegInstallInfo = ffmpegInstallInfo;
  33. }
  34. public async Task<FFMpegInfo> GetFFMpegInfo(NativeEnvironment environment, StartupOptions options, IProgress<double> progress)
  35. {
  36. var customffMpegPath = options.GetOption("-ffmpeg");
  37. var customffProbePath = options.GetOption("-ffprobe");
  38. if (!string.IsNullOrWhiteSpace(customffMpegPath) && !string.IsNullOrWhiteSpace(customffProbePath))
  39. {
  40. return new FFMpegInfo
  41. {
  42. ProbePath = customffProbePath,
  43. EncoderPath = customffMpegPath,
  44. Version = "external"
  45. };
  46. }
  47. var downloadInfo = _ffmpegInstallInfo;
  48. var version = downloadInfo.Version;
  49. if (string.Equals(version, "path", StringComparison.OrdinalIgnoreCase))
  50. {
  51. return new FFMpegInfo
  52. {
  53. ProbePath = downloadInfo.FFProbeFilename,
  54. EncoderPath = downloadInfo.FFMpegFilename,
  55. Version = version
  56. };
  57. }
  58. if (string.Equals(version, "0", StringComparison.OrdinalIgnoreCase))
  59. {
  60. return new FFMpegInfo();
  61. }
  62. var rootEncoderPath = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg");
  63. var versionedDirectoryPath = Path.Combine(rootEncoderPath, version);
  64. var info = new FFMpegInfo
  65. {
  66. ProbePath = Path.Combine(versionedDirectoryPath, downloadInfo.FFProbeFilename),
  67. EncoderPath = Path.Combine(versionedDirectoryPath, downloadInfo.FFMpegFilename),
  68. Version = version
  69. };
  70. _fileSystem.CreateDirectory(versionedDirectoryPath);
  71. var excludeFromDeletions = new List<string> { versionedDirectoryPath };
  72. if (!_fileSystem.FileExists(info.ProbePath) || !_fileSystem.FileExists(info.EncoderPath))
  73. {
  74. // ffmpeg not present. See if there's an older version we can start with
  75. var existingVersion = GetExistingVersion(info, rootEncoderPath);
  76. // No older version. Need to download and block until complete
  77. if (existingVersion == null)
  78. {
  79. var success = await DownloadFFMpeg(downloadInfo, versionedDirectoryPath, progress).ConfigureAwait(false);
  80. if (!success)
  81. {
  82. return new FFMpegInfo();
  83. }
  84. }
  85. else
  86. {
  87. info = existingVersion;
  88. versionedDirectoryPath = Path.GetDirectoryName(info.EncoderPath);
  89. excludeFromDeletions.Add(versionedDirectoryPath);
  90. }
  91. }
  92. // Allow just one of these to be overridden, if desired.
  93. if (!string.IsNullOrWhiteSpace(customffMpegPath))
  94. {
  95. info.EncoderPath = customffMpegPath;
  96. }
  97. if (!string.IsNullOrWhiteSpace(customffProbePath))
  98. {
  99. info.EncoderPath = customffProbePath;
  100. }
  101. return info;
  102. }
  103. private FFMpegInfo GetExistingVersion(FFMpegInfo info, string rootEncoderPath)
  104. {
  105. var encoderFilename = Path.GetFileName(info.EncoderPath);
  106. var probeFilename = Path.GetFileName(info.ProbePath);
  107. foreach (var directory in Directory.EnumerateDirectories(rootEncoderPath, "*", SearchOption.TopDirectoryOnly)
  108. .ToList())
  109. {
  110. var allFiles = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).ToList();
  111. var encoder = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), encoderFilename, StringComparison.OrdinalIgnoreCase));
  112. var probe = allFiles.FirstOrDefault(i => string.Equals(Path.GetFileName(i), probeFilename, StringComparison.OrdinalIgnoreCase));
  113. if (!string.IsNullOrWhiteSpace(encoder) &&
  114. !string.IsNullOrWhiteSpace(probe))
  115. {
  116. return new FFMpegInfo
  117. {
  118. EncoderPath = encoder,
  119. ProbePath = probe,
  120. Version = Path.GetFileName(Path.GetDirectoryName(probe))
  121. };
  122. }
  123. }
  124. return null;
  125. }
  126. private async Task<bool> DownloadFFMpeg(FFMpegInstallInfo downloadinfo, string directory, IProgress<double> progress)
  127. {
  128. foreach (var url in downloadinfo.DownloadUrls)
  129. {
  130. progress.Report(0);
  131. try
  132. {
  133. var tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
  134. {
  135. Url = url,
  136. CancellationToken = CancellationToken.None,
  137. Progress = progress
  138. }).ConfigureAwait(false);
  139. ExtractFFMpeg(downloadinfo, tempFile, directory);
  140. return true;
  141. }
  142. catch (Exception ex)
  143. {
  144. _logger.ErrorException("Error downloading {0}", ex, url);
  145. }
  146. }
  147. return false;
  148. }
  149. private void ExtractFFMpeg(FFMpegInstallInfo downloadinfo, string tempFile, string targetFolder)
  150. {
  151. _logger.Info("Extracting ffmpeg from {0}", tempFile);
  152. var tempFolder = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString());
  153. _fileSystem.CreateDirectory(tempFolder);
  154. try
  155. {
  156. ExtractArchive(downloadinfo, tempFile, tempFolder);
  157. var files = Directory.EnumerateFiles(tempFolder, "*", SearchOption.AllDirectories)
  158. .ToList();
  159. foreach (var file in files.Where(i =>
  160. {
  161. var filename = Path.GetFileName(i);
  162. return
  163. string.Equals(filename, downloadinfo.FFProbeFilename, StringComparison.OrdinalIgnoreCase) ||
  164. string.Equals(filename, downloadinfo.FFMpegFilename, StringComparison.OrdinalIgnoreCase);
  165. }))
  166. {
  167. var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
  168. _fileSystem.CopyFile(file, targetFile, true);
  169. SetFilePermissions(targetFile);
  170. }
  171. }
  172. finally
  173. {
  174. DeleteFile(tempFile);
  175. }
  176. }
  177. private void SetFilePermissions(string path)
  178. {
  179. // Linux: File permission to 666, and user's execute bit
  180. if (_environment.OperatingSystem == OperatingSystem.Bsd || _environment.OperatingSystem == OperatingSystem.Linux || _environment.OperatingSystem == OperatingSystem.Osx)
  181. {
  182. _logger.Info("Syscall.chmod {0} FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH", path);
  183. Syscall.chmod(path, FilePermissions.DEFFILEMODE | FilePermissions.S_IRWXU | FilePermissions.S_IXGRP | FilePermissions.S_IXOTH);
  184. }
  185. }
  186. private void ExtractArchive(FFMpegInstallInfo downloadinfo, string archivePath, string targetPath)
  187. {
  188. _logger.Info("Extracting {0} to {1}", archivePath, targetPath);
  189. if (string.Equals(downloadinfo.ArchiveType, "7z", StringComparison.OrdinalIgnoreCase))
  190. {
  191. _zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
  192. }
  193. else if (string.Equals(downloadinfo.ArchiveType, "gz", StringComparison.OrdinalIgnoreCase))
  194. {
  195. _zipClient.ExtractAllFromTar(archivePath, targetPath, true);
  196. }
  197. }
  198. private void DeleteFile(string path)
  199. {
  200. try
  201. {
  202. _fileSystem.DeleteFile(path);
  203. }
  204. catch (IOException ex)
  205. {
  206. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  207. }
  208. }
  209. }
  210. }