EncodingJob.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. using MediaBrowser.Controller.LiveTv;
  2. using MediaBrowser.Controller.MediaEncoding;
  3. using MediaBrowser.Model.Dlna;
  4. using MediaBrowser.Model.Drawing;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.IO;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Net;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.MediaEncoding.Encoder
  16. {
  17. public class EncodingJob : IDisposable
  18. {
  19. public bool HasExited { get; internal set; }
  20. public bool IsCancelled { get; internal set; }
  21. public Stream LogFileStream { get; set; }
  22. public IProgress<double> Progress { get; set; }
  23. public TaskCompletionSource<bool> TaskCompletionSource;
  24. public EncodingJobOptions Options { get; set; }
  25. public string InputContainer { get; set; }
  26. public List<MediaStream> AllMediaStreams { get; set; }
  27. public MediaStream AudioStream { get; set; }
  28. public MediaStream VideoStream { get; set; }
  29. public MediaStream SubtitleStream { get; set; }
  30. public IIsoMount IsoMount { get; set; }
  31. public bool ReadInputAtNativeFramerate { get; set; }
  32. public bool IsVideoRequest { get; set; }
  33. public string InputAudioSync { get; set; }
  34. public string InputVideoSync { get; set; }
  35. public string Id { get; set; }
  36. public string MediaPath { get; set; }
  37. public MediaProtocol InputProtocol { get; set; }
  38. public bool IsInputVideo { get; set; }
  39. public VideoType VideoType { get; set; }
  40. public IsoType? IsoType { get; set; }
  41. public List<string> PlayableStreamFileNames { get; set; }
  42. public List<string> SupportedAudioCodecs { get; set; }
  43. public Dictionary<string, string> RemoteHttpHeaders { get; set; }
  44. public TransportStreamTimestamp InputTimestamp { get; set; }
  45. public bool DeInterlace { get; set; }
  46. public string MimeType { get; set; }
  47. public bool EstimateContentLength { get; set; }
  48. public bool EnableMpegtsM2TsMode { get; set; }
  49. public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
  50. public long? EncodingDurationTicks { get; set; }
  51. public string LiveTvStreamId { get; set; }
  52. public long? RunTimeTicks;
  53. public string ItemType { get; set; }
  54. public long? InputBitrate { get; set; }
  55. public long? InputFileSize { get; set; }
  56. public string OutputAudioSync = "1";
  57. public string OutputVideoSync = "vfr";
  58. public string GetMimeType(string outputPath)
  59. {
  60. if (!string.IsNullOrEmpty(MimeType))
  61. {
  62. return MimeType;
  63. }
  64. return MimeTypes.GetMimeType(outputPath);
  65. }
  66. private readonly ILogger _logger;
  67. private readonly ILiveTvManager _liveTvManager;
  68. public EncodingJob(ILogger logger, ILiveTvManager liveTvManager)
  69. {
  70. _logger = logger;
  71. _liveTvManager = liveTvManager;
  72. Id = Guid.NewGuid().ToString("N");
  73. RemoteHttpHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  74. _logger = logger;
  75. SupportedAudioCodecs = new List<string>();
  76. PlayableStreamFileNames = new List<string>();
  77. RemoteHttpHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  78. AllMediaStreams = new List<MediaStream>();
  79. TaskCompletionSource = new TaskCompletionSource<bool>();
  80. }
  81. public void Dispose()
  82. {
  83. DisposeLiveStream();
  84. DisposeLogStream();
  85. DisposeIsoMount();
  86. }
  87. private void DisposeLogStream()
  88. {
  89. if (LogFileStream != null)
  90. {
  91. try
  92. {
  93. LogFileStream.Dispose();
  94. }
  95. catch (Exception ex)
  96. {
  97. _logger.ErrorException("Error disposing log stream", ex);
  98. }
  99. LogFileStream = null;
  100. }
  101. }
  102. private void DisposeIsoMount()
  103. {
  104. if (IsoMount != null)
  105. {
  106. try
  107. {
  108. IsoMount.Dispose();
  109. }
  110. catch (Exception ex)
  111. {
  112. _logger.ErrorException("Error disposing iso mount", ex);
  113. }
  114. IsoMount = null;
  115. }
  116. }
  117. private async void DisposeLiveStream()
  118. {
  119. if (!string.IsNullOrEmpty(LiveTvStreamId))
  120. {
  121. try
  122. {
  123. await _liveTvManager.CloseLiveStream(LiveTvStreamId, CancellationToken.None).ConfigureAwait(false);
  124. }
  125. catch (Exception ex)
  126. {
  127. _logger.ErrorException("Error closing live tv stream", ex);
  128. }
  129. }
  130. }
  131. public int InternalSubtitleStreamOffset { get; set; }
  132. public string OutputFilePath { get; set; }
  133. public string OutputVideoCodec { get; set; }
  134. public string OutputAudioCodec { get; set; }
  135. public int? OutputAudioChannels;
  136. public int? OutputAudioSampleRate;
  137. public int? OutputAudioBitrate;
  138. public int? OutputVideoBitrate;
  139. public string ActualOutputVideoCodec
  140. {
  141. get
  142. {
  143. var codec = OutputVideoCodec;
  144. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  145. {
  146. var stream = VideoStream;
  147. if (stream != null)
  148. {
  149. return stream.Codec;
  150. }
  151. return null;
  152. }
  153. return codec;
  154. }
  155. }
  156. public string ActualOutputAudioCodec
  157. {
  158. get
  159. {
  160. var codec = OutputAudioCodec;
  161. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  162. {
  163. var stream = AudioStream;
  164. if (stream != null)
  165. {
  166. return stream.Codec;
  167. }
  168. return null;
  169. }
  170. return codec;
  171. }
  172. }
  173. public int? TotalOutputBitrate
  174. {
  175. get
  176. {
  177. return (OutputAudioBitrate ?? 0) + (OutputVideoBitrate ?? 0);
  178. }
  179. }
  180. public int? OutputWidth
  181. {
  182. get
  183. {
  184. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  185. {
  186. var size = new ImageSize
  187. {
  188. Width = VideoStream.Width.Value,
  189. Height = VideoStream.Height.Value
  190. };
  191. var newSize = DrawingUtils.Resize(size,
  192. Options.Width,
  193. Options.Height,
  194. Options.MaxWidth,
  195. Options.MaxHeight);
  196. return Convert.ToInt32(newSize.Width);
  197. }
  198. if (!IsVideoRequest)
  199. {
  200. return null;
  201. }
  202. return Options.MaxWidth ?? Options.Width;
  203. }
  204. }
  205. public int? OutputHeight
  206. {
  207. get
  208. {
  209. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  210. {
  211. var size = new ImageSize
  212. {
  213. Width = VideoStream.Width.Value,
  214. Height = VideoStream.Height.Value
  215. };
  216. var newSize = DrawingUtils.Resize(size,
  217. Options.Width,
  218. Options.Height,
  219. Options.MaxWidth,
  220. Options.MaxHeight);
  221. return Convert.ToInt32(newSize.Height);
  222. }
  223. if (!IsVideoRequest)
  224. {
  225. return null;
  226. }
  227. return Options.MaxHeight ?? Options.Height;
  228. }
  229. }
  230. /// <summary>
  231. /// Predicts the audio sample rate that will be in the output stream
  232. /// </summary>
  233. public int? TargetVideoBitDepth
  234. {
  235. get
  236. {
  237. var stream = VideoStream;
  238. return stream == null || !Options.Static ? null : stream.BitDepth;
  239. }
  240. }
  241. /// <summary>
  242. /// Gets the target reference frames.
  243. /// </summary>
  244. /// <value>The target reference frames.</value>
  245. public int? TargetRefFrames
  246. {
  247. get
  248. {
  249. var stream = VideoStream;
  250. return stream == null || !Options.Static ? null : stream.RefFrames;
  251. }
  252. }
  253. /// <summary>
  254. /// Predicts the audio sample rate that will be in the output stream
  255. /// </summary>
  256. public float? TargetFramerate
  257. {
  258. get
  259. {
  260. var stream = VideoStream;
  261. var requestedFramerate = Options.MaxFramerate ?? Options.Framerate;
  262. return requestedFramerate.HasValue && !Options.Static
  263. ? requestedFramerate
  264. : stream == null ? null : stream.AverageFrameRate ?? stream.RealFrameRate;
  265. }
  266. }
  267. /// <summary>
  268. /// Predicts the audio sample rate that will be in the output stream
  269. /// </summary>
  270. public double? TargetVideoLevel
  271. {
  272. get
  273. {
  274. var stream = VideoStream;
  275. return Options.Level.HasValue && !Options.Static
  276. ? Options.Level.Value
  277. : stream == null ? null : stream.Level;
  278. }
  279. }
  280. public TransportStreamTimestamp TargetTimestamp
  281. {
  282. get
  283. {
  284. var defaultValue = string.Equals(Options.OutputContainer, "m2ts", StringComparison.OrdinalIgnoreCase) ?
  285. TransportStreamTimestamp.Valid :
  286. TransportStreamTimestamp.None;
  287. return !Options.Static
  288. ? defaultValue
  289. : InputTimestamp;
  290. }
  291. }
  292. /// <summary>
  293. /// Predicts the audio sample rate that will be in the output stream
  294. /// </summary>
  295. public int? TargetPacketLength
  296. {
  297. get
  298. {
  299. var stream = VideoStream;
  300. return !Options.Static
  301. ? null
  302. : stream == null ? null : stream.PacketLength;
  303. }
  304. }
  305. /// <summary>
  306. /// Predicts the audio sample rate that will be in the output stream
  307. /// </summary>
  308. public string TargetVideoProfile
  309. {
  310. get
  311. {
  312. var stream = VideoStream;
  313. return !string.IsNullOrEmpty(Options.Profile) && !Options.Static
  314. ? Options.Profile
  315. : stream == null ? null : stream.Profile;
  316. }
  317. }
  318. public bool? IsTargetAnamorphic
  319. {
  320. get
  321. {
  322. if (Options.Static)
  323. {
  324. return VideoStream == null ? null : VideoStream.IsAnamorphic;
  325. }
  326. return false;
  327. }
  328. }
  329. public bool? IsTargetCabac
  330. {
  331. get
  332. {
  333. if (Options.Static)
  334. {
  335. return VideoStream == null ? null : VideoStream.IsCabac;
  336. }
  337. return true;
  338. }
  339. }
  340. public void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded)
  341. {
  342. var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
  343. // job.Framerate = framerate;
  344. if (!percentComplete.HasValue && ticks.HasValue && RunTimeTicks.HasValue)
  345. {
  346. var pct = ticks.Value/RunTimeTicks.Value;
  347. percentComplete = pct*100;
  348. }
  349. if (percentComplete.HasValue)
  350. {
  351. Progress.Report(percentComplete.Value);
  352. }
  353. // job.TranscodingPositionTicks = ticks;
  354. // job.BytesTranscoded = bytesTranscoded;
  355. var deviceId = Options.DeviceId;
  356. if (!string.IsNullOrWhiteSpace(deviceId))
  357. {
  358. var audioCodec = ActualOutputVideoCodec;
  359. var videoCodec = ActualOutputVideoCodec;
  360. // SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  361. // {
  362. // Bitrate = job.TotalOutputBitrate,
  363. // AudioCodec = audioCodec,
  364. // VideoCodec = videoCodec,
  365. // Container = job.Options.OutputContainer,
  366. // Framerate = framerate,
  367. // CompletionPercentage = percentComplete,
  368. // Width = job.OutputWidth,
  369. // Height = job.OutputHeight,
  370. // AudioChannels = job.OutputAudioChannels,
  371. // IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
  372. // IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
  373. // });
  374. }
  375. }
  376. }
  377. }