StreamState.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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 List<string> AllAudioCodecs
  205. {
  206. get
  207. {
  208. return MediaSource.MediaStreams.Where(i => i.Type == MediaStreamType.Audio)
  209. .Select(i => i.Codec)
  210. .Where(i => !string.IsNullOrWhiteSpace(i))
  211. .ToList();
  212. }
  213. }
  214. public string ActualOutputVideoCodec
  215. {
  216. get
  217. {
  218. var codec = OutputVideoCodec;
  219. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  220. {
  221. var stream = VideoStream;
  222. if (stream != null)
  223. {
  224. return stream.Codec;
  225. }
  226. return null;
  227. }
  228. return codec;
  229. }
  230. }
  231. public string ActualOutputAudioCodec
  232. {
  233. get
  234. {
  235. var codec = OutputAudioCodec;
  236. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  237. {
  238. var stream = AudioStream;
  239. if (stream != null)
  240. {
  241. return stream.Codec;
  242. }
  243. return null;
  244. }
  245. return codec;
  246. }
  247. }
  248. public string OutputContainer { get; set; }
  249. public DeviceProfile DeviceProfile { get; set; }
  250. public int? TotalOutputBitrate
  251. {
  252. get
  253. {
  254. return (OutputAudioBitrate ?? 0) + (OutputVideoBitrate ?? 0);
  255. }
  256. }
  257. public int? OutputWidth
  258. {
  259. get
  260. {
  261. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  262. {
  263. var size = new ImageSize
  264. {
  265. Width = VideoStream.Width.Value,
  266. Height = VideoStream.Height.Value
  267. };
  268. var newSize = DrawingUtils.Resize(size,
  269. VideoRequest.Width,
  270. VideoRequest.Height,
  271. VideoRequest.MaxWidth,
  272. VideoRequest.MaxHeight);
  273. return Convert.ToInt32(newSize.Width);
  274. }
  275. if (VideoRequest == null)
  276. {
  277. return null;
  278. }
  279. return VideoRequest.MaxWidth ?? VideoRequest.Width;
  280. }
  281. }
  282. public int? OutputHeight
  283. {
  284. get
  285. {
  286. if (VideoStream != null && VideoStream.Width.HasValue && VideoStream.Height.HasValue)
  287. {
  288. var size = new ImageSize
  289. {
  290. Width = VideoStream.Width.Value,
  291. Height = VideoStream.Height.Value
  292. };
  293. var newSize = DrawingUtils.Resize(size,
  294. VideoRequest.Width,
  295. VideoRequest.Height,
  296. VideoRequest.MaxWidth,
  297. VideoRequest.MaxHeight);
  298. return Convert.ToInt32(newSize.Height);
  299. }
  300. if (VideoRequest == null)
  301. {
  302. return null;
  303. }
  304. return VideoRequest.MaxHeight ?? VideoRequest.Height;
  305. }
  306. }
  307. /// <summary>
  308. /// Predicts the audio sample rate that will be in the output stream
  309. /// </summary>
  310. public int? TargetVideoBitDepth
  311. {
  312. get
  313. {
  314. var stream = VideoStream;
  315. return stream == null || !Request.Static ? null : stream.BitDepth;
  316. }
  317. }
  318. /// <summary>
  319. /// Gets the target reference frames.
  320. /// </summary>
  321. /// <value>The target reference frames.</value>
  322. public int? TargetRefFrames
  323. {
  324. get
  325. {
  326. var stream = VideoStream;
  327. return stream == null || !Request.Static ? null : stream.RefFrames;
  328. }
  329. }
  330. public int? TargetVideoStreamCount
  331. {
  332. get
  333. {
  334. if (Request.Static)
  335. {
  336. return GetMediaStreamCount(MediaStreamType.Video, int.MaxValue);
  337. }
  338. return GetMediaStreamCount(MediaStreamType.Video, 1);
  339. }
  340. }
  341. public int? TargetAudioStreamCount
  342. {
  343. get
  344. {
  345. if (Request.Static)
  346. {
  347. return GetMediaStreamCount(MediaStreamType.Audio, int.MaxValue);
  348. }
  349. return GetMediaStreamCount(MediaStreamType.Audio, 1);
  350. }
  351. }
  352. private int? GetMediaStreamCount(MediaStreamType type, int limit)
  353. {
  354. var count = MediaSource.GetStreamCount(type);
  355. if (count.HasValue)
  356. {
  357. count = Math.Min(count.Value, limit);
  358. }
  359. return count;
  360. }
  361. /// <summary>
  362. /// Predicts the audio sample rate that will be in the output stream
  363. /// </summary>
  364. public float? TargetFramerate
  365. {
  366. get
  367. {
  368. var stream = VideoStream;
  369. var requestedFramerate = VideoRequest.MaxFramerate ?? VideoRequest.Framerate;
  370. return requestedFramerate.HasValue && !Request.Static
  371. ? requestedFramerate
  372. : stream == null ? null : stream.AverageFrameRate ?? stream.RealFrameRate;
  373. }
  374. }
  375. /// <summary>
  376. /// Predicts the audio sample rate that will be in the output stream
  377. /// </summary>
  378. public double? TargetVideoLevel
  379. {
  380. get
  381. {
  382. var stream = VideoStream;
  383. return !string.IsNullOrEmpty(VideoRequest.Level) && !Request.Static
  384. ? double.Parse(VideoRequest.Level, CultureInfo.InvariantCulture)
  385. : stream == null ? null : stream.Level;
  386. }
  387. }
  388. public TransportStreamTimestamp TargetTimestamp
  389. {
  390. get
  391. {
  392. var defaultValue = string.Equals(OutputContainer, "m2ts", StringComparison.OrdinalIgnoreCase) ?
  393. TransportStreamTimestamp.Valid :
  394. TransportStreamTimestamp.None;
  395. return !Request.Static
  396. ? defaultValue
  397. : InputTimestamp;
  398. }
  399. }
  400. /// <summary>
  401. /// Predicts the audio sample rate that will be in the output stream
  402. /// </summary>
  403. public int? TargetPacketLength
  404. {
  405. get
  406. {
  407. var stream = VideoStream;
  408. return !Request.Static
  409. ? null
  410. : stream == null ? null : stream.PacketLength;
  411. }
  412. }
  413. /// <summary>
  414. /// Predicts the audio sample rate that will be in the output stream
  415. /// </summary>
  416. public string TargetVideoProfile
  417. {
  418. get
  419. {
  420. var stream = VideoStream;
  421. return !string.IsNullOrEmpty(VideoRequest.Profile) && !Request.Static
  422. ? VideoRequest.Profile
  423. : stream == null ? null : stream.Profile;
  424. }
  425. }
  426. public string TargetVideoCodecTag
  427. {
  428. get
  429. {
  430. var stream = VideoStream;
  431. return !Request.Static
  432. ? null
  433. : stream == null ? null : stream.CodecTag;
  434. }
  435. }
  436. public bool? IsTargetAnamorphic
  437. {
  438. get
  439. {
  440. if (Request.Static)
  441. {
  442. return VideoStream == null ? null : VideoStream.IsAnamorphic;
  443. }
  444. return false;
  445. }
  446. }
  447. public bool? IsTargetAVC
  448. {
  449. get
  450. {
  451. if (Request.Static)
  452. {
  453. return VideoStream == null ? null : VideoStream.IsAVC;
  454. }
  455. return true;
  456. }
  457. }
  458. }
  459. }