EncodedRecorder.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Common.IO;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.MediaEncoding;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Diagnostics;
  18. using MediaBrowser.Model.Dto;
  19. using MediaBrowser.Model.Entities;
  20. using MediaBrowser.Model.LiveTv;
  21. using MediaBrowser.Model.Logging;
  22. using MediaBrowser.Model.Serialization;
  23. using MediaBrowser.Common.Configuration;
  24. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  25. {
  26. public class EncodedRecorder : IRecorder
  27. {
  28. private readonly ILogger _logger;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly IHttpClient _httpClient;
  31. private readonly IMediaEncoder _mediaEncoder;
  32. private readonly IServerApplicationPaths _appPaths;
  33. private readonly LiveTvOptions _liveTvOptions;
  34. private bool _hasExited;
  35. private Stream _logFileStream;
  36. private string _targetPath;
  37. private IProcess _process;
  38. private readonly IProcessFactory _processFactory;
  39. private readonly IJsonSerializer _json;
  40. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  41. private readonly IServerConfigurationManager _config;
  42. public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IServerApplicationPaths appPaths, IJsonSerializer json, LiveTvOptions liveTvOptions, IHttpClient httpClient, IProcessFactory processFactory, IServerConfigurationManager config)
  43. {
  44. _logger = logger;
  45. _fileSystem = fileSystem;
  46. _mediaEncoder = mediaEncoder;
  47. _appPaths = appPaths;
  48. _json = json;
  49. _liveTvOptions = liveTvOptions;
  50. _httpClient = httpClient;
  51. _processFactory = processFactory;
  52. _config = config;
  53. }
  54. private string OutputFormat
  55. {
  56. get
  57. {
  58. var format = _liveTvOptions.RecordingEncodingFormat;
  59. if (string.Equals(format, "mkv", StringComparison.OrdinalIgnoreCase))
  60. {
  61. return "mkv";
  62. }
  63. return "mp4";
  64. }
  65. }
  66. private bool CopySubtitles
  67. {
  68. get
  69. {
  70. return false;
  71. //return string.Equals(OutputFormat, "mkv", StringComparison.OrdinalIgnoreCase);
  72. }
  73. }
  74. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  75. {
  76. var extension = OutputFormat;
  77. if (string.Equals(extension, "mpegts", StringComparison.OrdinalIgnoreCase))
  78. {
  79. extension = "ts";
  80. }
  81. return Path.ChangeExtension(targetFile, "." + extension);
  82. }
  83. public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  84. {
  85. //var durationToken = new CancellationTokenSource(duration);
  86. //cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  87. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
  88. _logger.Info("Recording completed to file {0}", targetFile);
  89. }
  90. private EncodingOptions GetEncodingOptions()
  91. {
  92. return _config.GetConfiguration<EncodingOptions>("encoding");
  93. }
  94. private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  95. {
  96. _targetPath = targetFile;
  97. _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile));
  98. var process = _processFactory.Create(new ProcessOptions
  99. {
  100. CreateNoWindow = true,
  101. UseShellExecute = false,
  102. // Must consume both stdout and stderr or deadlocks may occur
  103. //RedirectStandardOutput = true,
  104. RedirectStandardError = true,
  105. RedirectStandardInput = true,
  106. FileName = _mediaEncoder.EncoderPath,
  107. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  108. IsHidden = true,
  109. ErrorDialog = false,
  110. EnableRaisingEvents = true
  111. });
  112. _process = process;
  113. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  114. _logger.Info(commandLineLogMessage);
  115. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  116. _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  117. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  118. _logFileStream = _fileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
  119. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  120. _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);
  121. process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile);
  122. process.Start();
  123. cancellationToken.Register(Stop);
  124. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  125. //process.BeginOutputReadLine();
  126. onStarted();
  127. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  128. StartStreamingLog(process.StandardError.BaseStream, _logFileStream);
  129. _logger.Info("ffmpeg recording process started for {0}", _targetPath);
  130. return _taskCompletionSource.Task;
  131. }
  132. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
  133. {
  134. string videoArgs;
  135. if (EncodeVideo(mediaSource))
  136. {
  137. var maxBitrate = 25000000;
  138. videoArgs = string.Format(
  139. "-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",
  140. GetOutputSizeParam(),
  141. maxBitrate.ToString(CultureInfo.InvariantCulture));
  142. }
  143. else
  144. {
  145. videoArgs = "-codec:v:0 copy";
  146. }
  147. var durationParam = " -t " + _mediaEncoder.GetTimeParameter(duration.Ticks);
  148. var flags = new List<string>();
  149. if (mediaSource.IgnoreDts)
  150. {
  151. flags.Add("+igndts");
  152. }
  153. if (mediaSource.IgnoreIndex)
  154. {
  155. flags.Add("+ignidx");
  156. }
  157. var inputModifiers = "-async 1 -vsync -1";
  158. if (flags.Count > 0)
  159. {
  160. inputModifiers += " -fflags " + string.Join("", flags.ToArray());
  161. }
  162. if (!string.IsNullOrWhiteSpace(GetEncodingOptions().HardwareAccelerationType))
  163. {
  164. inputModifiers += " -hwaccel auto";
  165. }
  166. if (mediaSource.ReadAtNativeFramerate)
  167. {
  168. inputModifiers += " -re";
  169. }
  170. var analyzeDurationSeconds = 5;
  171. var analyzeDuration = " -analyzeduration " +
  172. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  173. inputModifiers += analyzeDuration;
  174. var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
  175. var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
  176. " -f mp4 -movflags frag_keyframe+empty_moov" :
  177. string.Empty;
  178. var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"",
  179. inputTempFile,
  180. targetFile,
  181. videoArgs,
  182. GetAudioArgs(mediaSource),
  183. subtitleArgs,
  184. durationParam,
  185. outputParam);
  186. return inputModifiers + " " + commandLineArgs;
  187. }
  188. private string GetAudioArgs(MediaSourceInfo mediaSource)
  189. {
  190. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  191. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  192. // do not copy aac because many players have difficulty with aac_latm
  193. if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings && !string.Equals(inputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  194. {
  195. return "-codec:a:0 copy";
  196. }
  197. var audioChannels = 2;
  198. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  199. if (audioStream != null)
  200. {
  201. audioChannels = audioStream.Channels ?? audioChannels;
  202. }
  203. return "-codec:a:0 aac -strict experimental -ab 320000";
  204. }
  205. private bool EncodeVideo(MediaSourceInfo mediaSource)
  206. {
  207. if (string.Equals(_liveTvOptions.RecordedVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  208. {
  209. return false;
  210. }
  211. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  212. return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced);
  213. }
  214. protected string GetOutputSizeParam()
  215. {
  216. var filters = new List<string>();
  217. filters.Add("yadif=0:-1:0");
  218. var output = string.Empty;
  219. if (filters.Count > 0)
  220. {
  221. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  222. }
  223. return output;
  224. }
  225. private void Stop()
  226. {
  227. if (!_hasExited)
  228. {
  229. try
  230. {
  231. _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath);
  232. //process.Kill();
  233. _process.StandardInput.WriteLine("q");
  234. }
  235. catch (Exception ex)
  236. {
  237. _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath);
  238. }
  239. if (_hasExited)
  240. {
  241. return;
  242. }
  243. try
  244. {
  245. _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath);
  246. if (_process.WaitForExit(10000))
  247. {
  248. return;
  249. }
  250. }
  251. catch (Exception ex)
  252. {
  253. _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath);
  254. }
  255. if (_hasExited)
  256. {
  257. return;
  258. }
  259. try
  260. {
  261. _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
  262. _process.Kill();
  263. }
  264. catch (Exception ex)
  265. {
  266. _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath);
  267. }
  268. }
  269. }
  270. /// <summary>
  271. /// Processes the exited.
  272. /// </summary>
  273. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  274. {
  275. _hasExited = true;
  276. DisposeLogStream();
  277. try
  278. {
  279. var exitCode = process.ExitCode;
  280. _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath);
  281. if (exitCode == 0)
  282. {
  283. _taskCompletionSource.TrySetResult(true);
  284. }
  285. else
  286. {
  287. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode)));
  288. }
  289. }
  290. catch
  291. {
  292. _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath);
  293. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath)));
  294. }
  295. }
  296. private void DisposeLogStream()
  297. {
  298. if (_logFileStream != null)
  299. {
  300. try
  301. {
  302. _logFileStream.Dispose();
  303. }
  304. catch (Exception ex)
  305. {
  306. _logger.ErrorException("Error disposing recording log stream", ex);
  307. }
  308. _logFileStream = null;
  309. }
  310. }
  311. private async void StartStreamingLog(Stream source, Stream target)
  312. {
  313. try
  314. {
  315. using (var reader = new StreamReader(source))
  316. {
  317. while (!reader.EndOfStream)
  318. {
  319. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  320. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  321. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  322. await target.FlushAsync().ConfigureAwait(false);
  323. }
  324. }
  325. }
  326. catch (ObjectDisposedException)
  327. {
  328. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  329. }
  330. catch (Exception ex)
  331. {
  332. _logger.ErrorException("Error reading ffmpeg recording log", ex);
  333. }
  334. }
  335. }
  336. }