EncodingJob.cs 15 KB

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