EncodedRecorder.cs 13 KB

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