BaseTunerHost.cs 9.0 KB

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