StreamState.cs 16 KB

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