EncodedRecorder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  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.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.MediaEncoding;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Serialization;
  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 bool _hasExited;
  29. private Stream _logFileStream;
  30. private string _targetPath;
  31. private Process _process;
  32. private readonly IJsonSerializer _json;
  33. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  34. private readonly IServerConfigurationManager _config;
  35. public EncodedRecorder(
  36. ILogger logger,
  37. IMediaEncoder mediaEncoder,
  38. IServerApplicationPaths appPaths,
  39. IJsonSerializer json,
  40. IServerConfigurationManager config)
  41. {
  42. _logger = logger;
  43. _mediaEncoder = mediaEncoder;
  44. _appPaths = appPaths;
  45. _json = json;
  46. _config = config;
  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. var durationToken = new CancellationTokenSource(duration);
  57. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  58. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
  59. _logger.LogInformation("Recording completed to file {0}", targetFile);
  60. }
  61. private EncodingOptions GetEncodingOptions()
  62. {
  63. return _config.GetConfiguration<EncodingOptions>("encoding");
  64. }
  65. private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  66. {
  67. _targetPath = targetFile;
  68. Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
  69. var processStartInfo = new ProcessStartInfo
  70. {
  71. CreateNoWindow = true,
  72. UseShellExecute = false,
  73. RedirectStandardError = true,
  74. RedirectStandardInput = true,
  75. FileName = _mediaEncoder.EncoderPath,
  76. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  77. WindowStyle = ProcessWindowStyle.Hidden,
  78. ErrorDialog = false
  79. };
  80. _process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
  81. var commandLineLogMessage = _process.StartInfo.FileName + " " + _process.StartInfo.Arguments;
  82. _logger.LogInformation(commandLineLogMessage);
  83. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  84. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  85. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  86. _logFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
  87. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  88. _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);
  89. _process.Exited += (sender, args) => OnFfMpegProcessExited(_process, inputFile);
  90. _process.Start();
  91. cancellationToken.Register(Stop);
  92. onStarted();
  93. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  94. StartStreamingLog(_process.StandardError.BaseStream, _logFileStream);
  95. _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
  96. return _taskCompletionSource.Task;
  97. }
  98. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
  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 commandLineArgs = string.Format(
  151. CultureInfo.InvariantCulture,
  152. "-i \"{0}\" {2} -map_metadata -1 -threads 0 {3}{4}{5} -y \"{1}\"",
  153. inputTempFile,
  154. targetFile,
  155. videoArgs,
  156. GetAudioArgs(mediaSource),
  157. subtitleArgs,
  158. outputParam);
  159. return inputModifier + " " + commandLineArgs;
  160. }
  161. private static string GetAudioArgs(MediaSourceInfo mediaSource)
  162. {
  163. return "-codec:a:0 copy";
  164. //var audioChannels = 2;
  165. //var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  166. //if (audioStream != null)
  167. //{
  168. // audioChannels = audioStream.Channels ?? audioChannels;
  169. //}
  170. //return "-codec:a:0 aac -strict experimental -ab 320000";
  171. }
  172. private static bool EncodeVideo(MediaSourceInfo mediaSource)
  173. {
  174. return false;
  175. }
  176. protected string GetOutputSizeParam()
  177. {
  178. var filters = new List<string>();
  179. filters.Add("yadif=0:-1:0");
  180. var output = string.Empty;
  181. if (filters.Count > 0)
  182. {
  183. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  184. }
  185. return output;
  186. }
  187. private void Stop()
  188. {
  189. if (!_hasExited)
  190. {
  191. try
  192. {
  193. _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
  194. _process.StandardInput.WriteLine("q");
  195. }
  196. catch (Exception ex)
  197. {
  198. _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
  199. }
  200. if (_hasExited)
  201. {
  202. return;
  203. }
  204. try
  205. {
  206. _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
  207. if (_process.WaitForExit(10000))
  208. {
  209. return;
  210. }
  211. }
  212. catch (Exception ex)
  213. {
  214. _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
  215. }
  216. if (_hasExited)
  217. {
  218. return;
  219. }
  220. try
  221. {
  222. _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
  223. _process.Kill();
  224. }
  225. catch (Exception ex)
  226. {
  227. _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Processes the exited.
  233. /// </summary>
  234. private void OnFfMpegProcessExited(Process process, string inputFile)
  235. {
  236. try
  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. finally
  259. {
  260. process.Dispose();
  261. }
  262. }
  263. private async void StartStreamingLog(Stream source, Stream target)
  264. {
  265. try
  266. {
  267. using (var reader = new StreamReader(source))
  268. {
  269. while (!reader.EndOfStream)
  270. {
  271. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  272. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  273. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  274. await target.FlushAsync().ConfigureAwait(false);
  275. }
  276. }
  277. }
  278. catch (ObjectDisposedException)
  279. {
  280. // TODO Investigate and properly fix.
  281. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  282. }
  283. catch (Exception ex)
  284. {
  285. _logger.LogError(ex, "Error reading ffmpeg recording log");
  286. }
  287. }
  288. }
  289. }