EncodingJob.cs 12 KB

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