BaseEncoder.cs 14 KB

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