EncodedRecorder.cs 14 KB

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