EncodedRecorder.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  47. {
  48. return Path.ChangeExtension(targetFile, ".mp4");
  49. }
  50. public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  51. {
  52. var tempfile = Path.Combine(_appPaths.TranscodingTempPath, Guid.NewGuid().ToString("N") + ".ts");
  53. try
  54. {
  55. await RecordInternal(mediaSource, tempfile, targetFile, duration, onStarted, cancellationToken)
  56. .ConfigureAwait(false);
  57. }
  58. finally
  59. {
  60. File.Delete(tempfile);
  61. }
  62. }
  63. public async Task RecordInternal(MediaSourceInfo mediaSource, string tempFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  64. {
  65. var httpRequestOptions = new HttpRequestOptions()
  66. {
  67. Url = mediaSource.Path
  68. };
  69. httpRequestOptions.BufferContent = false;
  70. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
  71. {
  72. _logger.Info("Opened recording stream from tuner provider");
  73. Directory.CreateDirectory(Path.GetDirectoryName(tempFile));
  74. using (var output = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read))
  75. {
  76. //onStarted();
  77. _logger.Info("Copying recording stream to file {0}", tempFile);
  78. var bufferMs = 5000;
  79. if (mediaSource.RunTimeTicks.HasValue)
  80. {
  81. // The media source already has a fixed duration
  82. // But add another stop 1 minute later just in case the recording gets stuck for any reason
  83. var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1)));
  84. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  85. }
  86. else
  87. {
  88. // The media source if infinite so we need to handle stopping ourselves
  89. var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMilliseconds(bufferMs)));
  90. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  91. }
  92. var tempFileTask = response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken);
  93. // Give the temp file a little time to build up
  94. await Task.Delay(bufferMs, cancellationToken).ConfigureAwait(false);
  95. await RecordFromFile(mediaSource, tempFile, targetFile, onStarted, cancellationToken)
  96. .ConfigureAwait(false);
  97. await tempFileTask.ConfigureAwait(false);
  98. }
  99. }
  100. _logger.Info("Recording completed to file {0}", targetFile);
  101. }
  102. private async Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, Action onStarted, CancellationToken cancellationToken)
  103. {
  104. _targetPath = targetFile;
  105. _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile));
  106. var process = new Process
  107. {
  108. StartInfo = new ProcessStartInfo
  109. {
  110. CreateNoWindow = true,
  111. UseShellExecute = false,
  112. // Must consume both stdout and stderr or deadlocks may occur
  113. RedirectStandardOutput = true,
  114. RedirectStandardError = true,
  115. RedirectStandardInput = true,
  116. FileName = _mediaEncoder.EncoderPath,
  117. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile),
  118. WindowStyle = ProcessWindowStyle.Hidden,
  119. ErrorDialog = false
  120. },
  121. EnableRaisingEvents = true
  122. };
  123. _process = process;
  124. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  125. _logger.Info(commandLineLogMessage);
  126. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  127. _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  128. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  129. _logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  130. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  131. await _logFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
  132. process.Exited += (sender, args) => OnFfMpegProcessExited(process);
  133. process.Start();
  134. cancellationToken.Register(Stop);
  135. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  136. process.BeginOutputReadLine();
  137. onStarted();
  138. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  139. StartStreamingLog(process.StandardError.BaseStream, _logFileStream);
  140. await _taskCompletionSource.Task.ConfigureAwait(false);
  141. }
  142. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile)
  143. {
  144. string videoArgs;
  145. if (EncodeVideo(mediaSource))
  146. {
  147. var maxBitrate = 25000000;
  148. videoArgs = string.Format(
  149. "-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",
  150. GetOutputSizeParam(),
  151. maxBitrate.ToString(CultureInfo.InvariantCulture));
  152. }
  153. else
  154. {
  155. videoArgs = "-codec:v:0 copy";
  156. }
  157. var commandLineArgs = "-fflags +genpts -async 1 -vsync -1 -re -i \"{0}\" -sn {2} -map_metadata -1 -threads 0 {3} -y \"{1}\"";
  158. if (mediaSource.ReadAtNativeFramerate)
  159. {
  160. commandLineArgs = "-re " + commandLineArgs;
  161. }
  162. commandLineArgs = string.Format(commandLineArgs, inputTempFile, targetFile, videoArgs, GetAudioArgs(mediaSource));
  163. return commandLineArgs;
  164. }
  165. private string GetAudioArgs(MediaSourceInfo mediaSource)
  166. {
  167. // do not copy aac because many players have difficulty with aac_latm
  168. var copyAudio = new[] { "mp3" };
  169. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  170. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  171. if (copyAudio.Contains(inputAudioCodec, StringComparer.OrdinalIgnoreCase))
  172. {
  173. return "-codec:a:0 copy";
  174. }
  175. if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings && !string.Equals(inputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  176. {
  177. return "-codec:a:0 copy";
  178. }
  179. var audioChannels = 2;
  180. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  181. if (audioStream != null)
  182. {
  183. audioChannels = audioStream.Channels ?? audioChannels;
  184. }
  185. return "-codec:a:0 aac -strict experimental -ab 320000";
  186. }
  187. private bool EncodeVideo(MediaSourceInfo mediaSource)
  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("Killing ffmpeg recording process for {0}", _targetPath);
  210. //process.Kill();
  211. _process.StandardInput.WriteLine("q");
  212. }
  213. catch (Exception ex)
  214. {
  215. _logger.ErrorException("Error killing transcoding job for {0}", ex, _targetPath);
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// Processes the exited.
  221. /// </summary>
  222. /// <param name="process">The process.</param>
  223. private void OnFfMpegProcessExited(Process process)
  224. {
  225. _hasExited = true;
  226. DisposeLogStream();
  227. try
  228. {
  229. var exitCode = process.ExitCode;
  230. _logger.Info("FFMpeg recording exited with code {0} for {1}", exitCode, _targetPath);
  231. if (exitCode == 0)
  232. {
  233. _taskCompletionSource.TrySetResult(true);
  234. }
  235. else
  236. {
  237. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed. Exit code {1}", _targetPath, exitCode)));
  238. }
  239. }
  240. catch
  241. {
  242. _logger.Error("FFMpeg recording exited with an error for {0}.", _targetPath);
  243. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {0} failed", _targetPath)));
  244. }
  245. }
  246. private void DisposeLogStream()
  247. {
  248. if (_logFileStream != null)
  249. {
  250. try
  251. {
  252. _logFileStream.Dispose();
  253. }
  254. catch (Exception ex)
  255. {
  256. _logger.ErrorException("Error disposing recording log stream", ex);
  257. }
  258. _logFileStream = null;
  259. }
  260. }
  261. private async void StartStreamingLog(Stream source, Stream target)
  262. {
  263. try
  264. {
  265. using (var reader = new StreamReader(source))
  266. {
  267. while (!reader.EndOfStream)
  268. {
  269. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  270. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  271. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  272. await target.FlushAsync().ConfigureAwait(false);
  273. }
  274. }
  275. }
  276. catch (ObjectDisposedException)
  277. {
  278. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  279. }
  280. catch (Exception ex)
  281. {
  282. _logger.ErrorException("Error reading ffmpeg recording log", ex);
  283. }
  284. }
  285. }
  286. }