EncodingJob.cs 12 KB

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