EncodedRecorder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 string _targetPath;
  34. private IProcess _process;
  35. private readonly IProcessFactory _processFactory;
  36. private readonly IJsonSerializer _json;
  37. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  38. public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, IJsonSerializer json, LiveTvOptions liveTvOptions, IHttpClient httpClient, IProcessFactory processFactory)
  39. {
  40. _logger = logger;
  41. _fileSystem = fileSystem;
  42. _mediaEncoder = mediaEncoder;
  43. _appPaths = appPaths;
  44. _json = json;
  45. _liveTvOptions = liveTvOptions;
  46. _httpClient = httpClient;
  47. _processFactory = processFactory;
  48. }
  49. private string OutputFormat
  50. {
  51. get
  52. {
  53. var format = _liveTvOptions.RecordingEncodingFormat;
  54. if (string.Equals(format, "mkv", StringComparison.OrdinalIgnoreCase))
  55. {
  56. return "mkv";
  57. }
  58. return "mp4";
  59. }
  60. }
  61. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  62. {
  63. return Path.ChangeExtension(targetFile, "." + OutputFormat);
  64. }
  65. public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  66. {
  67. var durationToken = new CancellationTokenSource(duration);
  68. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  69. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
  70. _logger.Info("Recording completed to file {0}", targetFile);
  71. }
  72. private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  73. {
  74. _targetPath = targetFile;
  75. _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile));
  76. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid().ToString("N") + ".txt");
  77. _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  78. var process = _processFactory.Create(new ProcessOptions
  79. {
  80. CreateNoWindow = true,
  81. UseShellExecute = true,
  82. // Must consume both stdout and stderr or deadlocks may occur
  83. //RedirectStandardOutput = true,
  84. RedirectStandardError = false,
  85. RedirectStandardInput = false,
  86. FileName = _mediaEncoder.EncoderPath,
  87. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  88. IsHidden = true,
  89. ErrorDialog = false,
  90. EnableRaisingEvents = true,
  91. WorkingDirectory = Path.GetDirectoryName(logFilePath)
  92. });
  93. _process = process;
  94. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  95. _logger.Info(commandLineLogMessage);
  96. _mediaEncoder.SetLogFilename(Path.GetFileName(logFilePath));
  97. //var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  98. process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile);
  99. process.Start();
  100. cancellationToken.Register(Stop);
  101. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  102. //process.BeginOutputReadLine();
  103. onStarted();
  104. _logger.Info("ffmpeg recording process started for {0}", _targetPath);
  105. _mediaEncoder.ClearLogFilename();
  106. return _taskCompletionSource.Task;
  107. }
  108. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
  109. {
  110. string videoArgs;
  111. if (EncodeVideo(mediaSource))
  112. {
  113. var maxBitrate = 25000000;
  114. videoArgs = string.Format(
  115. "-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",
  116. GetOutputSizeParam(),
  117. maxBitrate.ToString(CultureInfo.InvariantCulture));
  118. }
  119. else
  120. {
  121. videoArgs = "-codec:v:0 copy";
  122. }
  123. var durationParam = " -t " + _mediaEncoder.GetTimeParameter(duration.Ticks);
  124. var inputModifiers = "-fflags +genpts -async 1 -vsync -1";
  125. var commandLineArgs = "-i \"{0}\"{4} -sn {2} -map_metadata -1 -threads 0 {3} -loglevel info -y \"{1}\"";
  126. long startTimeTicks = 0;
  127. //if (mediaSource.DateLiveStreamOpened.HasValue)
  128. //{
  129. // var elapsed = DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value;
  130. // elapsed -= TimeSpan.FromSeconds(10);
  131. // if (elapsed.TotalSeconds >= 0)
  132. // {
  133. // startTimeTicks = elapsed.Ticks + startTimeTicks;
  134. // }
  135. //}
  136. if (mediaSource.ReadAtNativeFramerate)
  137. {
  138. inputModifiers += " -re";
  139. }
  140. if (startTimeTicks > 0)
  141. {
  142. inputModifiers = "-ss " + _mediaEncoder.GetTimeParameter(startTimeTicks) + " " + inputModifiers;
  143. }
  144. var analyzeDurationSeconds = 5;
  145. var analyzeDuration = " -analyzeduration " +
  146. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  147. inputModifiers += analyzeDuration;
  148. commandLineArgs = string.Format(commandLineArgs, inputTempFile, targetFile, videoArgs, GetAudioArgs(mediaSource), durationParam);
  149. return inputModifiers + " " + commandLineArgs;
  150. }
  151. private string GetAudioArgs(MediaSourceInfo mediaSource)
  152. {
  153. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  154. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  155. // do not copy aac because many players have difficulty with aac_latm
  156. if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings && !string.Equals(inputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  157. {
  158. return "-codec:a:0 copy";
  159. }
  160. var audioChannels = 2;
  161. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  162. if (audioStream != null)
  163. {
  164. audioChannels = audioStream.Channels ?? audioChannels;
  165. }
  166. return "-codec:a:0 aac -strict experimental -ab 320000";
  167. }
  168. private bool EncodeVideo(MediaSourceInfo mediaSource)
  169. {
  170. if (string.Equals(_liveTvOptions.RecordedVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  171. {
  172. return false;
  173. }
  174. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  175. return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced);
  176. }
  177. protected string GetOutputSizeParam()
  178. {
  179. var filters = new List<string>();
  180. filters.Add("yadif=0:-1:0");
  181. var output = string.Empty;
  182. if (filters.Count > 0)
  183. {
  184. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  185. }
  186. return output;
  187. }
  188. private bool _isCancelled;
  189. private void Stop()
  190. {
  191. if (!_hasExited)
  192. {
  193. try
  194. {
  195. _isCancelled = true;
  196. _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
  197. _process.Kill();
  198. //_process.StandardInput.WriteLine("q");
  199. }
  200. catch (Exception ex)
  201. {
  202. _logger.ErrorException("Error killing transcoding job for {0}", ex, _targetPath);
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// Processes the exited.
  208. /// </summary>
  209. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  210. {
  211. _hasExited = true;
  212. try
  213. {
  214. var exitCode = _isCancelled ? 0 : process.ExitCode;
  215. _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath);
  216. if (exitCode == 0)
  217. {
  218. _taskCompletionSource.TrySetResult(true);
  219. }
  220. else
  221. {
  222. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode)));
  223. }
  224. }
  225. catch
  226. {
  227. _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath);
  228. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath)));
  229. }
  230. }
  231. }
  232. }