StreamState.cs 15 KB

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