EncodedRecorder.cs 11 KB

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