EncodedRecorder.cs 12 KB

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