BaseTunerHost.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.LiveTv;
  3. using MediaBrowser.Model.Dto;
  4. using MediaBrowser.Model.LiveTv;
  5. using MediaBrowser.Model.Logging;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Controller.MediaEncoding;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Serialization;
  15. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
  16. {
  17. public abstract class BaseTunerHost
  18. {
  19. protected readonly IConfigurationManager Config;
  20. protected readonly ILogger Logger;
  21. protected IJsonSerializer JsonSerializer;
  22. protected readonly IMediaEncoder MediaEncoder;
  23. private readonly ConcurrentDictionary<string, ChannelCache> _channelCache =
  24. new ConcurrentDictionary<string, ChannelCache>(StringComparer.OrdinalIgnoreCase);
  25. protected BaseTunerHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder)
  26. {
  27. Config = config;
  28. Logger = logger;
  29. JsonSerializer = jsonSerializer;
  30. MediaEncoder = mediaEncoder;
  31. }
  32. protected abstract Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
  33. public abstract string Type { get; }
  34. public async Task<IEnumerable<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken)
  35. {
  36. ChannelCache cache = null;
  37. var key = tuner.Id;
  38. if (enableCache && !string.IsNullOrWhiteSpace(key) && _channelCache.TryGetValue(key, out cache))
  39. {
  40. if ((DateTime.UtcNow - cache.Date) < TimeSpan.FromMinutes(60))
  41. {
  42. return cache.Channels.ToList();
  43. }
  44. }
  45. var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
  46. var list = result.ToList();
  47. Logger.Debug("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
  48. if (!string.IsNullOrWhiteSpace(key) && list.Count > 0)
  49. {
  50. cache = cache ?? new ChannelCache();
  51. cache.Date = DateTime.UtcNow;
  52. cache.Channels = list;
  53. _channelCache.AddOrUpdate(key, cache, (k, v) => cache);
  54. }
  55. return list;
  56. }
  57. private List<TunerHostInfo> GetTunerHosts()
  58. {
  59. return GetConfiguration().TunerHosts
  60. .Where(i => i.IsEnabled && string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase))
  61. .ToList();
  62. }
  63. public async Task<IEnumerable<ChannelInfo>> GetChannels(CancellationToken cancellationToken)
  64. {
  65. var list = new List<ChannelInfo>();
  66. var hosts = GetTunerHosts();
  67. foreach (var host in hosts)
  68. {
  69. try
  70. {
  71. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  72. var newChannels = channels.Where(i => !list.Any(l => string.Equals(i.Id, l.Id, StringComparison.OrdinalIgnoreCase))).ToList();
  73. list.AddRange(newChannels);
  74. }
  75. catch (Exception ex)
  76. {
  77. Logger.ErrorException("Error getting channel list", ex);
  78. }
  79. }
  80. return list;
  81. }
  82. protected abstract Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken);
  83. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  84. {
  85. if (IsValidChannelId(channelId))
  86. {
  87. var hosts = GetTunerHosts();
  88. var hostsWithChannel = new List<TunerHostInfo>();
  89. foreach (var host in hosts)
  90. {
  91. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  92. if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
  93. {
  94. hostsWithChannel.Add(host);
  95. }
  96. }
  97. foreach (var host in hostsWithChannel)
  98. {
  99. try
  100. {
  101. var mediaSources = await GetChannelStreamMediaSources(host, channelId, cancellationToken).ConfigureAwait(false);
  102. // Prefix the id with the host Id so that we can easily find it
  103. foreach (var mediaSource in mediaSources)
  104. {
  105. mediaSource.Id = host.Id + mediaSource.Id;
  106. }
  107. return mediaSources;
  108. }
  109. catch (Exception ex)
  110. {
  111. Logger.Error("Error opening tuner", ex);
  112. }
  113. }
  114. }
  115. return new List<MediaSourceInfo>();
  116. }
  117. protected abstract Task<MediaSourceInfo> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken);
  118. public async Task<Tuple<MediaSourceInfo, SemaphoreSlim>> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  119. {
  120. if (IsValidChannelId(channelId))
  121. {
  122. var hosts = GetTunerHosts();
  123. var hostsWithChannel = new List<TunerHostInfo>();
  124. foreach (var host in hosts)
  125. {
  126. if (string.IsNullOrWhiteSpace(streamId))
  127. {
  128. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  129. if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
  130. {
  131. hostsWithChannel.Add(host);
  132. }
  133. }
  134. else if (streamId.StartsWith(host.Id, StringComparison.OrdinalIgnoreCase))
  135. {
  136. hostsWithChannel = new List<TunerHostInfo> { host };
  137. streamId = streamId.Substring(host.Id.Length);
  138. break;
  139. }
  140. }
  141. foreach (var host in hostsWithChannel)
  142. {
  143. try
  144. {
  145. var stream = await GetChannelStream(host, channelId, streamId, cancellationToken).ConfigureAwait(false);
  146. var resourcePool = GetLock(host.Url);
  147. await AddMediaInfo(stream, false, resourcePool, cancellationToken).ConfigureAwait(false);
  148. return new Tuple<MediaSourceInfo, SemaphoreSlim>(stream, resourcePool);
  149. }
  150. catch (Exception ex)
  151. {
  152. Logger.Error("Error opening tuner", ex);
  153. }
  154. }
  155. }
  156. throw new LiveTvConflictException();
  157. }
  158. /// <summary>
  159. /// The _semaphoreLocks
  160. /// </summary>
  161. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(StringComparer.OrdinalIgnoreCase);
  162. /// <summary>
  163. /// Gets the lock.
  164. /// </summary>
  165. /// <param name="url">The filename.</param>
  166. /// <returns>System.Object.</returns>
  167. private SemaphoreSlim GetLock(string url)
  168. {
  169. return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1));
  170. }
  171. private async Task AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  172. {
  173. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  174. try
  175. {
  176. await AddMediaInfoInternal(mediaSource, isAudio, cancellationToken).ConfigureAwait(false);
  177. // Leave the resource locked. it will be released upstream
  178. }
  179. catch (Exception)
  180. {
  181. // Release the resource if there's some kind of failure.
  182. resourcePool.Release();
  183. throw;
  184. }
  185. }
  186. private async Task AddMediaInfoInternal(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  187. {
  188. var originalRuntime = mediaSource.RunTimeTicks;
  189. var info = await MediaEncoder.GetMediaInfo(new MediaInfoRequest
  190. {
  191. InputPath = mediaSource.Path,
  192. Protocol = mediaSource.Protocol,
  193. MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
  194. ExtractChapters = false
  195. }, cancellationToken).ConfigureAwait(false);
  196. mediaSource.Bitrate = info.Bitrate;
  197. mediaSource.Container = info.Container;
  198. mediaSource.Formats = info.Formats;
  199. mediaSource.MediaStreams = info.MediaStreams;
  200. mediaSource.RunTimeTicks = info.RunTimeTicks;
  201. mediaSource.Size = info.Size;
  202. mediaSource.Timestamp = info.Timestamp;
  203. mediaSource.Video3DFormat = info.Video3DFormat;
  204. mediaSource.VideoType = info.VideoType;
  205. mediaSource.DefaultSubtitleStreamIndex = null;
  206. // Null this out so that it will be treated like a live stream
  207. if (!originalRuntime.HasValue)
  208. {
  209. mediaSource.RunTimeTicks = null;
  210. }
  211. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Audio);
  212. if (audioStream == null || audioStream.Index == -1)
  213. {
  214. mediaSource.DefaultAudioStreamIndex = null;
  215. }
  216. else
  217. {
  218. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  219. }
  220. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Video);
  221. if (videoStream != null)
  222. {
  223. if (!videoStream.BitRate.HasValue)
  224. {
  225. var width = videoStream.Width ?? 1920;
  226. if (width >= 1900)
  227. {
  228. videoStream.BitRate = 8000000;
  229. }
  230. else if (width >= 1260)
  231. {
  232. videoStream.BitRate = 3000000;
  233. }
  234. else if (width >= 700)
  235. {
  236. videoStream.BitRate = 1000000;
  237. }
  238. }
  239. }
  240. // Try to estimate this
  241. if (!mediaSource.Bitrate.HasValue)
  242. {
  243. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  244. if (total > 0)
  245. {
  246. mediaSource.Bitrate = total;
  247. }
  248. }
  249. }
  250. protected abstract bool IsValidChannelId(string channelId);
  251. protected LiveTvOptions GetConfiguration()
  252. {
  253. return Config.GetConfiguration<LiveTvOptions>("livetv");
  254. }
  255. private class ChannelCache
  256. {
  257. public DateTime Date;
  258. public List<ChannelInfo> Channels;
  259. }
  260. }
  261. }