EncodedRecorder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Text;
  9. using System.Text.Json;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using Jellyfin.Extensions;
  13. using Jellyfin.Extensions.Json;
  14. using MediaBrowser.Common.Configuration;
  15. using MediaBrowser.Controller;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.MediaEncoding;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.IO;
  21. using Microsoft.Extensions.Logging;
  22. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  23. {
  24. public class EncodedRecorder : IRecorder
  25. {
  26. private readonly ILogger _logger;
  27. private readonly IMediaEncoder _mediaEncoder;
  28. private readonly IServerApplicationPaths _appPaths;
  29. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  30. private readonly IServerConfigurationManager _serverConfigurationManager;
  31. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  32. private bool _hasExited;
  33. private Stream _logFileStream;
  34. private string _targetPath;
  35. private Process _process;
  36. public EncodedRecorder(
  37. ILogger logger,
  38. IMediaEncoder mediaEncoder,
  39. IServerApplicationPaths appPaths,
  40. IServerConfigurationManager serverConfigurationManager)
  41. {
  42. _logger = logger;
  43. _mediaEncoder = mediaEncoder;
  44. _appPaths = appPaths;
  45. _serverConfigurationManager = serverConfigurationManager;
  46. }
  47. private static bool CopySubtitles => false;
  48. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  49. {
  50. return Path.ChangeExtension(targetFile, ".ts");
  51. }
  52. public async Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  53. {
  54. // The media source is infinite so we need to handle stopping ourselves
  55. using var durationToken = new CancellationTokenSource(duration);
  56. using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
  57. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationTokenSource.Token).ConfigureAwait(false);
  58. _logger.LogInformation("Recording completed to file {0}", targetFile);
  59. }
  60. private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  61. {
  62. _targetPath = targetFile;
  63. Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
  64. var processStartInfo = new ProcessStartInfo
  65. {
  66. CreateNoWindow = true,
  67. UseShellExecute = false,
  68. RedirectStandardError = true,
  69. RedirectStandardInput = true,
  70. FileName = _mediaEncoder.EncoderPath,
  71. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  72. WindowStyle = ProcessWindowStyle.Hidden,
  73. ErrorDialog = false
  74. };
  75. var commandLineLogMessage = processStartInfo.FileName + " " + processStartInfo.Arguments;
  76. _logger.LogInformation(commandLineLogMessage);
  77. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  78. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  79. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  80. _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  81. await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false);
  82. await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false);
  83. _process = new Process
  84. {
  85. StartInfo = processStartInfo,
  86. EnableRaisingEvents = true
  87. };
  88. _process.Exited += (sender, args) => OnFfMpegProcessExited(_process);
  89. _process.Start();
  90. cancellationToken.Register(Stop);
  91. onStarted();
  92. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  93. _ = StartStreamingLog(_process.StandardError.BaseStream, _logFileStream);
  94. _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
  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. await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
  257. {
  258. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  259. await target.WriteAsync(bytes.AsMemory()).ConfigureAwait(false);
  260. await target.FlushAsync().ConfigureAwait(false);
  261. }
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. _logger.LogError(ex, "Error reading ffmpeg recording log");
  267. }
  268. }
  269. }
  270. }