LiveTvMediaSourceProvider.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. //allowLiveStreamProbe = false;
  124. }
  125. else
  126. {
  127. stream = await _liveTvManager.GetRecordingStream(keys[1], cancellationToken).ConfigureAwait(false);
  128. }
  129. try
  130. {
  131. if (!allowLiveStreamProbe || !stream.SupportsProbing || stream.MediaStreams.Any(i => i.Index != -1))
  132. {
  133. AddMediaInfo(stream, isAudio, cancellationToken);
  134. }
  135. else
  136. {
  137. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  138. }
  139. }
  140. catch (Exception ex)
  141. {
  142. _logger.ErrorException("Error probing live tv stream", ex);
  143. }
  144. _logger.Info("Live stream info: {0}", _jsonSerializer.SerializeToString(stream));
  145. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(stream, directStreamProvider);
  146. }
  147. private void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  148. {
  149. mediaSource.DefaultSubtitleStreamIndex = null;
  150. // Null this out so that it will be treated like a live stream
  151. mediaSource.RunTimeTicks = null;
  152. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Audio);
  153. if (audioStream == null || audioStream.Index == -1)
  154. {
  155. mediaSource.DefaultAudioStreamIndex = null;
  156. }
  157. else
  158. {
  159. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  160. }
  161. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaBrowser.Model.Entities.MediaStreamType.Video);
  162. if (videoStream != null)
  163. {
  164. if (!videoStream.BitRate.HasValue)
  165. {
  166. var width = videoStream.Width ?? 1920;
  167. if (width >= 3000)
  168. {
  169. videoStream.BitRate = 30000000;
  170. }
  171. else if (width >= 1900)
  172. {
  173. videoStream.BitRate = 20000000;
  174. }
  175. else if (width >= 1200)
  176. {
  177. videoStream.BitRate = 8000000;
  178. }
  179. else if (width >= 700)
  180. {
  181. videoStream.BitRate = 2000000;
  182. }
  183. }
  184. }
  185. // Try to estimate this
  186. mediaSource.InferTotalBitrate();
  187. }
  188. public Task CloseMediaSource(string liveStreamId)
  189. {
  190. return _liveTvManager.CloseLiveStream(liveStreamId);
  191. }
  192. }
  193. }