LiveTvMediaSourceProvider.cs 8.6 KB

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