EncodedRecorder.cs 11 KB

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