EncodedRecorder.cs 12 KB

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