LiveTvMediaSourceProvider.cs 7.6 KB

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