EncodedRecorder.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using CommonIO;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller.MediaEncoding;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.Logging;
  16. using MediaBrowser.Model.Serialization;
  17. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  18. {
  19. public class EncodedRecorder : IRecorder
  20. {
  21. private readonly ILogger _logger;
  22. private readonly IFileSystem _fileSystem;
  23. private readonly IMediaEncoder _mediaEncoder;
  24. private readonly IApplicationPaths _appPaths;
  25. private bool _hasExited;
  26. private Stream _logFileStream;
  27. private string _targetPath;
  28. private Process _process;
  29. private readonly IJsonSerializer _json;
  30. public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IApplicationPaths appPaths, IJsonSerializer json)
  31. {
  32. _logger = logger;
  33. _fileSystem = fileSystem;
  34. _mediaEncoder = mediaEncoder;
  35. _appPaths = appPaths;
  36. _json = json;
  37. }
  38. public async Task Record(MediaSourceInfo mediaSource, string targetFile, Action onStarted, CancellationToken cancellationToken)
  39. {
  40. _targetPath = targetFile;
  41. _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile));
  42. var process = new Process
  43. {
  44. StartInfo = new ProcessStartInfo
  45. {
  46. CreateNoWindow = true,
  47. UseShellExecute = false,
  48. // Must consume both stdout and stderr or deadlocks may occur
  49. RedirectStandardOutput = true,
  50. RedirectStandardError = true,
  51. RedirectStandardInput = true,
  52. FileName = _mediaEncoder.EncoderPath,
  53. Arguments = GetCommandLineArgs(mediaSource, targetFile),
  54. WindowStyle = ProcessWindowStyle.Hidden,
  55. ErrorDialog = false
  56. },
  57. EnableRaisingEvents = true
  58. };
  59. _process = process;
  60. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  61. _logger.Info(commandLineLogMessage);
  62. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  63. _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  64. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  65. _logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  66. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  67. await _logFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
  68. process.Exited += (sender, args) => OnFfMpegProcessExited(process);
  69. process.Start();
  70. cancellationToken.Register(Stop);
  71. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  72. process.BeginOutputReadLine();
  73. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  74. StartStreamingLog(process.StandardError.BaseStream, _logFileStream);
  75. // Wait for the file to exist before proceeeding
  76. while (!_hasExited)
  77. {
  78. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  79. }
  80. }
  81. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string targetFile)
  82. {
  83. string videoArgs;
  84. if (EncodeVideo(mediaSource))
  85. {
  86. var maxBitrate = 25000000;
  87. videoArgs = string.Format(
  88. "-codec:v:0 libx264 -force_key_frames expr:gte(t,n_forced*5) {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync vfr -profile:v high -level 41",
  89. GetOutputSizeParam(),
  90. maxBitrate.ToString(CultureInfo.InvariantCulture));
  91. }
  92. else
  93. {
  94. videoArgs = "-codec:v:0 copy";
  95. }
  96. var commandLineArgs = "-fflags +genpts -i \"{0}\" -sn {2} -map_metadata -1 -threads 0 {3} -y \"{1}\"";
  97. //if (mediaSource.ReadAtNativeFramerate)
  98. {
  99. commandLineArgs = "-re " + commandLineArgs;
  100. }
  101. commandLineArgs = string.Format(commandLineArgs, mediaSource.Path, targetFile, videoArgs, GetAudioArgs(mediaSource));
  102. return commandLineArgs;
  103. }
  104. private string GetAudioArgs(MediaSourceInfo mediaSource)
  105. {
  106. var copyAudio = new[] { "aac", "mp3" };
  107. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  108. if (mediaStreams.Any(i => i.Type == MediaStreamType.Audio && copyAudio.Contains(i.Codec, StringComparer.OrdinalIgnoreCase)))
  109. {
  110. return "-codec:a:0 copy";
  111. }
  112. var audioChannels = 2;
  113. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  114. if (audioStream != null)
  115. {
  116. audioChannels = audioStream.Channels ?? audioChannels;
  117. }
  118. return "-codec:a:0 aac -strict experimental -ab 320000 -ac " + audioChannels.ToString(CultureInfo.InvariantCulture);
  119. }
  120. private bool EncodeVideo(MediaSourceInfo mediaSource)
  121. {
  122. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  123. return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced);
  124. }
  125. protected string GetOutputSizeParam()
  126. {
  127. var filters = new List<string>();
  128. filters.Add("yadif=0:-1:0");
  129. var output = string.Empty;
  130. if (filters.Count > 0)
  131. {
  132. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  133. }
  134. return output;
  135. }
  136. private void Stop()
  137. {
  138. if (!_hasExited)
  139. {
  140. try
  141. {
  142. _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
  143. //process.Kill();
  144. _process.StandardInput.WriteLine("q");
  145. // Need to wait because killing is asynchronous
  146. _process.WaitForExit(5000);
  147. }
  148. catch (Exception ex)
  149. {
  150. _logger.ErrorException("Error killing transcoding job for {0}", ex, _targetPath);
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// Processes the exited.
  156. /// </summary>
  157. /// <param name="process">The process.</param>
  158. private void OnFfMpegProcessExited(Process process)
  159. {
  160. _hasExited = true;
  161. _logger.Debug("Disposing stream resources");
  162. DisposeLogStream();
  163. try
  164. {
  165. _logger.Info("FFMpeg exited with code {0}", process.ExitCode);
  166. }
  167. catch
  168. {
  169. _logger.Error("FFMpeg exited with an error.");
  170. }
  171. }
  172. private void DisposeLogStream()
  173. {
  174. if (_logFileStream != null)
  175. {
  176. try
  177. {
  178. _logFileStream.Dispose();
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("Error disposing log stream", ex);
  183. }
  184. _logFileStream = null;
  185. }
  186. }
  187. private async void StartStreamingLog(Stream source, Stream target)
  188. {
  189. try
  190. {
  191. using (var reader = new StreamReader(source))
  192. {
  193. while (!reader.EndOfStream)
  194. {
  195. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  196. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  197. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  198. await target.FlushAsync().ConfigureAwait(false);
  199. }
  200. }
  201. }
  202. catch (ObjectDisposedException)
  203. {
  204. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  205. }
  206. catch (Exception ex)
  207. {
  208. _logger.ErrorException("Error reading ffmpeg log", ex);
  209. }
  210. }
  211. }
  212. }