EncodingJob.cs 15 KB

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