EncodedRecorder.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. string videoDecoder = null;
  146. if (!string.IsNullOrEmpty(videoDecoder))
  147. {
  148. inputModifier += " " + videoDecoder;
  149. }
  150. if (mediaSource.ReadAtNativeFramerate)
  151. {
  152. inputModifier += " -re";
  153. }
  154. if (mediaSource.RequiresLooping)
  155. {
  156. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  157. }
  158. var analyzeDurationSeconds = 5;
  159. var analyzeDuration = " -analyzeduration " +
  160. (analyzeDurationSeconds * 1000000).ToString(CultureInfo.InvariantCulture);
  161. inputModifier += analyzeDuration;
  162. var subtitleArgs = CopySubtitles ? " -codec:s copy" : " -sn";
  163. //var outputParam = string.Equals(Path.GetExtension(targetFile), ".mp4", StringComparison.OrdinalIgnoreCase) ?
  164. // " -f mp4 -movflags frag_keyframe+empty_moov" :
  165. // string.Empty;
  166. var outputParam = string.Empty;
  167. var commandLineArgs = string.Format("-i \"{0}\"{5} {2} -map_metadata -1 -threads 0 {3}{4}{6} -y \"{1}\"",
  168. inputTempFile,
  169. targetFile,
  170. videoArgs,
  171. GetAudioArgs(mediaSource),
  172. subtitleArgs,
  173. durationParam,
  174. outputParam);
  175. return inputModifier + " " + commandLineArgs;
  176. }
  177. private static string GetAudioArgs(MediaSourceInfo mediaSource)
  178. {
  179. var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>();
  180. var inputAudioCodec = mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Select(i => i.Codec).FirstOrDefault() ?? string.Empty;
  181. return "-codec:a:0 copy";
  182. //var audioChannels = 2;
  183. //var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  184. //if (audioStream != null)
  185. //{
  186. // audioChannels = audioStream.Channels ?? audioChannels;
  187. //}
  188. //return "-codec:a:0 aac -strict experimental -ab 320000";
  189. }
  190. private static bool EncodeVideo(MediaSourceInfo mediaSource)
  191. {
  192. return false;
  193. }
  194. protected string GetOutputSizeParam()
  195. {
  196. var filters = new List<string>();
  197. filters.Add("yadif=0:-1:0");
  198. var output = string.Empty;
  199. if (filters.Count > 0)
  200. {
  201. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  202. }
  203. return output;
  204. }
  205. private void Stop()
  206. {
  207. if (!_hasExited)
  208. {
  209. try
  210. {
  211. _logger.LogInformation("Stopping ffmpeg recording process for {path}", _targetPath);
  212. //process.Kill();
  213. _process.StandardInput.WriteLine("q");
  214. }
  215. catch (Exception ex)
  216. {
  217. _logger.LogError(ex, "Error stopping recording transcoding job for {path}", _targetPath);
  218. }
  219. if (_hasExited)
  220. {
  221. return;
  222. }
  223. try
  224. {
  225. _logger.LogInformation("Calling recording process.WaitForExit for {path}", _targetPath);
  226. if (_process.WaitForExit(10000))
  227. {
  228. return;
  229. }
  230. }
  231. catch (Exception ex)
  232. {
  233. _logger.LogError(ex, "Error waiting for recording process to exit for {path}", _targetPath);
  234. }
  235. if (_hasExited)
  236. {
  237. return;
  238. }
  239. try
  240. {
  241. _logger.LogInformation("Killing ffmpeg recording process for {path}", _targetPath);
  242. _process.Kill();
  243. }
  244. catch (Exception ex)
  245. {
  246. _logger.LogError(ex, "Error killing recording transcoding job for {path}", _targetPath);
  247. }
  248. }
  249. }
  250. /// <summary>
  251. /// Processes the exited.
  252. /// </summary>
  253. private void OnFfMpegProcessExited(IProcess process, string inputFile)
  254. {
  255. _hasExited = true;
  256. DisposeLogStream();
  257. try
  258. {
  259. var exitCode = process.ExitCode;
  260. _logger.LogInformation("FFMpeg recording exited with code {ExitCode} for {path}", exitCode, _targetPath);
  261. if (exitCode == 0)
  262. {
  263. _taskCompletionSource.TrySetResult(true);
  264. }
  265. else
  266. {
  267. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed. Exit code {ExitCode}", _targetPath, exitCode)));
  268. }
  269. }
  270. catch
  271. {
  272. _logger.LogError("FFMpeg recording exited with an error for {path}.", _targetPath);
  273. _taskCompletionSource.TrySetException(new Exception(string.Format("Recording for {path} failed", _targetPath)));
  274. }
  275. }
  276. private void DisposeLogStream()
  277. {
  278. if (_logFileStream != null)
  279. {
  280. try
  281. {
  282. _logFileStream.Dispose();
  283. }
  284. catch (Exception ex)
  285. {
  286. _logger.LogError(ex, "Error disposing recording log stream");
  287. }
  288. _logFileStream = null;
  289. }
  290. }
  291. private async void StartStreamingLog(Stream source, Stream target)
  292. {
  293. try
  294. {
  295. using (var reader = new StreamReader(source))
  296. {
  297. while (!reader.EndOfStream)
  298. {
  299. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  300. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  301. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  302. await target.FlushAsync().ConfigureAwait(false);
  303. }
  304. }
  305. }
  306. catch (ObjectDisposedException)
  307. {
  308. // TODO Investigate and properly fix.
  309. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  310. }
  311. catch (Exception ex)
  312. {
  313. _logger.LogError(ex, "Error reading ffmpeg recording log");
  314. }
  315. }
  316. }
  317. }