EncodedRecorder.cs 12 KB

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