BaseTunerHost.cs 8.5 KB

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