BaseTunerHost.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.LiveTv;
  3. using MediaBrowser.Model.Dto;
  4. using MediaBrowser.Model.LiveTv;
  5. using Microsoft.Extensions.Logging;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.MediaEncoding;
  16. using MediaBrowser.Model.Dlna;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Controller.Library;
  20. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  21. {
  22. public abstract class BaseTunerHost
  23. {
  24. protected readonly IServerConfigurationManager Config;
  25. protected readonly ILogger Logger;
  26. protected IJsonSerializer JsonSerializer;
  27. protected readonly IMediaEncoder MediaEncoder;
  28. protected readonly IFileSystem FileSystem;
  29. private readonly ConcurrentDictionary<string, ChannelCache> _channelCache =
  30. new ConcurrentDictionary<string, ChannelCache>(StringComparer.OrdinalIgnoreCase);
  31. protected BaseTunerHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IFileSystem fileSystem)
  32. {
  33. Config = config;
  34. Logger = logger;
  35. JsonSerializer = jsonSerializer;
  36. MediaEncoder = mediaEncoder;
  37. FileSystem = fileSystem;
  38. }
  39. public virtual bool IsSupported
  40. {
  41. get
  42. {
  43. return true;
  44. }
  45. }
  46. protected abstract Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
  47. public abstract string Type { get; }
  48. public async Task<List<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken)
  49. {
  50. ChannelCache cache = null;
  51. var key = tuner.Id;
  52. if (enableCache && !string.IsNullOrEmpty(key) && _channelCache.TryGetValue(key, out cache))
  53. {
  54. return cache.Channels.ToList();
  55. }
  56. var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
  57. var list = result.ToList();
  58. //logger.LogInformation("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
  59. if (!string.IsNullOrEmpty(key) && list.Count > 0)
  60. {
  61. cache = cache ?? new ChannelCache();
  62. cache.Channels = list;
  63. _channelCache.AddOrUpdate(key, cache, (k, v) => cache);
  64. }
  65. return list;
  66. }
  67. protected virtual List<TunerHostInfo> GetTunerHosts()
  68. {
  69. return GetConfiguration().TunerHosts
  70. .Where(i => string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase))
  71. .ToList();
  72. }
  73. public async Task<List<ChannelInfo>> GetChannels(bool enableCache, CancellationToken cancellationToken)
  74. {
  75. var list = new List<ChannelInfo>();
  76. var hosts = GetTunerHosts();
  77. foreach (var host in hosts)
  78. {
  79. var channelCacheFile = Path.Combine(Config.ApplicationPaths.CachePath, host.Id + "_channels");
  80. try
  81. {
  82. var channels = await GetChannels(host, enableCache, cancellationToken).ConfigureAwait(false);
  83. var newChannels = channels.Where(i => !list.Any(l => string.Equals(i.Id, l.Id, StringComparison.OrdinalIgnoreCase))).ToList();
  84. list.AddRange(newChannels);
  85. if (!enableCache)
  86. {
  87. try
  88. {
  89. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(channelCacheFile));
  90. JsonSerializer.SerializeToFile(channels, channelCacheFile);
  91. }
  92. catch (IOException)
  93. {
  94. }
  95. }
  96. }
  97. catch (Exception ex)
  98. {
  99. Logger.LogError(ex, "Error getting channel list");
  100. if (enableCache)
  101. {
  102. try
  103. {
  104. var channels = JsonSerializer.DeserializeFromFile<List<ChannelInfo>>(channelCacheFile);
  105. list.AddRange(channels);
  106. }
  107. catch (IOException)
  108. {
  109. }
  110. }
  111. }
  112. }
  113. return list;
  114. }
  115. protected abstract Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, ChannelInfo channel, CancellationToken cancellationToken);
  116. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  117. {
  118. if (string.IsNullOrEmpty(channelId))
  119. {
  120. throw new ArgumentNullException("channelId");
  121. }
  122. if (IsValidChannelId(channelId))
  123. {
  124. var hosts = GetTunerHosts();
  125. foreach (var host in hosts)
  126. {
  127. try
  128. {
  129. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  130. var channelInfo = channels.FirstOrDefault(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  131. if (channelInfo != null)
  132. {
  133. return await GetChannelStreamMediaSources(host, channelInfo, cancellationToken).ConfigureAwait(false);
  134. }
  135. }
  136. catch (Exception ex)
  137. {
  138. Logger.LogError(ex, "Error getting channels");
  139. }
  140. }
  141. }
  142. return new List<MediaSourceInfo>();
  143. }
  144. protected abstract Task<ILiveStream> GetChannelStream(TunerHostInfo tuner, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken);
  145. public async Task<ILiveStream> GetChannelStream(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  146. {
  147. if (string.IsNullOrEmpty(channelId))
  148. {
  149. throw new ArgumentNullException("channelId");
  150. }
  151. if (!IsValidChannelId(channelId))
  152. {
  153. throw new FileNotFoundException();
  154. }
  155. var hosts = GetTunerHosts();
  156. var hostsWithChannel = new List<Tuple<TunerHostInfo, ChannelInfo>>();
  157. foreach (var host in hosts)
  158. {
  159. try
  160. {
  161. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  162. var channelInfo = channels.FirstOrDefault(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  163. if (channelInfo != null)
  164. {
  165. hostsWithChannel.Add(new Tuple<TunerHostInfo, ChannelInfo>(host, channelInfo));
  166. }
  167. }
  168. catch (Exception ex)
  169. {
  170. Logger.LogError(ex, "Error getting channels");
  171. }
  172. }
  173. foreach (var hostTuple in hostsWithChannel)
  174. {
  175. var host = hostTuple.Item1;
  176. var channelInfo = hostTuple.Item2;
  177. try
  178. {
  179. var liveStream = await GetChannelStream(host, channelInfo, streamId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
  180. var startTime = DateTime.UtcNow;
  181. await liveStream.Open(cancellationToken).ConfigureAwait(false);
  182. var endTime = DateTime.UtcNow;
  183. Logger.LogInformation("Live stream opened after {0}ms", (endTime - startTime).TotalMilliseconds);
  184. return liveStream;
  185. }
  186. catch (Exception ex)
  187. {
  188. Logger.LogError(ex, "Error opening tuner");
  189. }
  190. }
  191. throw new LiveTvConflictException();
  192. }
  193. protected virtual string ChannelIdPrefix
  194. {
  195. get
  196. {
  197. return Type + "_";
  198. }
  199. }
  200. protected virtual bool IsValidChannelId(string channelId)
  201. {
  202. if (string.IsNullOrEmpty(channelId))
  203. {
  204. throw new ArgumentNullException("channelId");
  205. }
  206. return channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase);
  207. }
  208. protected LiveTvOptions GetConfiguration()
  209. {
  210. return Config.GetConfiguration<LiveTvOptions>("livetv");
  211. }
  212. private class ChannelCache
  213. {
  214. public List<ChannelInfo> Channels;
  215. }
  216. }
  217. }