StreamState.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. using MediaBrowser.Controller.Library;
  2. using MediaBrowser.Model.Dlna;
  3. using MediaBrowser.Model.Drawing;
  4. using MediaBrowser.Model.Dto;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.IO;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Net;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using MediaBrowser.Controller.MediaEncoding;
  17. namespace MediaBrowser.Api.Playback
  18. {
  19. public class StreamState : EncodingJobInfo, IDisposable
  20. {
  21. private readonly ILogger _logger;
  22. private readonly IMediaSourceManager _mediaSourceManager;
  23. public string RequestedUrl { get; set; }
  24. public StreamRequest Request
  25. {
  26. get { return (StreamRequest)BaseRequest; }
  27. set
  28. {
  29. BaseRequest = value;
  30. IsVideoRequest = VideoRequest != null;
  31. }
  32. }
  33. public TranscodingThrottler TranscodingThrottler { get; set; }
  34. public VideoStreamRequest VideoRequest
  35. {
  36. get { return Request as VideoStreamRequest; }
  37. }
  38. /// <summary>
  39. /// Gets or sets the log file stream.
  40. /// </summary>
  41. /// <value>The log file stream.</value>
  42. public Stream LogFileStream { get; set; }
  43. public IDirectStreamProvider DirectStreamProvider { get; set; }
  44. public string WaitForPath { get; set; }
  45. public bool IsOutputVideo
  46. {
  47. get { return Request is VideoStreamRequest; }
  48. }
  49. public int SegmentLength
  50. {
  51. get
  52. {
  53. if (Request.SegmentLength.HasValue)
  54. {
  55. return Request.SegmentLength.Value;
  56. }
  57. if (string.Equals(OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  58. {
  59. var userAgent = UserAgent ?? string.Empty;
  60. if (userAgent.IndexOf("AppleTV", StringComparison.OrdinalIgnoreCase) != -1 ||
  61. userAgent.IndexOf("cfnetwork", StringComparison.OrdinalIgnoreCase) != -1 ||
  62. userAgent.IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
  63. userAgent.IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
  64. userAgent.IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
  65. {
  66. if (IsSegmentedLiveStream)
  67. {
  68. return 6;
  69. }
  70. return 10;
  71. }
  72. if (IsSegmentedLiveStream)
  73. {
  74. return 3;
  75. }
  76. return 6;
  77. }
  78. return 3;
  79. }
  80. }
  81. public int MinSegments
  82. {
  83. get
  84. {
  85. if (Request.MinSegments.HasValue)
  86. {
  87. return Request.MinSegments.Value;
  88. }
  89. return SegmentLength >= 10 ? 2 : 3;
  90. }
  91. }
  92. public int HlsListSize
  93. {
  94. get
  95. {
  96. return 0;
  97. }
  98. }
  99. public string UserAgent { get; set; }
  100. public StreamState(IMediaSourceManager mediaSourceManager, ILogger logger, TranscodingJobType transcodingType)
  101. : base(logger, transcodingType)
  102. {
  103. _mediaSourceManager = mediaSourceManager;
  104. _logger = logger;
  105. }
  106. public string MimeType { get; set; }
  107. public bool EstimateContentLength { get; set; }
  108. public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
  109. public long? EncodingDurationTicks { get; set; }
  110. public string GetMimeType(string outputPath)
  111. {
  112. if (!string.IsNullOrEmpty(MimeType))
  113. {
  114. return MimeType;
  115. }
  116. return MimeTypes.GetMimeType(outputPath);
  117. }
  118. public bool EnableDlnaHeaders { get; set; }
  119. public void Dispose()
  120. {
  121. DisposeTranscodingThrottler();
  122. DisposeLiveStream();
  123. DisposeLogStream();
  124. DisposeIsoMount();
  125. TranscodingJob = null;
  126. }
  127. private void DisposeLogStream()
  128. {
  129. if (LogFileStream != null)
  130. {
  131. try
  132. {
  133. LogFileStream.Dispose();
  134. }
  135. catch (Exception ex)
  136. {
  137. _logger.ErrorException("Error disposing log stream", ex);
  138. }
  139. LogFileStream = null;
  140. }
  141. }
  142. private void DisposeTranscodingThrottler()
  143. {
  144. if (TranscodingThrottler != null)
  145. {
  146. try
  147. {
  148. TranscodingThrottler.Dispose();
  149. }
  150. catch (Exception ex)
  151. {
  152. _logger.ErrorException("Error disposing TranscodingThrottler", ex);
  153. }
  154. TranscodingThrottler = null;
  155. }
  156. }
  157. private async void DisposeLiveStream()
  158. {
  159. if (MediaSource.RequiresClosing && string.IsNullOrWhiteSpace(Request.LiveStreamId) && !string.IsNullOrWhiteSpace(MediaSource.LiveStreamId))
  160. {
  161. try
  162. {
  163. await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).ConfigureAwait(false);
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.ErrorException("Error closing media source", ex);
  168. }
  169. }
  170. }
  171. public string OutputFilePath { get; set; }
  172. public string ActualOutputVideoCodec
  173. {
  174. get
  175. {
  176. var codec = OutputVideoCodec;
  177. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  178. {
  179. var stream = VideoStream;
  180. if (stream != null)
  181. {
  182. return stream.Codec;
  183. }
  184. return null;
  185. }
  186. return codec;
  187. }
  188. }
  189. public string ActualOutputAudioCodec
  190. {
  191. get
  192. {
  193. var codec = OutputAudioCodec;
  194. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  195. {
  196. var stream = AudioStream;
  197. if (stream != null)
  198. {
  199. return stream.Codec;
  200. }
  201. return null;
  202. }
  203. return codec;
  204. }
  205. }
  206. public DeviceProfile DeviceProfile { get; set; }
  207. public int? TotalOutputBitrate
  208. {
  209. get
  210. {
  211. return (OutputAudioBitrate ?? 0) + (OutputVideoBitrate ?? 0);
  212. }
  213. }
  214. public int? OutputWidth
  215. {
  216. get
  217. {
  218. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  219. {
  220. var size = new ImageSize
  221. {
  222. Width = VideoStream.Width.Value,
  223. Height = VideoStream.Height.Value
  224. };
  225. var newSize = DrawingUtils.Resize(size,
  226. VideoRequest.Width,
  227. VideoRequest.Height,
  228. VideoRequest.MaxWidth,
  229. VideoRequest.MaxHeight);
  230. return Convert.ToInt32(newSize.Width);
  231. }
  232. if (VideoRequest == null)
  233. {
  234. return null;
  235. }
  236. return VideoRequest.MaxWidth ?? VideoRequest.Width;
  237. }
  238. }
  239. public int? OutputHeight
  240. {
  241. get
  242. {
  243. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  244. {
  245. var size = new ImageSize
  246. {
  247. Width = VideoStream.Width.Value,
  248. Height = VideoStream.Height.Value
  249. };
  250. var newSize = DrawingUtils.Resize(size,
  251. VideoRequest.Width,
  252. VideoRequest.Height,
  253. VideoRequest.MaxWidth,
  254. VideoRequest.MaxHeight);
  255. return Convert.ToInt32(newSize.Height);
  256. }
  257. if (VideoRequest == null)
  258. {
  259. return null;
  260. }
  261. return VideoRequest.MaxHeight ?? VideoRequest.Height;
  262. }
  263. }
  264. /// <summary>
  265. /// Predicts the audio sample rate that will be in the output stream
  266. /// </summary>
  267. public int? TargetVideoBitDepth
  268. {
  269. get
  270. {
  271. var stream = VideoStream;
  272. return stream == null || !Request.Static ? null : stream.BitDepth;
  273. }
  274. }
  275. /// <summary>
  276. /// Gets the target reference frames.
  277. /// </summary>
  278. /// <value>The target reference frames.</value>
  279. public int? TargetRefFrames
  280. {
  281. get
  282. {
  283. var stream = VideoStream;
  284. return stream == null || !Request.Static ? null : stream.RefFrames;
  285. }
  286. }
  287. public int? TargetVideoStreamCount
  288. {
  289. get
  290. {
  291. if (Request.Static)
  292. {
  293. return GetMediaStreamCount(MediaStreamType.Video, int.MaxValue);
  294. }
  295. return GetMediaStreamCount(MediaStreamType.Video, 1);
  296. }
  297. }
  298. public int? TargetAudioStreamCount
  299. {
  300. get
  301. {
  302. if (Request.Static)
  303. {
  304. return GetMediaStreamCount(MediaStreamType.Audio, int.MaxValue);
  305. }
  306. return GetMediaStreamCount(MediaStreamType.Audio, 1);
  307. }
  308. }
  309. public bool? IsTargetAnamorphic
  310. {
  311. get
  312. {
  313. if (Request.Static)
  314. {
  315. return VideoStream == null ? null : VideoStream.IsAnamorphic;
  316. }
  317. return false;
  318. }
  319. }
  320. public bool? IsTargetInterlaced
  321. {
  322. get
  323. {
  324. if (Request.Static)
  325. {
  326. return VideoStream == null ? (bool?)null : VideoStream.IsInterlaced;
  327. }
  328. if (DeInterlace)
  329. {
  330. return false;
  331. }
  332. return VideoStream == null ? (bool?)null : VideoStream.IsInterlaced;
  333. }
  334. }
  335. private int? GetMediaStreamCount(MediaStreamType type, int limit)
  336. {
  337. var count = MediaSource.GetStreamCount(type);
  338. if (count.HasValue)
  339. {
  340. count = Math.Min(count.Value, limit);
  341. }
  342. return count;
  343. }
  344. /// <summary>
  345. /// Predicts the audio sample rate that will be in the output stream
  346. /// </summary>
  347. public float? TargetFramerate
  348. {
  349. get
  350. {
  351. var stream = VideoStream;
  352. var requestedFramerate = VideoRequest.MaxFramerate ?? VideoRequest.Framerate;
  353. return requestedFramerate.HasValue && !Request.Static
  354. ? requestedFramerate
  355. : stream == null ? null : stream.AverageFrameRate ?? stream.RealFrameRate;
  356. }
  357. }
  358. public TransportStreamTimestamp TargetTimestamp
  359. {
  360. get
  361. {
  362. var defaultValue = string.Equals(OutputContainer, "m2ts", StringComparison.OrdinalIgnoreCase) ?
  363. TransportStreamTimestamp.Valid :
  364. TransportStreamTimestamp.None;
  365. return !Request.Static
  366. ? defaultValue
  367. : InputTimestamp;
  368. }
  369. }
  370. /// <summary>
  371. /// Predicts the audio sample rate that will be in the output stream
  372. /// </summary>
  373. public int? TargetPacketLength
  374. {
  375. get
  376. {
  377. var stream = VideoStream;
  378. return !Request.Static
  379. ? null
  380. : stream == null ? null : stream.PacketLength;
  381. }
  382. }
  383. /// <summary>
  384. /// Predicts the audio sample rate that will be in the output stream
  385. /// </summary>
  386. public string TargetVideoProfile
  387. {
  388. get
  389. {
  390. var stream = VideoStream;
  391. return !string.IsNullOrEmpty(VideoRequest.Profile) && !Request.Static
  392. ? VideoRequest.Profile
  393. : stream == null ? null : stream.Profile;
  394. }
  395. }
  396. public string TargetVideoCodecTag
  397. {
  398. get
  399. {
  400. var stream = VideoStream;
  401. return !Request.Static
  402. ? null
  403. : stream == null ? null : stream.CodecTag;
  404. }
  405. }
  406. public bool? IsTargetAVC
  407. {
  408. get
  409. {
  410. if (Request.Static)
  411. {
  412. return VideoStream == null ? null : VideoStream.IsAVC;
  413. }
  414. return true;
  415. }
  416. }
  417. public TranscodingJob TranscodingJob;
  418. public override void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
  419. {
  420. ApiEntryPoint.Instance.ReportTranscodingProgress(TranscodingJob, this, transcodingPosition, framerate, percentComplete, bytesTranscoded, bitRate);
  421. }
  422. }
  423. }