BaseTunerHost.cs 8.5 KB

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