StreamState.cs 16 KB

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