EncodingJob.cs 12 KB

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