LiveTvMediaSourceProvider.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. source.RequiresOpening = true;
  78. source.BufferMs = source.BufferMs ?? 1500;
  79. var openKeys = new List<string>();
  80. openKeys.Add(item.GetType().Name);
  81. openKeys.Add(item.Id.ToString("N"));
  82. openKeys.Add(source.Id ?? string.Empty);
  83. source.OpenToken = string.Join(StreamIdDelimeterString, openKeys.ToArray());
  84. // Dummy this up so that direct play checks can still run
  85. if (string.IsNullOrEmpty(source.Path) && source.Protocol == MediaProtocol.Http)
  86. {
  87. source.Path = serverUrl;
  88. }
  89. }
  90. _logger.Debug("MediaSources: {0}", _jsonSerializer.SerializeToString(list));
  91. return list;
  92. }
  93. public async Task<MediaSourceInfo> OpenMediaSource(string openToken, CancellationToken cancellationToken)
  94. {
  95. MediaSourceInfo stream;
  96. const bool isAudio = false;
  97. var keys = openToken.Split(new[] { StreamIdDelimeter }, 3);
  98. var mediaSourceId = keys.Length >= 3 ? keys[2] : null;
  99. if (string.Equals(keys[0], typeof(LiveTvChannel).Name, StringComparison.OrdinalIgnoreCase))
  100. {
  101. stream = await _liveTvManager.GetChannelStream(keys[1], mediaSourceId, cancellationToken).ConfigureAwait(false);
  102. }
  103. else
  104. {
  105. stream = await _liveTvManager.GetRecordingStream(keys[1], cancellationToken).ConfigureAwait(false);
  106. }
  107. try
  108. {
  109. await AddMediaInfo(stream, isAudio, cancellationToken).ConfigureAwait(false);
  110. }
  111. catch (Exception ex)
  112. {
  113. _logger.ErrorException("Error probing live tv stream", ex);
  114. }
  115. return stream;
  116. }
  117. private async Task AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  118. {
  119. var originalRuntime = mediaSource.RunTimeTicks;
  120. mediaSource.DefaultSubtitleStreamIndex = null;
  121. // Null this out so that it will be treated like a live stream
  122. if (!originalRuntime.HasValue)
  123. {
  124. mediaSource.RunTimeTicks = null;
  125. }
  126. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Audio);
  127. if (audioStream == null || audioStream.Index == -1)
  128. {
  129. mediaSource.DefaultAudioStreamIndex = null;
  130. }
  131. else
  132. {
  133. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  134. }
  135. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Video);
  136. if (videoStream != null)
  137. {
  138. if (!videoStream.BitRate.HasValue)
  139. {
  140. var width = videoStream.Width ?? 1920;
  141. if (width >= 1900)
  142. {
  143. videoStream.BitRate = 8000000;
  144. }
  145. else if (width >= 1260)
  146. {
  147. videoStream.BitRate = 3000000;
  148. }
  149. else if (width >= 700)
  150. {
  151. videoStream.BitRate = 1000000;
  152. }
  153. }
  154. }
  155. // Try to estimate this
  156. if (!mediaSource.Bitrate.HasValue)
  157. {
  158. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  159. if (total > 0)
  160. {
  161. mediaSource.Bitrate = total;
  162. }
  163. }
  164. }
  165. public Task CloseMediaSource(string liveStreamId, CancellationToken cancellationToken)
  166. {
  167. return _liveTvManager.CloseLiveStream(liveStreamId, cancellationToken);
  168. }
  169. }
  170. }