EncodedRecorder.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. onStarted();
  76. // Wait for the file to exist before proceeeding
  77. while (!_hasExited)
  78. {
  79. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  80. }
  81. }
  82. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string targetFile)
  83. {
  84. string videoArgs;
  85. if (EncodeVideo(mediaSource))
  86. {
  87. var maxBitrate = 25000000;
  88. videoArgs = string.Format(
  89. "-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",
  90. GetOutputSizeParam(),
  91. maxBitrate.ToString(CultureInfo.InvariantCulture));
  92. }
  93. else
  94. {
  95. videoArgs = "-codec:v:0 copy";
  96. }
  97. var commandLineArgs = "-fflags +genpts -i \"{0}\" -sn {2} -map_metadata -1 -threads 0 {3} -y \"{1}\"";
  98. if (mediaSource.ReadAtNativeFramerate)
  99. {
  100. commandLineArgs = "-re " + commandLineArgs;
  101. }
  102. commandLineArgs = string.Format(commandLineArgs, mediaSource.Path, targetFile, videoArgs, GetAudioArgs(mediaSource));
  103. return commandLineArgs;
  104. }
  105. private string GetAudioArgs(MediaSourceInfo mediaSource)
  106. {
  107. var copyAudio = new[] { "aac", "mp3" };
  108. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  109. if (mediaStreams.Any(i => i.Type == MediaStreamType.Audio && copyAudio.Contains(i.Codec, StringComparer.OrdinalIgnoreCase)))
  110. {
  111. return "-codec:a:0 copy";
  112. }
  113. var audioChannels = 2;
  114. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  115. if (audioStream != null)
  116. {
  117. audioChannels = audioStream.Channels ?? audioChannels;
  118. }
  119. return "-codec:a:0 aac -strict experimental -ab 320000 -ac " + audioChannels.ToString(CultureInfo.InvariantCulture);
  120. }
  121. private bool EncodeVideo(MediaSourceInfo mediaSource)
  122. {
  123. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  124. return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced);
  125. }
  126. protected string GetOutputSizeParam()
  127. {
  128. var filters = new List<string>();
  129. filters.Add("yadif=0:-1:0");
  130. var output = string.Empty;
  131. if (filters.Count > 0)
  132. {
  133. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  134. }
  135. return output;
  136. }
  137. private void Stop()
  138. {
  139. if (!_hasExited)
  140. {
  141. try
  142. {
  143. _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
  144. //process.Kill();
  145. _process.StandardInput.WriteLine("q");
  146. // Need to wait because killing is asynchronous
  147. _process.WaitForExit(5000);
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.ErrorException("Error killing transcoding job for {0}", ex, _targetPath);
  152. }
  153. }
  154. }
  155. /// <summary>
  156. /// Processes the exited.
  157. /// </summary>
  158. /// <param name="process">The process.</param>
  159. private void OnFfMpegProcessExited(Process process)
  160. {
  161. _hasExited = true;
  162. _logger.Debug("Disposing stream resources");
  163. DisposeLogStream();
  164. try
  165. {
  166. _logger.Info("FFMpeg exited with code {0}", process.ExitCode);
  167. }
  168. catch
  169. {
  170. _logger.Error("FFMpeg exited with an error.");
  171. }
  172. }
  173. private void DisposeLogStream()
  174. {
  175. if (_logFileStream != null)
  176. {
  177. try
  178. {
  179. _logFileStream.Dispose();
  180. }
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error disposing log stream", ex);
  184. }
  185. _logFileStream = null;
  186. }
  187. }
  188. private async void StartStreamingLog(Stream source, Stream target)
  189. {
  190. try
  191. {
  192. using (var reader = new StreamReader(source))
  193. {
  194. while (!reader.EndOfStream)
  195. {
  196. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  197. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  198. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  199. await target.FlushAsync().ConfigureAwait(false);
  200. }
  201. }
  202. }
  203. catch (ObjectDisposedException)
  204. {
  205. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  206. }
  207. catch (Exception ex)
  208. {
  209. _logger.ErrorException("Error reading ffmpeg log", ex);
  210. }
  211. }
  212. }
  213. }