EncodedRecorder.cs 11 KB

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