EncodedRecorder.cs 16 KB

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