StreamState.cs 15 KB

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