EncodedRecorder.cs 9.6 KB

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