EncodedRecorder.cs 14 KB

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