EncodedRecorder.cs 12 KB

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