EncodedRecorder.cs 15 KB

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