LiveTvMediaSourceProvider.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.LiveTv;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Model.Dto;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using MediaBrowser.Model.Dlna;
  17. namespace Emby.Server.Implementations.LiveTv
  18. {
  19. public class LiveTvMediaSourceProvider : IMediaSourceProvider
  20. {
  21. private readonly ILiveTvManager _liveTvManager;
  22. private readonly IJsonSerializer _jsonSerializer;
  23. private readonly ILogger _logger;
  24. private readonly IMediaSourceManager _mediaSourceManager;
  25. private readonly IMediaEncoder _mediaEncoder;
  26. private readonly IServerApplicationHost _appHost;
  27. public LiveTvMediaSourceProvider(ILiveTvManager liveTvManager, IJsonSerializer jsonSerializer, ILogManager logManager, IMediaSourceManager mediaSourceManager, IMediaEncoder mediaEncoder, IServerApplicationHost appHost)
  28. {
  29. _liveTvManager = liveTvManager;
  30. _jsonSerializer = jsonSerializer;
  31. _mediaSourceManager = mediaSourceManager;
  32. _mediaEncoder = mediaEncoder;
  33. _appHost = appHost;
  34. _logger = logManager.GetLogger(GetType().Name);
  35. }
  36. public Task<IEnumerable<MediaSourceInfo>> GetMediaSources(IHasMediaSources item, CancellationToken cancellationToken)
  37. {
  38. var baseItem = (BaseItem)item;
  39. if (baseItem.SourceType == SourceType.LiveTV)
  40. {
  41. if (string.IsNullOrWhiteSpace(baseItem.Path))
  42. {
  43. return GetMediaSourcesInternal(item, cancellationToken);
  44. }
  45. }
  46. return Task.FromResult<IEnumerable<MediaSourceInfo>>(new List<MediaSourceInfo>());
  47. }
  48. // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
  49. private const char StreamIdDelimeter = '_';
  50. private const string StreamIdDelimeterString = "_";
  51. private async Task<IEnumerable<MediaSourceInfo>> GetMediaSourcesInternal(IHasMediaSources item, CancellationToken cancellationToken)
  52. {
  53. IEnumerable<MediaSourceInfo> sources;
  54. var forceRequireOpening = false;
  55. try
  56. {
  57. if (item is ILiveTvRecording)
  58. {
  59. sources = await _liveTvManager.GetRecordingMediaSources(item, cancellationToken)
  60. .ConfigureAwait(false);
  61. }
  62. else
  63. {
  64. sources = await _liveTvManager.GetChannelMediaSources(item, cancellationToken)
  65. .ConfigureAwait(false);
  66. }
  67. }
  68. catch (NotImplementedException)
  69. {
  70. var hasMediaSources = (IHasMediaSources)item;
  71. sources = _mediaSourceManager.GetStaticMediaSources(hasMediaSources, false);
  72. forceRequireOpening = true;
  73. }
  74. var list = sources.ToList();
  75. var serverUrl = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  76. foreach (var source in list)
  77. {
  78. source.Type = MediaSourceType.Default;
  79. source.BufferMs = source.BufferMs ?? 1500;
  80. if (source.RequiresOpening || forceRequireOpening)
  81. {
  82. source.RequiresOpening = true;
  83. }
  84. if (source.RequiresOpening)
  85. {
  86. var openKeys = new List<string>();
  87. openKeys.Add(item.GetType().Name);
  88. openKeys.Add(item.Id.ToString("N"));
  89. openKeys.Add(source.Id ?? string.Empty);
  90. source.OpenToken = string.Join(StreamIdDelimeterString, openKeys.ToArray());
  91. }
  92. // Dummy this up so that direct play checks can still run
  93. if (string.IsNullOrEmpty(source.Path) && source.Protocol == MediaProtocol.Http)
  94. {
  95. source.Path = serverUrl;
  96. }
  97. }
  98. _logger.Debug("MediaSources: {0}", _jsonSerializer.SerializeToString(list));
  99. return list;
  100. }
  101. public async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> OpenMediaSource(string openToken, bool allowLiveStreamProbe, CancellationToken cancellationToken)
  102. {
  103. MediaSourceInfo stream = null;
  104. const bool isAudio = false;
  105. var keys = openToken.Split(new[] { StreamIdDelimeter }, 3);
  106. var mediaSourceId = keys.Length >= 3 ? keys[2] : null;
  107. IDirectStreamProvider directStreamProvider = null;
  108. if (string.Equals(keys[0], typeof(LiveTvChannel).Name, StringComparison.OrdinalIgnoreCase))
  109. {
  110. var info = await _liveTvManager.GetChannelStream(keys[1], mediaSourceId, cancellationToken).ConfigureAwait(false);
  111. stream = info.Item1;
  112. directStreamProvider = info.Item2;
  113. }
  114. else
  115. {
  116. stream = await _liveTvManager.GetRecordingStream(keys[1], cancellationToken).ConfigureAwait(false);
  117. }
  118. try
  119. {
  120. if (!allowLiveStreamProbe || !stream.SupportsProbing || stream.MediaStreams.Any(i => i.Index != -1))
  121. {
  122. AddMediaInfo(stream, isAudio, cancellationToken);
  123. }
  124. else
  125. {
  126. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  127. }
  128. }
  129. catch (Exception ex)
  130. {
  131. _logger.ErrorException("Error probing live tv stream", ex);
  132. }
  133. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(stream));
  134. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(stream, directStreamProvider);
  135. }
  136. private void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  137. {
  138. mediaSource.DefaultSubtitleStreamIndex = null;
  139. // Null this out so that it will be treated like a live stream
  140. mediaSource.RunTimeTicks = null;
  141. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Audio);
  142. if (audioStream == null || audioStream.Index == -1)
  143. {
  144. mediaSource.DefaultAudioStreamIndex = null;
  145. }
  146. else
  147. {
  148. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  149. }
  150. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Video);
  151. if (videoStream != null)
  152. {
  153. if (!videoStream.BitRate.HasValue)
  154. {
  155. var width = videoStream.Width ?? 1920;
  156. if (width >= 3000)
  157. {
  158. videoStream.BitRate = 30000000;
  159. }
  160. else if (width >= 1900)
  161. {
  162. videoStream.BitRate = 20000000;
  163. }
  164. else if (width >= 1200)
  165. {
  166. videoStream.BitRate = 8000000;
  167. }
  168. else if (width >= 700)
  169. {
  170. videoStream.BitRate = 2000000;
  171. }
  172. }
  173. }
  174. // Try to estimate this
  175. mediaSource.InferTotalBitrate();
  176. }
  177. public Task CloseMediaSource(string liveStreamId)
  178. {
  179. return _liveTvManager.CloseLiveStream(liveStreamId);
  180. }
  181. }
  182. }