EncodedRecorder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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.Extensions;
  13. using MediaBrowser.Common.Json;
  14. using MediaBrowser.Controller;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.MediaEncoding;
  18. using MediaBrowser.Model.Dto;
  19. using MediaBrowser.Model.IO;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  22. {
  23. public class EncodedRecorder : IRecorder
  24. {
  25. private readonly ILogger _logger;
  26. private readonly IMediaEncoder _mediaEncoder;
  27. private readonly IServerApplicationPaths _appPaths;
  28. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  29. private readonly IServerConfigurationManager _serverConfigurationManager;
  30. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  31. private bool _hasExited;
  32. private Stream _logFileStream;
  33. private string _targetPath;
  34. private Process _process;
  35. public EncodedRecorder(
  36. ILogger logger,
  37. IMediaEncoder mediaEncoder,
  38. IServerApplicationPaths appPaths,
  39. IServerConfigurationManager serverConfigurationManager)
  40. {
  41. _logger = logger;
  42. _mediaEncoder = mediaEncoder;
  43. _appPaths = appPaths;
  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 async 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. await JsonSerializer.SerializeAsync(_logFileStream, mediaSource, _jsonOptions, cancellationToken).ConfigureAwait(false);
  81. await _logFileStream.WriteAsync(Encoding.UTF8.GetBytes(Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine), cancellationToken).ConfigureAwait(false);
  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. }
  95. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
  96. {
  97. string videoArgs;
  98. if (EncodeVideo(mediaSource))
  99. {
  100. const int MaxBitrate = 25000000;
  101. videoArgs = string.Format(
  102. CultureInfo.InvariantCulture,
  103. "-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",
  104. GetOutputSizeParam(),
  105. MaxBitrate);
  106. }
  107. else
  108. {
  109. videoArgs = "-codec:v:0 copy";
  110. }
  111. videoArgs += " -fflags +genpts";
  112. var flags = new List<string>();
  113. if (mediaSource.IgnoreDts)
  114. {
  115. flags.Add("+igndts");
  116. }
  117. if (mediaSource.IgnoreIndex)
  118. {
  119. flags.Add("+ignidx");
  120. }
  121. if (mediaSource.GenPtsInput)
  122. {
  123. flags.Add("+genpts");
  124. }
  125. var inputModifier = "-async 1 -vsync -1";
  126. if (flags.Count > 0)
  127. {
  128. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  129. }
  130. if (mediaSource.ReadAtNativeFramerate)
  131. {
  132. inputModifier += " -re";
  133. }
  134. if (mediaSource.RequiresLooping)
  135. {
  136. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  137. }
  138. var analyzeDurationSeconds = 5;
  139. var analyzeDuration = " -analyzeduration " +
  140. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  141. inputModifier += analyzeDuration;
  142. var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
  143. // var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
  144. // " -f mp4 -movflags frag_keyframe+empty_moov" :
  145. // string.Empty;
  146. var outputParam = string.Empty;
  147. var threads = EncodingHelper.GetNumberOfThreads(null, _serverConfigurationManager.GetEncodingOptions(), null);
  148. var commandLineArgs = string.Format(
  149. CultureInfo.InvariantCulture,
  150. "-i \"{0}\" {2} -map_metadata -1 -threads {6} {3}{4}{5} -y \"{1}\"",
  151. inputTempFile,
  152. targetFile,
  153. videoArgs,
  154. GetAudioArgs(mediaSource),
  155. subtitleArgs,
  156. outputParam,
  157. threads);
  158. return inputModifier + " " + commandLineArgs;
  159. }
  160. private static string GetAudioArgs(MediaSourceInfo mediaSource)
  161. {
  162. return "-codec:a:0 copy";
  163. // var audioChannels = 2;
  164. // var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  165. // if (audioStream != null)
  166. //{
  167. // audioChannels = audioStream.Channels ?? audioChannels;
  168. //}
  169. // return "-codec:a:0 aac -strict experimental -ab 320000";
  170. }
  171. private static bool EncodeVideo(MediaSourceInfo mediaSource)
  172. {
  173. return false;
  174. }
  175. protected string GetOutputSizeParam()
  176. => "-vf \"yadif=0:-1:0\"";
  177. private void Stop()
  178. {
  179. if (!_hasExited)
  180. {
  181. try
  182. {
  183. _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
  184. _process.StandardInput.WriteLine("q");
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
  189. }
  190. if (_hasExited)
  191. {
  192. return;
  193. }
  194. try
  195. {
  196. _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
  197. if (_process.WaitForExit(10000))
  198. {
  199. return;
  200. }
  201. }
  202. catch (Exception ex)
  203. {
  204. _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
  205. }
  206. if (_hasExited)
  207. {
  208. return;
  209. }
  210. try
  211. {
  212. _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
  213. _process.Kill();
  214. }
  215. catch (Exception ex)
  216. {
  217. _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// Processes the exited.
  223. /// </summary>
  224. private void OnFfMpegProcessExited(Process process)
  225. {
  226. using (process)
  227. {
  228. _hasExited = true;
  229. _logFileStream?.Dispose();
  230. _logFileStream = null;
  231. var exitCode = process.ExitCode;
  232. _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {Path}", exitCode, _targetPath);
  233. if (exitCode == 0)
  234. {
  235. _taskCompletionSource.TrySetResult(true);
  236. }
  237. else
  238. {
  239. _taskCompletionSource.TrySetException(
  240. new Exception(
  241. string.Format(
  242. CultureInfo.InvariantCulture,
  243. "Recording for {0} failed. Exit code {1}",
  244. _targetPath,
  245. exitCode)));
  246. }
  247. }
  248. }
  249. private async Task StartStreamingLog(Stream source, Stream target)
  250. {
  251. try
  252. {
  253. using (var reader = new StreamReader(source))
  254. {
  255. await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
  256. {
  257. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  258. await target.WriteAsync(bytes.AsMemory()).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. }