EncodedRecorder.cs 14 KB

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