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