EncodedRecorder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Controller;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Controller.MediaEncoding;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Diagnostics;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Serialization;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  22. {
  23. public class EncodedRecorder : IRecorder
  24. {
  25. private readonly ILogger _logger;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly IMediaEncoder _mediaEncoder;
  28. private readonly IServerApplicationPaths _appPaths;
  29. private bool _hasExited;
  30. private Stream _logFileStream;
  31. private string _targetPath;
  32. private IProcess _process;
  33. private readonly IProcessFactory _processFactory;
  34. private readonly IJsonSerializer _json;
  35. private readonly TaskCompletionSource<bool> _taskCompletionSource = new TaskCompletionSource<bool>();
  36. private readonly IServerConfigurationManager _config;
  37. public EncodedRecorder(
  38. ILogger logger,
  39. IFileSystem fileSystem,
  40. IMediaEncoder mediaEncoder,
  41. IServerApplicationPaths appPaths,
  42. IJsonSerializer json,
  43. IProcessFactory processFactory,
  44. IServerConfigurationManager config)
  45. {
  46. _logger = logger;
  47. _fileSystem = fileSystem;
  48. _mediaEncoder = mediaEncoder;
  49. _appPaths = appPaths;
  50. _json = json;
  51. _processFactory = processFactory;
  52. _config = config;
  53. }
  54. private static bool CopySubtitles => false;
  55. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  56. {
  57. return Path.ChangeExtension(targetFile, ".ts");
  58. }
  59. public async Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  60. {
  61. // The media source is infinite so we need to handle stopping ourselves
  62. var durationToken = new CancellationTokenSource(duration);
  63. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  64. await RecordFromFile(mediaSource, mediaSource.Path, targetFile, duration, onStarted, cancellationToken).ConfigureAwait(false);
  65. _logger.LogInformation("Recording completed to file {0}", targetFile);
  66. }
  67. private EncodingOptions GetEncodingOptions()
  68. {
  69. return _config.GetConfiguration<EncodingOptions>("encoding");
  70. }
  71. private Task RecordFromFile(MediaSourceInfo mediaSource, string inputFile, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  72. {
  73. _targetPath = targetFile;
  74. Directory.CreateDirectory(Path.GetDirectoryName(targetFile));
  75. var process = _processFactory.Create(new ProcessOptions
  76. {
  77. CreateNoWindow = true,
  78. UseShellExecute = false,
  79. // Must consume both stdout and stderr or deadlocks may occur
  80. //RedirectStandardOutput = true,
  81. RedirectStandardError = true,
  82. RedirectStandardInput = true,
  83. FileName = _mediaEncoder.EncoderPath,
  84. Arguments = GetCommandLineArgs(mediaSource, inputFile, targetFile, duration),
  85. IsHidden = true,
  86. ErrorDialog = false,
  87. EnableRaisingEvents = true
  88. });
  89. _process = process;
  90. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  91. _logger.LogInformation(commandLineLogMessage);
  92. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt");
  93. Directory.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, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
  96. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  97. _logFileStream.Write(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length);
  98. process.Exited += (sender, args) => OnFfMpegProcessExited(process, inputFile);
  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. _logger.LogInformation("ffmpeg recording process started for {0}", _targetPath);
  107. return _taskCompletionSource.Task;
  108. }
  109. private string GetCommandLineArgs(MediaSourceInfo mediaSource, string inputTempFile, string targetFile, TimeSpan duration)
  110. {
  111. string videoArgs;
  112. if (EncodeVideo(mediaSource))
  113. {
  114. var maxBitrate = 25000000;
  115. videoArgs = string.Format(
  116. "-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",
  117. GetOutputSizeParam(),
  118. maxBitrate.ToString(CultureInfo.InvariantCulture));
  119. }
  120. else
  121. {
  122. videoArgs = "-codec:v:0 copy";
  123. }
  124. videoArgs += " -fflags +genpts";
  125. var durationParam = " -t " + _mediaEncoder.GetTimeParameter(duration.Ticks);
  126. durationParam = string.Empty;
  127. var flags = new List<string>();
  128. if (mediaSource.IgnoreDts)
  129. {
  130. flags.Add("+igndts");
  131. }
  132. if (mediaSource.IgnoreIndex)
  133. {
  134. flags.Add("+ignidx");
  135. }
  136. if (mediaSource.GenPtsInput)
  137. {
  138. flags.Add("+genpts");
  139. }
  140. var inputModifier = "-async 1 -vsync -1";
  141. if (flags.Count > 0)
  142. {
  143. inputModifier += " -fflags " + string.Join("", flags.ToArray());
  144. }
  145. var videoStream = mediaSource.VideoStream;
  146. if (mediaSource.ReadAtNativeFramerate)
  147. {
  148. inputModifier += " -re";
  149. }
  150. if (mediaSource.RequiresLooping)
  151. {
  152. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  153. }
  154. var analyzeDurationSeconds = 5;
  155. var analyzeDuration = " -analyzeduration " +
  156. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  157. inputModifier += analyzeDuration;
  158. var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
  159. //var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
  160. // " -f mp4 -movflags frag_keyframe+empty_moov" :
  161. // string.Empty;
  162. var outputParam = string.Empty;
  163. var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"",
  164. inputTempFile,
  165. targetFile,
  166. videoArgs,
  167. GetAudioArgs(mediaSource),
  168. subtitleArgs,
  169. durationParam,
  170. outputParam);
  171. return inputModifier + " " + commandLineArgs;
  172. }
  173. private static string GetAudioArgs(MediaSourceInfo mediaSource)
  174. {
  175. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  176. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  177. return "-codec:a:0 copy";
  178. //var audioChannels = 2;
  179. //var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  180. //if (audioStream != null)
  181. //{
  182. // audioChannels = audioStream.Channels ?? audioChannels;
  183. //}
  184. //return "-codec:a:0 aac -strict experimental -ab 320000";
  185. }
  186. private static bool EncodeVideo(MediaSourceInfo mediaSource)
  187. {
  188. return false;
  189. }
  190. protected string GetOutputSizeParam()
  191. {
  192. var filters = new List<string>();
  193. filters.Add("yadif=0:-1:0");
  194. var output = string.Empty;
  195. if (filters.Count > 0)
  196. {
  197. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  198. }
  199. return output;
  200. }
  201. private void Stop()
  202. {
  203. if (!_hasExited)
  204. {
  205. try
  206. {
  207. _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
  208. //process.Kill();
  209. _process.StandardInput.WriteLine("q");
  210. }
  211. catch (Exception ex)
  212. {
  213. _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
  214. }
  215. if (_hasExited)
  216. {
  217. return;
  218. }
  219. try
  220. {
  221. _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
  222. if (_process.WaitForExit(10000))
  223. {
  224. return;
  225. }
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
  230. }
  231. if (_hasExited)
  232. {
  233. return;
  234. }
  235. try
  236. {
  237. _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
  238. _process.Kill();
  239. }
  240. catch (Exception ex)
  241. {
  242. _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
  243. }
  244. }
  245. }
  246. /// <summary>
  247. /// Processes the exited.
  248. /// </summary>
  249. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  250. {
  251. _hasExited = true;
  252. DisposeLogStream();
  253. try
  254. {
  255. var exitCode = process.ExitCode;
  256. _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath);
  257. if (exitCode == 0)
  258. {
  259. _taskCompletionSource.TrySetResult(true);
  260. }
  261. else
  262. {
  263. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode)));
  264. }
  265. }
  266. catch
  267. {
  268. _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath);
  269. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath)));
  270. }
  271. }
  272. private void DisposeLogStream()
  273. {
  274. if (_logFileStream != null)
  275. {
  276. try
  277. {
  278. _logFileStream.Dispose();
  279. }
  280. catch (Exception ex)
  281. {
  282. _logger.LogError(ex, "Error disposing recording log stream");
  283. }
  284. _logFileStream = null;
  285. }
  286. }
  287. private async void StartStreamingLog(Stream source, Stream target)
  288. {
  289. try
  290. {
  291. using (var reader = new StreamReader(source))
  292. {
  293. while (!reader.EndOfStream)
  294. {
  295. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  296. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  297. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  298. await target.FlushAsync().ConfigureAwait(false);
  299. }
  300. }
  301. }
  302. catch (ObjectDisposedException)
  303. {
  304. // TODO Investigate and properly fix.
  305. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  306. }
  307. catch (Exception ex)
  308. {
  309. _logger.LogError(ex, "Error reading ffmpeg recording log");
  310. }
  311. }
  312. }
  313. }