EncodingJob.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 : EncodingJobInfo, 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
  27. {
  28. get { return (EncodingJobOptions) BaseRequest; }
  29. set { BaseRequest = value; }
  30. }
  31. public string Id { get; set; }
  32. public string MimeType { get; set; }
  33. public bool EstimateContentLength { get; set; }
  34. public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
  35. public long? EncodingDurationTicks { get; set; }
  36. public string ItemType { get; set; }
  37. public string GetMimeType(string outputPath)
  38. {
  39. if (!string.IsNullOrEmpty(MimeType))
  40. {
  41. return MimeType;
  42. }
  43. return MimeTypes.GetMimeType(outputPath);
  44. }
  45. private readonly ILogger _logger;
  46. private readonly IMediaSourceManager _mediaSourceManager;
  47. public EncodingJob(ILogger logger, IMediaSourceManager mediaSourceManager) :
  48. base(logger, TranscodingJobType.Progressive)
  49. {
  50. _logger = logger;
  51. _mediaSourceManager = mediaSourceManager;
  52. Id = Guid.NewGuid().ToString("N");
  53. _logger = logger;
  54. TaskCompletionSource = new TaskCompletionSource<bool>();
  55. }
  56. public void Dispose()
  57. {
  58. DisposeLiveStream();
  59. DisposeLogStream();
  60. DisposeIsoMount();
  61. }
  62. private void DisposeLogStream()
  63. {
  64. if (LogFileStream != null)
  65. {
  66. try
  67. {
  68. LogFileStream.Dispose();
  69. }
  70. catch (Exception ex)
  71. {
  72. _logger.ErrorException("Error disposing log stream", ex);
  73. }
  74. LogFileStream = null;
  75. }
  76. }
  77. private async void DisposeLiveStream()
  78. {
  79. if (MediaSource.RequiresClosing && string.IsNullOrWhiteSpace(Options.LiveStreamId) && !string.IsNullOrWhiteSpace(MediaSource.LiveStreamId))
  80. {
  81. try
  82. {
  83. await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).ConfigureAwait(false);
  84. }
  85. catch (Exception ex)
  86. {
  87. _logger.ErrorException("Error closing media source", ex);
  88. }
  89. }
  90. }
  91. public string OutputFilePath { get; set; }
  92. public string ActualOutputVideoCodec
  93. {
  94. get
  95. {
  96. var codec = OutputVideoCodec;
  97. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  98. {
  99. var stream = VideoStream;
  100. if (stream != null)
  101. {
  102. return stream.Codec;
  103. }
  104. return null;
  105. }
  106. return codec;
  107. }
  108. }
  109. public string ActualOutputAudioCodec
  110. {
  111. get
  112. {
  113. var codec = OutputAudioCodec;
  114. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  115. {
  116. var stream = AudioStream;
  117. if (stream != null)
  118. {
  119. return stream.Codec;
  120. }
  121. return null;
  122. }
  123. return codec;
  124. }
  125. }
  126. public int? TotalOutputBitrate
  127. {
  128. get
  129. {
  130. return (OutputAudioBitrate ?? 0) + (OutputVideoBitrate ?? 0);
  131. }
  132. }
  133. public int? OutputWidth
  134. {
  135. get
  136. {
  137. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  138. {
  139. var size = new ImageSize
  140. {
  141. Width = VideoStream.Width.Value,
  142. Height = VideoStream.Height.Value
  143. };
  144. var newSize = DrawingUtils.Resize(size,
  145. Options.Width,
  146. Options.Height,
  147. Options.MaxWidth,
  148. Options.MaxHeight);
  149. return Convert.ToInt32(newSize.Width);
  150. }
  151. if (!IsVideoRequest)
  152. {
  153. return null;
  154. }
  155. return Options.MaxWidth ?? Options.Width;
  156. }
  157. }
  158. public int? OutputHeight
  159. {
  160. get
  161. {
  162. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  163. {
  164. var size = new ImageSize
  165. {
  166. Width = VideoStream.Width.Value,
  167. Height = VideoStream.Height.Value
  168. };
  169. var newSize = DrawingUtils.Resize(size,
  170. Options.Width,
  171. Options.Height,
  172. Options.MaxWidth,
  173. Options.MaxHeight);
  174. return Convert.ToInt32(newSize.Height);
  175. }
  176. if (!IsVideoRequest)
  177. {
  178. return null;
  179. }
  180. return Options.MaxHeight ?? Options.Height;
  181. }
  182. }
  183. /// <summary>
  184. /// Predicts the audio sample rate that will be in the output stream
  185. /// </summary>
  186. public int? TargetVideoBitDepth
  187. {
  188. get
  189. {
  190. var stream = VideoStream;
  191. return stream == null || !Options.Static ? null : stream.BitDepth;
  192. }
  193. }
  194. /// <summary>
  195. /// Gets the target reference frames.
  196. /// </summary>
  197. /// <value>The target reference frames.</value>
  198. public int? TargetRefFrames
  199. {
  200. get
  201. {
  202. var stream = VideoStream;
  203. return stream == null || !Options.Static ? null : stream.RefFrames;
  204. }
  205. }
  206. /// <summary>
  207. /// Predicts the audio sample rate that will be in the output stream
  208. /// </summary>
  209. public float? TargetFramerate
  210. {
  211. get
  212. {
  213. var stream = VideoStream;
  214. var requestedFramerate = Options.MaxFramerate ?? Options.Framerate;
  215. return requestedFramerate.HasValue && !Options.Static
  216. ? requestedFramerate
  217. : stream == null ? null : stream.AverageFrameRate ?? stream.RealFrameRate;
  218. }
  219. }
  220. public TransportStreamTimestamp TargetTimestamp
  221. {
  222. get
  223. {
  224. var defaultValue = string.Equals(OutputContainer, "m2ts", StringComparison.OrdinalIgnoreCase) ?
  225. TransportStreamTimestamp.Valid :
  226. TransportStreamTimestamp.None;
  227. return !Options.Static
  228. ? defaultValue
  229. : InputTimestamp;
  230. }
  231. }
  232. /// <summary>
  233. /// Predicts the audio sample rate that will be in the output stream
  234. /// </summary>
  235. public int? TargetPacketLength
  236. {
  237. get
  238. {
  239. var stream = VideoStream;
  240. return !Options.Static
  241. ? null
  242. : stream == null ? null : stream.PacketLength;
  243. }
  244. }
  245. /// <summary>
  246. /// Predicts the audio sample rate that will be in the output stream
  247. /// </summary>
  248. public string TargetVideoProfile
  249. {
  250. get
  251. {
  252. var stream = VideoStream;
  253. return !string.IsNullOrEmpty(Options.Profile) && !Options.Static
  254. ? Options.Profile
  255. : stream == null ? null : stream.Profile;
  256. }
  257. }
  258. public string TargetVideoCodecTag
  259. {
  260. get
  261. {
  262. var stream = VideoStream;
  263. return !Options.Static
  264. ? null
  265. : stream == null ? null : stream.CodecTag;
  266. }
  267. }
  268. public bool? IsTargetAnamorphic
  269. {
  270. get
  271. {
  272. if (Options.Static)
  273. {
  274. return VideoStream == null ? null : VideoStream.IsAnamorphic;
  275. }
  276. return false;
  277. }
  278. }
  279. public bool? IsTargetInterlaced
  280. {
  281. get
  282. {
  283. if (Options.Static)
  284. {
  285. return VideoStream == null ? (bool?)null : VideoStream.IsInterlaced;
  286. }
  287. if (DeInterlace)
  288. {
  289. return false;
  290. }
  291. return VideoStream == null ? (bool?)null : VideoStream.IsInterlaced;
  292. }
  293. }
  294. public bool? IsTargetAVC
  295. {
  296. get
  297. {
  298. if (Options.Static)
  299. {
  300. return VideoStream == null ? null : VideoStream.IsAVC;
  301. }
  302. return false;
  303. }
  304. }
  305. public int? TargetVideoStreamCount
  306. {
  307. get
  308. {
  309. if (Options.Static)
  310. {
  311. return GetMediaStreamCount(MediaStreamType.Video, int.MaxValue);
  312. }
  313. return GetMediaStreamCount(MediaStreamType.Video, 1);
  314. }
  315. }
  316. public int? TargetAudioStreamCount
  317. {
  318. get
  319. {
  320. if (Options.Static)
  321. {
  322. return GetMediaStreamCount(MediaStreamType.Audio, int.MaxValue);
  323. }
  324. return GetMediaStreamCount(MediaStreamType.Audio, 1);
  325. }
  326. }
  327. private int? GetMediaStreamCount(MediaStreamType type, int limit)
  328. {
  329. var count = MediaSource.GetStreamCount(type);
  330. if (count.HasValue)
  331. {
  332. count = Math.Min(count.Value, limit);
  333. }
  334. return count;
  335. }
  336. public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
  337. {
  338. var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
  339. // job.Framerate = framerate;
  340. if (!percentComplete.HasValue && ticks.HasValue && RunTimeTicks.HasValue)
  341. {
  342. var pct = ticks.Value / RunTimeTicks.Value;
  343. percentComplete = pct * 100;
  344. }
  345. if (percentComplete.HasValue)
  346. {
  347. Progress.Report(percentComplete.Value);
  348. }
  349. // job.TranscodingPositionTicks = ticks;
  350. // job.BytesTranscoded = bytesTranscoded;
  351. var deviceId = Options.DeviceId;
  352. if (!string.IsNullOrWhiteSpace(deviceId))
  353. {
  354. var audioCodec = ActualOutputVideoCodec;
  355. var videoCodec = ActualOutputVideoCodec;
  356. // SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  357. // {
  358. // Bitrate = job.TotalOutputBitrate,
  359. // AudioCodec = audioCodec,
  360. // VideoCodec = videoCodec,
  361. // Container = job.Options.OutputContainer,
  362. // Framerate = framerate,
  363. // CompletionPercentage = percentComplete,
  364. // Width = job.OutputWidth,
  365. // Height = job.OutputHeight,
  366. // AudioChannels = job.OutputAudioChannels,
  367. // IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
  368. // IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
  369. // });
  370. }
  371. }
  372. }
  373. }