EncodedRecorder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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.Diagnostics;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.LiveTv;
  20. using MediaBrowser.Model.Logging;
  21. using MediaBrowser.Model.Serialization;
  22. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  23. {
  24. public class EncodedRecorder : IRecorder
  25. {
  26. private readonly ILogger _logger;
  27. private readonly IFileSystem _fileSystem;
  28. private readonly IHttpClient _httpClient;
  29. private readonly IMediaEncoder _mediaEncoder;
  30. private readonly IServerApplicationPaths _appPaths;
  31. private readonly LiveTvOptions _liveTvOptions;
  32. private bool _hasExited;
  33. private Stream _logFileStream;
  34. private string _targetPath;
  35. private IProcess _process;
  36. private readonly IProcessFactory _processFactory;
  37. private readonly IJsonSerializer _json;
  38. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  39. public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, IJsonSerializer json, LiveTvOptions liveTvOptions, IHttpClient httpClient, IProcessFactory processFactory)
  40. {
  41. _logger = logger;
  42. _fileSystem = fileSystem;
  43. _mediaEncoder = mediaEncoder;
  44. _appPaths = appPaths;
  45. _json = json;
  46. _liveTvOptions = liveTvOptions;
  47. _httpClient = httpClient;
  48. _processFactory = processFactory;
  49. }
  50. private string OutputFormat
  51. {
  52. get
  53. {
  54. var format = _liveTvOptions.RecordingEncodingFormat;
  55. if (string.Equals(format, "mkv", StringComparison.OrdinalIgnoreCase))
  56. {
  57. return "mkv";
  58. }
  59. return "mp4";
  60. }
  61. }
  62. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  63. {
  64. return Path.ChangeExtension(targetFile, "." + OutputFormat);
  65. }
  66. public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  67. {
  68. var durationToken = new CancellationTokenSource(duration);
  69. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  70. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
  71. _logger.Info("Recording completed to file {0}", targetFile);
  72. }
  73. private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  74. {
  75. _targetPath = targetFile;
  76. _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile));
  77. var process = _processFactory.Create(new ProcessOptions
  78. {
  79. CreateNoWindow = true,
  80. UseShellExecute = false,
  81. // Must consume both stdout and stderr or deadlocks may occur
  82. //RedirectStandardOutput = true,
  83. RedirectStandardError = true,
  84. RedirectStandardInput = true,
  85. FileName = _mediaEncoder.EncoderPath,
  86. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  87. IsHidden = true,
  88. ErrorDialog = false,
  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 mapArgs = string.Equals(OutputFormat, "mkv", StringComparison.OrdinalIgnoreCase) ? "-map 0" : "-sn";
  129. var commandLineArgs = "-i \"{0}\"{4} " + mapArgs + " {2} -map_metadata -1 -threads 0 {3} -y \"{1}\"";
  130. long startTimeTicks = 0;
  131. //if (mediaSource.DateLiveStreamOpened.HasValue)
  132. //{
  133. // var elapsed = DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value;
  134. // elapsed -= TimeSpan.FromSeconds(10);
  135. // if (elapsed.TotalSeconds >= 0)
  136. // {
  137. // startTimeTicks = elapsed.Ticks + startTimeTicks;
  138. // }
  139. //}
  140. if (mediaSource.ReadAtNativeFramerate)
  141. {
  142. inputModifiers += " -re";
  143. }
  144. if (startTimeTicks > 0)
  145. {
  146. inputModifiers = "-ss " + _mediaEncoder.GetTimeParameter(startTimeTicks) + " " + inputModifiers;
  147. }
  148. var analyzeDurationSeconds = 5;
  149. var analyzeDuration = " -analyzeduration " +
  150. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  151. inputModifiers += analyzeDuration;
  152. commandLineArgs = string.Format(commandLineArgs, inputTempFile, targetFile, videoArgs, GetAudioArgs(mediaSource), durationParam);
  153. return inputModifiers + " " + commandLineArgs;
  154. }
  155. private string GetAudioArgs(MediaSourceInfo mediaSource)
  156. {
  157. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  158. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  159. // do not copy aac because many players have difficulty with aac_latm
  160. if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings && !string.Equals(inputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  161. {
  162. return "-codec:a:0 copy";
  163. }
  164. var audioChannels = 2;
  165. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  166. if (audioStream != null)
  167. {
  168. audioChannels = audioStream.Channels ?? audioChannels;
  169. }
  170. return "-codec:a:0 aac -strict experimental -ab 320000";
  171. }
  172. private bool EncodeVideo(MediaSourceInfo mediaSource)
  173. {
  174. if (string.Equals(_liveTvOptions.RecordedVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  175. {
  176. return false;
  177. }
  178. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  179. return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced);
  180. }
  181. protected string GetOutputSizeParam()
  182. {
  183. var filters = new List<string>();
  184. filters.Add("yadif=0:-1:0");
  185. var output = string.Empty;
  186. if (filters.Count > 0)
  187. {
  188. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  189. }
  190. return output;
  191. }
  192. private void Stop()
  193. {
  194. if (!_hasExited)
  195. {
  196. try
  197. {
  198. _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath);
  199. //process.Kill();
  200. _process.StandardInput.WriteLine("q");
  201. }
  202. catch (Exception ex)
  203. {
  204. _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath);
  205. }
  206. if (_hasExited)
  207. {
  208. return;
  209. }
  210. try
  211. {
  212. _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath);
  213. if (_process.WaitForExit(5000))
  214. {
  215. return;
  216. }
  217. }
  218. catch (Exception ex)
  219. {
  220. _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath);
  221. }
  222. if (_hasExited)
  223. {
  224. return;
  225. }
  226. try
  227. {
  228. _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
  229. _process.Kill();
  230. }
  231. catch (Exception ex)
  232. {
  233. _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath);
  234. }
  235. }
  236. }
  237. /// <summary>
  238. /// Processes the exited.
  239. /// </summary>
  240. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  241. {
  242. _hasExited = true;
  243. DisposeLogStream();
  244. try
  245. {
  246. var exitCode = process.ExitCode;
  247. _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath);
  248. if (exitCode == 0)
  249. {
  250. _taskCompletionSource.TrySetResult(true);
  251. }
  252. else
  253. {
  254. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode)));
  255. }
  256. }
  257. catch
  258. {
  259. _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath);
  260. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath)));
  261. }
  262. }
  263. private void DisposeLogStream()
  264. {
  265. if (_logFileStream != null)
  266. {
  267. try
  268. {
  269. _logFileStream.Dispose();
  270. }
  271. catch (Exception ex)
  272. {
  273. _logger.ErrorException("Error disposing recording log stream", ex);
  274. }
  275. _logFileStream = null;
  276. }
  277. }
  278. private async void StartStreamingLog(Stream source, Stream target)
  279. {
  280. try
  281. {
  282. using (var reader = new StreamReader(source))
  283. {
  284. while (!reader.EndOfStream)
  285. {
  286. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  287. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  288. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  289. await target.FlushAsync().ConfigureAwait(false);
  290. }
  291. }
  292. }
  293. catch (ObjectDisposedException)
  294. {
  295. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  296. }
  297. catch (Exception ex)
  298. {
  299. _logger.ErrorException("Error reading ffmpeg recording log", ex);
  300. }
  301. }
  302. }
  303. }