BaseTunerHost.cs 8.7 KB

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