LiveTvMediaSourceProvider.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. var forceRequireOpening = false;
  54. try
  55. {
  56. if (item is ILiveTvRecording)
  57. {
  58. sources = await _liveTvManager.GetRecordingMediaSources(item.Id.ToString("N"), cancellationToken)
  59. .ConfigureAwait(false);
  60. }
  61. else
  62. {
  63. sources = await _liveTvManager.GetChannelMediaSources(item.Id.ToString("N"), cancellationToken)
  64. .ConfigureAwait(false);
  65. }
  66. }
  67. catch (NotImplementedException)
  68. {
  69. var hasMediaSources = (IHasMediaSources)item;
  70. sources = _mediaSourceManager.GetStaticMediaSources(hasMediaSources, false)
  71. .ToList();
  72. forceRequireOpening = true;
  73. }
  74. var list = sources.ToList();
  75. var serverUrl = _appHost.LocalApiUrl;
  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<MediaSourceInfo> OpenMediaSource(string openToken, CancellationToken cancellationToken)
  102. {
  103. MediaSourceInfo stream;
  104. const bool isAudio = false;
  105. var keys = openToken.Split(new[] { StreamIdDelimeter }, 3);
  106. var mediaSourceId = keys.Length >= 3 ? keys[2] : null;
  107. if (string.Equals(keys[0], typeof(LiveTvChannel).Name, StringComparison.OrdinalIgnoreCase))
  108. {
  109. stream = await _liveTvManager.GetChannelStream(keys[1], mediaSourceId, cancellationToken).ConfigureAwait(false);
  110. }
  111. else
  112. {
  113. stream = await _liveTvManager.GetRecordingStream(keys[1], cancellationToken).ConfigureAwait(false);
  114. }
  115. try
  116. {
  117. await AddMediaInfo(stream, isAudio, cancellationToken).ConfigureAwait(false);
  118. }
  119. catch (Exception ex)
  120. {
  121. _logger.ErrorException("Error probing live tv stream", ex);
  122. }
  123. return stream;
  124. }
  125. private async Task AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  126. {
  127. var originalRuntime = mediaSource.RunTimeTicks;
  128. mediaSource.DefaultSubtitleStreamIndex = null;
  129. // Null this out so that it will be treated like a live stream
  130. if (!originalRuntime.HasValue)
  131. {
  132. mediaSource.RunTimeTicks = null;
  133. }
  134. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Audio);
  135. if (audioStream == null || audioStream.Index == -1)
  136. {
  137. mediaSource.DefaultAudioStreamIndex = null;
  138. }
  139. else
  140. {
  141. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  142. }
  143. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Video);
  144. if (videoStream != null)
  145. {
  146. if (!videoStream.BitRate.HasValue)
  147. {
  148. var width = videoStream.Width ?? 1920;
  149. if (width >= 1900)
  150. {
  151. videoStream.BitRate = 8000000;
  152. }
  153. else if (width >= 1260)
  154. {
  155. videoStream.BitRate = 3000000;
  156. }
  157. else if (width >= 700)
  158. {
  159. videoStream.BitRate = 1000000;
  160. }
  161. }
  162. }
  163. // Try to estimate this
  164. if (!mediaSource.Bitrate.HasValue)
  165. {
  166. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  167. if (total > 0)
  168. {
  169. mediaSource.Bitrate = total;
  170. }
  171. }
  172. }
  173. public Task CloseMediaSource(string liveStreamId, CancellationToken cancellationToken)
  174. {
  175. return _liveTvManager.CloseLiveStream(liveStreamId, cancellationToken);
  176. }
  177. }
  178. }