BaseTunerHost.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. protected virtual 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. try
  92. {
  93. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  94. if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
  95. {
  96. hostsWithChannel.Add(host);
  97. }
  98. }
  99. catch (Exception ex)
  100. {
  101. Logger.Error("Error getting channels", ex);
  102. }
  103. }
  104. foreach (var host in hostsWithChannel)
  105. {
  106. var resourcePool = GetLock(host.Url);
  107. Logger.Debug("GetChannelStreamMediaSources - Waiting on tuner resource pool");
  108. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  109. Logger.Debug("GetChannelStreamMediaSources - Unlocked resource pool");
  110. try
  111. {
  112. // Check to make sure the tuner is available
  113. // If there's only one tuner, don't bother with the check and just let the tuner be the one to throw an error
  114. if (hostsWithChannel.Count > 1 &&
  115. !await IsAvailable(host, channelId, cancellationToken).ConfigureAwait(false))
  116. {
  117. Logger.Error("Tuner is not currently available");
  118. continue;
  119. }
  120. var mediaSources = await GetChannelStreamMediaSources(host, channelId, cancellationToken).ConfigureAwait(false);
  121. // Prefix the id with the host Id so that we can easily find it
  122. foreach (var mediaSource in mediaSources)
  123. {
  124. mediaSource.Id = host.Id + mediaSource.Id;
  125. }
  126. return mediaSources;
  127. }
  128. catch (Exception ex)
  129. {
  130. Logger.Error("Error opening tuner", ex);
  131. }
  132. finally
  133. {
  134. resourcePool.Release();
  135. }
  136. }
  137. }
  138. return new List<MediaSourceInfo>();
  139. }
  140. protected abstract Task<MediaSourceInfo> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken);
  141. public async Task<Tuple<MediaSourceInfo, SemaphoreSlim>> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  142. {
  143. if (IsValidChannelId(channelId))
  144. {
  145. var hosts = GetTunerHosts();
  146. var hostsWithChannel = new List<TunerHostInfo>();
  147. foreach (var host in hosts)
  148. {
  149. if (string.IsNullOrWhiteSpace(streamId))
  150. {
  151. try
  152. {
  153. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  154. if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
  155. {
  156. hostsWithChannel.Add(host);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. Logger.Error("Error getting channels", ex);
  162. }
  163. }
  164. else if (streamId.StartsWith(host.Id, StringComparison.OrdinalIgnoreCase))
  165. {
  166. hostsWithChannel = new List<TunerHostInfo> { host };
  167. streamId = streamId.Substring(host.Id.Length);
  168. break;
  169. }
  170. }
  171. foreach (var host in hostsWithChannel)
  172. {
  173. var resourcePool = GetLock(host.Url);
  174. Logger.Debug("GetChannelStream - Waiting on tuner resource pool");
  175. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  176. Logger.Debug("GetChannelStream - Unlocked resource pool");
  177. try
  178. {
  179. // Check to make sure the tuner is available
  180. // If there's only one tuner, don't bother with the check and just let the tuner be the one to throw an error
  181. // If a streamId is specified then availibility has already been checked in GetChannelStreamMediaSources
  182. if (string.IsNullOrWhiteSpace(streamId) && hostsWithChannel.Count > 1)
  183. {
  184. if (!await IsAvailable(host, channelId, cancellationToken).ConfigureAwait(false))
  185. {
  186. Logger.Error("Tuner is not currently available");
  187. resourcePool.Release();
  188. continue;
  189. }
  190. }
  191. var stream = await GetChannelStream(host, channelId, streamId, cancellationToken).ConfigureAwait(false);
  192. if (EnableMediaProbing)
  193. {
  194. await AddMediaInfo(stream, false, resourcePool, cancellationToken).ConfigureAwait(false);
  195. }
  196. return new Tuple<MediaSourceInfo, SemaphoreSlim>(stream, resourcePool);
  197. }
  198. catch (Exception ex)
  199. {
  200. Logger.Error("Error opening tuner", ex);
  201. resourcePool.Release();
  202. }
  203. }
  204. }
  205. throw new LiveTvConflictException();
  206. }
  207. protected virtual bool EnableMediaProbing
  208. {
  209. get { return false; }
  210. }
  211. protected async Task<bool> IsAvailable(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken)
  212. {
  213. try
  214. {
  215. return await IsAvailableInternal(tuner, channelId, cancellationToken).ConfigureAwait(false);
  216. }
  217. catch (Exception ex)
  218. {
  219. Logger.ErrorException("Error checking tuner availability", ex);
  220. return false;
  221. }
  222. }
  223. protected abstract Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken);
  224. /// <summary>
  225. /// The _semaphoreLocks
  226. /// </summary>
  227. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(StringComparer.OrdinalIgnoreCase);
  228. /// <summary>
  229. /// Gets the lock.
  230. /// </summary>
  231. /// <param name="url">The filename.</param>
  232. /// <returns>System.Object.</returns>
  233. private SemaphoreSlim GetLock(string url)
  234. {
  235. return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1));
  236. }
  237. private async Task AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  238. {
  239. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  240. try
  241. {
  242. await AddMediaInfoInternal(mediaSource, isAudio, cancellationToken).ConfigureAwait(false);
  243. // Leave the resource locked. it will be released upstream
  244. }
  245. catch (Exception)
  246. {
  247. // Release the resource if there's some kind of failure.
  248. resourcePool.Release();
  249. throw;
  250. }
  251. }
  252. private async Task AddMediaInfoInternal(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  253. {
  254. var originalRuntime = mediaSource.RunTimeTicks;
  255. var info = await MediaEncoder.GetMediaInfo(new MediaInfoRequest
  256. {
  257. InputPath = mediaSource.Path,
  258. Protocol = mediaSource.Protocol,
  259. MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
  260. ExtractChapters = false
  261. }, cancellationToken).ConfigureAwait(false);
  262. mediaSource.Bitrate = info.Bitrate;
  263. mediaSource.Container = info.Container;
  264. mediaSource.Formats = info.Formats;
  265. mediaSource.MediaStreams = info.MediaStreams;
  266. mediaSource.RunTimeTicks = info.RunTimeTicks;
  267. mediaSource.Size = info.Size;
  268. mediaSource.Timestamp = info.Timestamp;
  269. mediaSource.Video3DFormat = info.Video3DFormat;
  270. mediaSource.VideoType = info.VideoType;
  271. mediaSource.DefaultSubtitleStreamIndex = null;
  272. // Null this out so that it will be treated like a live stream
  273. if (!originalRuntime.HasValue)
  274. {
  275. mediaSource.RunTimeTicks = null;
  276. }
  277. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Audio);
  278. if (audioStream == null || audioStream.Index == -1)
  279. {
  280. mediaSource.DefaultAudioStreamIndex = null;
  281. }
  282. else
  283. {
  284. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  285. }
  286. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Video);
  287. if (videoStream != null)
  288. {
  289. if (!videoStream.BitRate.HasValue)
  290. {
  291. var width = videoStream.Width ?? 1920;
  292. if (width >= 1900)
  293. {
  294. videoStream.BitRate = 8000000;
  295. }
  296. else if (width >= 1260)
  297. {
  298. videoStream.BitRate = 3000000;
  299. }
  300. else if (width >= 700)
  301. {
  302. videoStream.BitRate = 1000000;
  303. }
  304. }
  305. }
  306. // Try to estimate this
  307. if (!mediaSource.Bitrate.HasValue)
  308. {
  309. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  310. if (total > 0)
  311. {
  312. mediaSource.Bitrate = total;
  313. }
  314. }
  315. }
  316. protected abstract bool IsValidChannelId(string channelId);
  317. protected LiveTvOptions GetConfiguration()
  318. {
  319. return Config.GetConfiguration<LiveTvOptions>("livetv");
  320. }
  321. private class ChannelCache
  322. {
  323. public DateTime Date;
  324. public List<ChannelInfo> Channels;
  325. }
  326. }
  327. }