EncodedRecorder.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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(_fileSystem.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(_fileSystem.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 outputParam = string.Empty;
  179. var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"",
  180. inputTempFile,
  181. targetFile,
  182. videoArgs,
  183. GetAudioArgs(mediaSource),
  184. subtitleArgs,
  185. durationParam,
  186. outputParam);
  187. return inputModifiers + " " + commandLineArgs;
  188. }
  189. private string GetAudioArgs(MediaSourceInfo mediaSource)
  190. {
  191. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  192. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  193. // do not copy aac because many players have difficulty with aac_latm
  194. if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings && !string.Equals(inputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  195. {
  196. return "-codec:a:0 copy";
  197. }
  198. var audioChannels = 2;
  199. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  200. if (audioStream != null)
  201. {
  202. audioChannels = audioStream.Channels ?? audioChannels;
  203. }
  204. return "-codec:a:0 aac -strict experimental -ab 320000";
  205. }
  206. private bool EncodeVideo(MediaSourceInfo mediaSource)
  207. {
  208. if (string.Equals(_liveTvOptions.RecordedVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  209. {
  210. return false;
  211. }
  212. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  213. return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced);
  214. }
  215. protected string GetOutputSizeParam()
  216. {
  217. var filters = new List<string>();
  218. filters.Add("yadif=0:-1:0");
  219. var output = string.Empty;
  220. if (filters.Count > 0)
  221. {
  222. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  223. }
  224. return output;
  225. }
  226. private void Stop()
  227. {
  228. if (!_hasExited)
  229. {
  230. try
  231. {
  232. _logger.Info("Stopping ffmpeg recording process for {0}", _targetPath);
  233. //process.Kill();
  234. _process.StandardInput.WriteLine("q");
  235. }
  236. catch (Exception ex)
  237. {
  238. _logger.ErrorException("Error stopping recording transcoding job for {0}", ex, _targetPath);
  239. }
  240. if (_hasExited)
  241. {
  242. return;
  243. }
  244. try
  245. {
  246. _logger.Info("Calling recording process.WaitForExit for {0}", _targetPath);
  247. if (_process.WaitForExit(10000))
  248. {
  249. return;
  250. }
  251. }
  252. catch (Exception ex)
  253. {
  254. _logger.ErrorException("Error waiting for recording process to exit for {0}", ex, _targetPath);
  255. }
  256. if (_hasExited)
  257. {
  258. return;
  259. }
  260. try
  261. {
  262. _logger.Info("Killing ffmpeg recording process for {0}", _targetPath);
  263. _process.Kill();
  264. }
  265. catch (Exception ex)
  266. {
  267. _logger.ErrorException("Error killing recording transcoding job for {0}", ex, _targetPath);
  268. }
  269. }
  270. }
  271. /// <summary>
  272. /// Processes the exited.
  273. /// </summary>
  274. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  275. {
  276. _hasExited = true;
  277. DisposeLogStream();
  278. try
  279. {
  280. var exitCode = process.ExitCode;
  281. _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath);
  282. if (exitCode == 0)
  283. {
  284. _taskCompletionSource.TrySetResult(true);
  285. }
  286. else
  287. {
  288. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode)));
  289. }
  290. }
  291. catch
  292. {
  293. _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath);
  294. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath)));
  295. }
  296. }
  297. private void DisposeLogStream()
  298. {
  299. if (_logFileStream != null)
  300. {
  301. try
  302. {
  303. _logFileStream.Dispose();
  304. }
  305. catch (Exception ex)
  306. {
  307. _logger.ErrorException("Error disposing recording log stream", ex);
  308. }
  309. _logFileStream = null;
  310. }
  311. }
  312. private async void StartStreamingLog(Stream source, Stream target)
  313. {
  314. try
  315. {
  316. using (var reader = new StreamReader(source))
  317. {
  318. while (!reader.EndOfStream)
  319. {
  320. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  321. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  322. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  323. await target.FlushAsync().ConfigureAwait(false);
  324. }
  325. }
  326. }
  327. catch (ObjectDisposedException)
  328. {
  329. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  330. }
  331. catch (Exception ex)
  332. {
  333. _logger.ErrorException("Error reading ffmpeg recording log", ex);
  334. }
  335. }
  336. }
  337. }