EncodedRecorder.cs 12 KB

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