EncodedRecorder.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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, IDisposable
  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>(TaskCreationOptions.RunContinuationsAsynchronously);
  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. private bool _disposed = false;
  37. public EncodedRecorder(
  38. ILogger logger,
  39. IMediaEncoder mediaEncoder,
  40. IServerApplicationPaths appPaths,
  41. IServerConfigurationManager serverConfigurationManager)
  42. {
  43. _logger = logger;
  44. _mediaEncoder = mediaEncoder;
  45. _appPaths = appPaths;
  46. _serverConfigurationManager = serverConfigurationManager;
  47. }
  48. private static bool CopySubtitles => false;
  49. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  50. {
  51. return Path.ChangeExtension(targetFile, ".ts");
  52. }
  53. public async Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  54. {
  55. // The media source is infinite so we need to handle stopping ourselves
  56. using var durationToken = new CancellationTokenSource(duration);
  57. using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token);
  58. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, onStarted, cancellationTokenSource.Token).ConfigureAwait(false);
  59. _logger.LogInformation("Recording completed to file {Path}", targetFile);
  60. }
  61. private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, Action onStarted, CancellationToken cancellationToken)
  62. {
  63. _targetPath = targetFile;
  64. Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
  65. var processStartInfo = new ProcessStartInfo
  66. {
  67. CreateNoWindow = true,
  68. UseShellExecute = false,
  69. RedirectStandardError = true,
  70. RedirectStandardInput = true,
  71. FileName = _mediaEncoder.EncoderPath,
  72. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile),
  73. WindowStyle = ProcessWindowStyle.Hidden,
  74. ErrorDialog = false
  75. };
  76. _logger.LogInformation("{Filename} {Arguments}", processStartInfo.FileName, processStartInfo.Arguments);
  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.CreateNew, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  81. await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false);
  82. await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + processStartInfo.FileName + " " + processStartInfo.Arguments + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false);
  83. _process = new Process
  84. {
  85. StartInfo = processStartInfo,
  86. EnableRaisingEvents = true
  87. };
  88. _process.Exited += (_, _) => 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 {Path}", _targetPath);
  95. // Block until ffmpeg exits
  96. await _taskCompletionSource.Task.ConfigureAwait(false);
  97. }
  98. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile)
  99. {
  100. string videoArgs;
  101. if (EncodeVideo(mediaSource))
  102. {
  103. const int MaxBitrate = 25000000;
  104. videoArgs = string.Format(
  105. CultureInfo.InvariantCulture,
  106. "-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",
  107. GetOutputSizeParam(),
  108. MaxBitrate);
  109. }
  110. else
  111. {
  112. videoArgs = "-codec:v:0 copy";
  113. }
  114. videoArgs += " -fflags +genpts";
  115. var flags = new List<string>();
  116. if (mediaSource.IgnoreDts)
  117. {
  118. flags.Add("+igndts");
  119. }
  120. if (mediaSource.IgnoreIndex)
  121. {
  122. flags.Add("+ignidx");
  123. }
  124. if (mediaSource.GenPtsInput)
  125. {
  126. flags.Add("+genpts");
  127. }
  128. var inputModifier = "-async 1 -vsync -1";
  129. if (flags.Count > 0)
  130. {
  131. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  132. }
  133. if (mediaSource.ReadAtNativeFramerate)
  134. {
  135. inputModifier += " -re";
  136. }
  137. if (mediaSource.RequiresLooping)
  138. {
  139. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  140. }
  141. var analyzeDurationSeconds = 5;
  142. var analyzeDuration = " -analyzeduration " +
  143. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  144. inputModifier += analyzeDuration;
  145. var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
  146. // var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
  147. // " -f mp4 -movflags frag_keyframe+empty_moov" :
  148. // string.Empty;
  149. var outputParam = string.Empty;
  150. var threads = EncodingHelper.GetNumberOfThreads(null, _serverConfigurationManager.GetEncodingOptions(), null);
  151. var commandLineArgs = string.Format(
  152. CultureInfo.InvariantCulture,
  153. "-i \"{0}\" {2} -map_metadata -1 -threads {6} {3}{4}{5} -y \"{1}\"",
  154. inputTempFile,
  155. targetFile.Replace("\"", "\\\"", StringComparison.Ordinal), // Escape quotes in filename
  156. videoArgs,
  157. GetAudioArgs(mediaSource),
  158. subtitleArgs,
  159. outputParam,
  160. threads);
  161. return inputModifier + " " + commandLineArgs;
  162. }
  163. private static string GetAudioArgs(MediaSourceInfo mediaSource)
  164. {
  165. return "-codec:a:0 copy";
  166. // var audioChannels = 2;
  167. // var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  168. // if (audioStream != null)
  169. // {
  170. // audioChannels = audioStream.Channels ?? audioChannels;
  171. // }
  172. // return "-codec:a:0 aac -strict experimental -ab 320000";
  173. }
  174. private static bool EncodeVideo(MediaSourceInfo mediaSource)
  175. {
  176. return false;
  177. }
  178. protected string GetOutputSizeParam()
  179. => "-vf \"yadif=0:-1:0\"";
  180. private void Stop()
  181. {
  182. if (!_hasExited)
  183. {
  184. try
  185. {
  186. _logger.LogInformation("Stopping ffmpeg recording process for {Path}", _targetPath);
  187. _process.StandardInput.WriteLine("q");
  188. }
  189. catch (Exception ex)
  190. {
  191. _logger.LogError(ex, "Error stopping recording transcoding job for {Path}", _targetPath);
  192. }
  193. if (_hasExited)
  194. {
  195. return;
  196. }
  197. try
  198. {
  199. _logger.LogInformation("Calling recording process.WaitForExit for {Path}", _targetPath);
  200. if (_process.WaitForExit(10000))
  201. {
  202. return;
  203. }
  204. }
  205. catch (Exception ex)
  206. {
  207. _logger.LogError(ex, "Error waiting for recording process to exit for {Path}", _targetPath);
  208. }
  209. if (_hasExited)
  210. {
  211. return;
  212. }
  213. try
  214. {
  215. _logger.LogInformation("Killing ffmpeg recording process for {Path}", _targetPath);
  216. _process.Kill();
  217. }
  218. catch (Exception ex)
  219. {
  220. _logger.LogError(ex, "Error killing recording transcoding job for {Path}", _targetPath);
  221. }
  222. }
  223. }
  224. /// <summary>
  225. /// Processes the exited.
  226. /// </summary>
  227. private void OnFfMpegProcessExited(Process process)
  228. {
  229. using (process)
  230. {
  231. _hasExited = true;
  232. _logFileStream?.Dispose();
  233. _logFileStream = null;
  234. var exitCode = process.ExitCode;
  235. _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath);
  236. if (exitCode == 0)
  237. {
  238. _taskCompletionSource.TrySetResult(true);
  239. }
  240. else
  241. {
  242. _taskCompletionSource.TrySetException(
  243. new Exception(
  244. string.Format(
  245. CultureInfo.InvariantCulture,
  246. "Recording for {0} failed. Exit code {1}",
  247. _targetPath,
  248. exitCode)));
  249. }
  250. }
  251. }
  252. private async Task StartStreamingLog(Stream source, Stream target)
  253. {
  254. try
  255. {
  256. using (var reader = new StreamReader(source))
  257. {
  258. await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
  259. {
  260. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  261. await target.WriteAsync(bytes.AsMemory()).ConfigureAwait(false);
  262. await target.FlushAsync().ConfigureAwait(false);
  263. }
  264. }
  265. }
  266. catch (Exception ex)
  267. {
  268. _logger.LogError(ex, "Error reading ffmpeg recording log");
  269. }
  270. }
  271. /// <inheritdoc />
  272. public void Dispose()
  273. {
  274. Dispose(true);
  275. GC.SuppressFinalize(this);
  276. }
  277. /// <summary>
  278. /// Releases unmanaged and optionally managed resources.
  279. /// </summary>
  280. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  281. protected virtual void Dispose(bool disposing)
  282. {
  283. if (_disposed)
  284. {
  285. return;
  286. }
  287. if (disposing)
  288. {
  289. _logFileStream?.Dispose();
  290. _process?.Dispose();
  291. }
  292. _logFileStream = null;
  293. _process = null;
  294. _disposed = true;
  295. }
  296. }
  297. }