EncodedRecorder.cs 12 KB

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