EncodedRecorder.cs 12 KB

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