EncodedRecorder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Configuration;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Model.Configuration;
  16. using MediaBrowser.Model.Diagnostics;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Serialization;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  22. {
  23. public class EncodedRecorder : IRecorder
  24. {
  25. private readonly ILogger _logger;
  26. private readonly IMediaEncoder _mediaEncoder;
  27. private readonly IServerApplicationPaths _appPaths;
  28. private bool _hasExited;
  29. private Stream _logFileStream;
  30. private string _targetPath;
  31. private IProcess _process;
  32. private readonly IProcessFactory _processFactory;
  33. private readonly IJsonSerializer _json;
  34. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  35. private readonly IServerConfigurationManager _config;
  36. public EncodedRecorder(
  37. ILogger logger,
  38. IMediaEncoder mediaEncoder,
  39. IServerApplicationPaths appPaths,
  40. IJsonSerializer json,
  41. IProcessFactory processFactory,
  42. IServerConfigurationManager config)
  43. {
  44. _logger = logger;
  45. _mediaEncoder = mediaEncoder;
  46. _appPaths = appPaths;
  47. _json = json;
  48. _processFactory = processFactory;
  49. _config = config;
  50. }
  51. private static bool CopySubtitles => false;
  52. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  53. {
  54. return Path.ChangeExtension(targetFile, ".ts");
  55. }
  56. public async Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  57. {
  58. // The media source is infinite so we need to handle stopping ourselves
  59. var durationToken = new CancellationTokenSource(duration);
  60. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  61. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
  62. _logger.LogInformation("Recording completed to file {0}", targetFile);
  63. }
  64. private EncodingOptions GetEncodingOptions()
  65. {
  66. return _config.GetConfiguration<EncodingOptions>("encoding");
  67. }
  68. private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  69. {
  70. _targetPath = targetFile;
  71. Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
  72. var process = _processFactory.Create(new ProcessOptions
  73. {
  74. CreateNoWindow = true,
  75. UseShellExecute = false,
  76. RedirectStandardError = true,
  77. RedirectStandardInput = true,
  78. FileName = _mediaEncoder.EncoderPath,
  79. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  80. IsHidden = true,
  81. ErrorDialog = false,
  82. EnableRaisingEvents = true
  83. });
  84. _process = process;
  85. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  86. _logger.LogInformation(commandLineLogMessage);
  87. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  88. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  89. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  90. _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  91. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  92. _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);
  93. process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile);
  94. process.Start();
  95. cancellationToken.Register(Stop);
  96. onStarted();
  97. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  98. StartStreamingLog(process.StandardError.BaseStream, _logFileStream);
  99. _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
  100. return _taskCompletionSource.Task;
  101. }
  102. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
  103. {
  104. string videoArgs;
  105. if (EncodeVideo(mediaSource))
  106. {
  107. const int MaxBitrate = 25000000;
  108. videoArgs = string.Format(
  109. CultureInfo.InvariantCulture,
  110. "-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",
  111. GetOutputSizeParam(),
  112. MaxBitrate);
  113. }
  114. else
  115. {
  116. videoArgs = "-codec:v:0 copy";
  117. }
  118. videoArgs += " -fflags +genpts";
  119. var flags = new List<string>();
  120. if (mediaSource.IgnoreDts)
  121. {
  122. flags.Add("+igndts");
  123. }
  124. if (mediaSource.IgnoreIndex)
  125. {
  126. flags.Add("+ignidx");
  127. }
  128. if (mediaSource.GenPtsInput)
  129. {
  130. flags.Add("+genpts");
  131. }
  132. var inputModifier = "-async 1 -vsync -1";
  133. if (flags.Count > 0)
  134. {
  135. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  136. }
  137. if (mediaSource.ReadAtNativeFramerate)
  138. {
  139. inputModifier += " -re";
  140. }
  141. if (mediaSource.RequiresLooping)
  142. {
  143. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  144. }
  145. var analyzeDurationSeconds = 5;
  146. var analyzeDuration = " -analyzeduration " +
  147. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  148. inputModifier += analyzeDuration;
  149. var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
  150. //var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
  151. // " -f mp4 -movflags frag_keyframe+empty_moov" :
  152. // string.Empty;
  153. var outputParam = string.Empty;
  154. var commandLineArgs = string.Format(
  155. CultureInfo.InvariantCulture,
  156. "-i \"{0}\" {2} -map_metadata -1 -threads 0 {3}{4}{5} -y \"{1}\"",
  157. inputTempFile,
  158. targetFile,
  159. videoArgs,
  160. GetAudioArgs(mediaSource),
  161. subtitleArgs,
  162. outputParam);
  163. return inputModifier + " " + commandLineArgs;
  164. }
  165. private static string GetAudioArgs(MediaSourceInfo mediaSource)
  166. {
  167. return "-codec:a:0 copy";
  168. //var audioChannels = 2;
  169. //var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  170. //if (audioStream != null)
  171. //{
  172. // audioChannels = audioStream.Channels ?? audioChannels;
  173. //}
  174. //return "-codec:a:0 aac -strict experimental -ab 320000";
  175. }
  176. private static bool EncodeVideo(MediaSourceInfo mediaSource)
  177. {
  178. return false;
  179. }
  180. protected string GetOutputSizeParam()
  181. {
  182. var filters = new List<string>();
  183. filters.Add("yadif=0:-1:0");
  184. var output = string.Empty;
  185. if (filters.Count > 0)
  186. {
  187. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  188. }
  189. return output;
  190. }
  191. private void Stop()
  192. {
  193. if (!_hasExited)
  194. {
  195. try
  196. {
  197. _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
  198. _process.StandardInput.WriteLine("q");
  199. }
  200. catch (Exception ex)
  201. {
  202. _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
  203. }
  204. if (_hasExited)
  205. {
  206. return;
  207. }
  208. try
  209. {
  210. _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
  211. if (_process.WaitForExit(10000))
  212. {
  213. return;
  214. }
  215. }
  216. catch (Exception ex)
  217. {
  218. _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
  219. }
  220. if (_hasExited)
  221. {
  222. return;
  223. }
  224. try
  225. {
  226. _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
  227. _process.Kill();
  228. }
  229. catch (Exception ex)
  230. {
  231. _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
  232. }
  233. }
  234. }
  235. /// <summary>
  236. /// Processes the exited.
  237. /// </summary>
  238. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  239. {
  240. _hasExited = true;
  241. _logFileStream?.Dispose();
  242. _logFileStream = null;
  243. var exitCode = process.ExitCode;
  244. _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath);
  245. if (exitCode == 0)
  246. {
  247. _taskCompletionSource.TrySetResult(true);
  248. }
  249. else
  250. {
  251. _taskCompletionSource.TrySetException(
  252. new Exception(
  253. string.Format(
  254. CultureInfo.InvariantCulture,
  255. "Recording for {0} failed. Exit code {1}",
  256. _targetPath,
  257. exitCode)));
  258. }
  259. }
  260. private async void StartStreamingLog(Stream source, Stream target)
  261. {
  262. try
  263. {
  264. using (var reader = new StreamReader(source))
  265. {
  266. while (!reader.EndOfStream)
  267. {
  268. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  269. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  270. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  271. await target.FlushAsync().ConfigureAwait(false);
  272. }
  273. }
  274. }
  275. catch (ObjectDisposedException)
  276. {
  277. // TODO Investigate and properly fix.
  278. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  279. }
  280. catch (Exception ex)
  281. {
  282. _logger.LogError(ex, "Error reading ffmpeg recording log");
  283. }
  284. }
  285. }
  286. }