EncodedRecorder.cs 14 KB

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