StreamState.cs 15 KB

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