EncodedRecorder.cs 11 KB

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