2
0

BaseEncoder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Controller.Configuration;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Session;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Diagnostics;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.MediaInfo;
  17. using Microsoft.Extensions.Logging;
  18. namespace MediaBrowser.MediaEncoding.Encoder
  19. {
  20. public abstract class BaseEncoder
  21. {
  22. protected readonly MediaEncoder MediaEncoder;
  23. protected readonly ILogger Logger;
  24. protected readonly IServerConfigurationManager ConfigurationManager;
  25. protected readonly IFileSystem FileSystem;
  26. protected readonly IIsoManager IsoManager;
  27. protected readonly ILibraryManager LibraryManager;
  28. protected readonly ISessionManager SessionManager;
  29. protected readonly ISubtitleEncoder SubtitleEncoder;
  30. protected readonly IMediaSourceManager MediaSourceManager;
  31. protected IProcessFactory ProcessFactory;
  32. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  33. protected EncodingHelper EncodingHelper;
  34. protected BaseEncoder(MediaEncoder mediaEncoder,
  35. ILogger logger,
  36. IServerConfigurationManager configurationManager,
  37. IFileSystem fileSystem,
  38. IIsoManager isoManager,
  39. ILibraryManager libraryManager,
  40. ISessionManager sessionManager,
  41. ISubtitleEncoder subtitleEncoder,
  42. IMediaSourceManager mediaSourceManager, IProcessFactory processFactory)
  43. {
  44. MediaEncoder = mediaEncoder;
  45. Logger = logger;
  46. ConfigurationManager = configurationManager;
  47. FileSystem = fileSystem;
  48. IsoManager = isoManager;
  49. LibraryManager = libraryManager;
  50. SessionManager = sessionManager;
  51. SubtitleEncoder = subtitleEncoder;
  52. MediaSourceManager = mediaSourceManager;
  53. ProcessFactory = processFactory;
  54. EncodingHelper = new EncodingHelper(MediaEncoder, FileSystem, SubtitleEncoder);
  55. }
  56. public async Task<EncodingJob> Start(EncodingJobOptions options,
  57. IProgress<double> progress,
  58. CancellationToken cancellationToken)
  59. {
  60. var encodingJob = await new EncodingJobFactory(Logger, LibraryManager, MediaSourceManager, ConfigurationManager, MediaEncoder)
  61. .CreateJob(options, EncodingHelper, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
  62. encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
  63. Directory.CreateDirectory(Path.GetDirectoryName(encodingJob.OutputFilePath));
  64. encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate;
  65. await AcquireResources(encodingJob, cancellationToken).ConfigureAwait(false);
  66. var commandLineArgs = GetCommandLineArguments(encodingJob);
  67. var process = ProcessFactory.Create(new ProcessOptions
  68. {
  69. CreateNoWindow = true,
  70. UseShellExecute = false,
  71. // Must consume both stdout and stderr or deadlocks may occur
  72. //RedirectStandardOutput = true,
  73. RedirectStandardError = true,
  74. RedirectStandardInput = true,
  75. FileName = MediaEncoder.EncoderPath,
  76. Arguments = commandLineArgs,
  77. IsHidden = true,
  78. ErrorDialog = false,
  79. EnableRaisingEvents = true
  80. });
  81. var workingDirectory = GetWorkingDirectory(options);
  82. if (!string.IsNullOrWhiteSpace(workingDirectory))
  83. {
  84. process.StartInfo.WorkingDirectory = workingDirectory;
  85. }
  86. OnTranscodeBeginning(encodingJob);
  87. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  88. Logger.LogInformation(commandLineLogMessage);
  89. var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
  90. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  91. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  92. encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
  93. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  94. await encodingJob.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
  95. process.Exited += (sender, args) => OnFfMpegProcessExited(process, encodingJob);
  96. try
  97. {
  98. process.Start();
  99. }
  100. catch (Exception ex)
  101. {
  102. Logger.LogError(ex, "Error starting ffmpeg");
  103. OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
  104. throw;
  105. }
  106. cancellationToken.Register(() => Cancel(process, encodingJob));
  107. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  108. //process.BeginOutputReadLine();
  109. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  110. new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
  111. // Wait for the file to exist before proceeeding
  112. while (!File.Exists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
  113. {
  114. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  115. }
  116. return encodingJob;
  117. }
  118. private void Cancel(IProcess process, EncodingJob job)
  119. {
  120. Logger.LogInformation("Killing ffmpeg process for {0}", job.OutputFilePath);
  121. //process.Kill();
  122. process.StandardInput.WriteLine("q");
  123. job.IsCancelled = true;
  124. }
  125. /// <summary>
  126. /// Processes the exited.
  127. /// </summary>
  128. /// <param name="process">The process.</param>
  129. /// <param name="job">The job.</param>
  130. private void OnFfMpegProcessExited(IProcess process, EncodingJob job)
  131. {
  132. job.HasExited = true;
  133. Logger.LogDebug("Disposing stream resources");
  134. job.Dispose();
  135. var isSuccesful = false;
  136. try
  137. {
  138. var exitCode = process.ExitCode;
  139. Logger.LogInformation("FFMpeg exited with code {0}", exitCode);
  140. isSuccesful = exitCode == 0;
  141. }
  142. catch (Exception ex)
  143. {
  144. Logger.LogError(ex, "FFMpeg exited with an error.");
  145. }
  146. if (isSuccesful && !job.IsCancelled)
  147. {
  148. job.TaskCompletionSource.TrySetResult(true);
  149. }
  150. else if (job.IsCancelled)
  151. {
  152. try
  153. {
  154. DeleteFiles(job);
  155. }
  156. catch
  157. {
  158. }
  159. try
  160. {
  161. job.TaskCompletionSource.TrySetException(new OperationCanceledException());
  162. }
  163. catch
  164. {
  165. }
  166. }
  167. else
  168. {
  169. try
  170. {
  171. DeleteFiles(job);
  172. }
  173. catch
  174. {
  175. }
  176. try
  177. {
  178. job.TaskCompletionSource.TrySetException(new Exception("Encoding failed"));
  179. }
  180. catch
  181. {
  182. }
  183. }
  184. // This causes on exited to be called twice:
  185. //try
  186. //{
  187. // // Dispose the process
  188. // process.Dispose();
  189. //}
  190. //catch (Exception ex)
  191. //{
  192. // Logger.LogError("Error disposing ffmpeg.", ex);
  193. //}
  194. }
  195. protected virtual void DeleteFiles(EncodingJob job)
  196. {
  197. FileSystem.DeleteFile(job.OutputFilePath);
  198. }
  199. private void OnTranscodeBeginning(EncodingJob job)
  200. {
  201. job.ReportTranscodingProgress(null, null, null, null, null);
  202. }
  203. private void OnTranscodeFailedToStart(string path, EncodingJob job)
  204. {
  205. if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
  206. {
  207. SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
  208. }
  209. }
  210. protected abstract bool IsVideoEncoder { get; }
  211. protected virtual string GetWorkingDirectory(EncodingJobOptions options)
  212. {
  213. return null;
  214. }
  215. protected EncodingOptions GetEncodingOptions()
  216. {
  217. return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  218. }
  219. protected abstract string GetCommandLineArguments(EncodingJob job);
  220. private string GetOutputFilePath(EncodingJob state)
  221. {
  222. var folder = string.IsNullOrWhiteSpace(state.Options.TempDirectory) ?
  223. ConfigurationManager.ApplicationPaths.TranscodingTempPath :
  224. state.Options.TempDirectory;
  225. var outputFileExtension = GetOutputFileExtension(state);
  226. var filename = state.Id + (outputFileExtension ?? string.Empty).ToLowerInvariant();
  227. return Path.Combine(folder, filename);
  228. }
  229. protected virtual string GetOutputFileExtension(EncodingJob state)
  230. {
  231. if (!string.IsNullOrWhiteSpace(state.Options.Container))
  232. {
  233. return "." + state.Options.Container;
  234. }
  235. return null;
  236. }
  237. /// <summary>
  238. /// Gets the name of the output video codec
  239. /// </summary>
  240. /// <param name="state">The state.</param>
  241. /// <returns>System.String.</returns>
  242. protected string GetVideoDecoder(EncodingJob state)
  243. {
  244. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  245. {
  246. return null;
  247. }
  248. // Only use alternative encoders for video files.
  249. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  250. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  251. if (state.VideoType != VideoType.VideoFile)
  252. {
  253. return null;
  254. }
  255. if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
  256. {
  257. if (string.Equals(GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  258. {
  259. switch (state.MediaSource.VideoStream.Codec.ToLowerInvariant())
  260. {
  261. case "avc":
  262. case "h264":
  263. if (MediaEncoder.SupportsDecoder("h264_qsv"))
  264. {
  265. // Seeing stalls and failures with decoding. Not worth it compared to encoding.
  266. return "-c:v h264_qsv ";
  267. }
  268. break;
  269. case "mpeg2video":
  270. if (MediaEncoder.SupportsDecoder("mpeg2_qsv"))
  271. {
  272. return "-c:v mpeg2_qsv ";
  273. }
  274. break;
  275. case "vc1":
  276. if (MediaEncoder.SupportsDecoder("vc1_qsv"))
  277. {
  278. return "-c:v vc1_qsv ";
  279. }
  280. break;
  281. }
  282. }
  283. }
  284. // leave blank so ffmpeg will decide
  285. return null;
  286. }
  287. private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
  288. {
  289. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  290. {
  291. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
  292. }
  293. if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Options.LiveStreamId))
  294. {
  295. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  296. {
  297. OpenToken = state.MediaSource.OpenToken
  298. }, cancellationToken).ConfigureAwait(false);
  299. EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, null);
  300. if (state.IsVideoRequest)
  301. {
  302. EncodingHelper.TryStreamCopy(state);
  303. }
  304. }
  305. if (state.MediaSource.BufferMs.HasValue)
  306. {
  307. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
  308. }
  309. }
  310. }
  311. }