EncodedRecorder.cs 12 KB

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