EncodedRecorder.cs 15 KB

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