StreamState.cs 15 KB

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