BaseTunerHost.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.LiveTv;
  3. using MediaBrowser.Model.Dto;
  4. using MediaBrowser.Model.LiveTv;
  5. using MediaBrowser.Model.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.Controller.Configuration;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Model.Dlna;
  16. using MediaBrowser.Model.Serialization;
  17. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts
  18. {
  19. public abstract class BaseTunerHost
  20. {
  21. protected readonly IServerConfigurationManager Config;
  22. protected readonly ILogger Logger;
  23. protected IJsonSerializer JsonSerializer;
  24. protected readonly IMediaEncoder MediaEncoder;
  25. private readonly ConcurrentDictionary<string, ChannelCache> _channelCache =
  26. new ConcurrentDictionary<string, ChannelCache>(StringComparer.OrdinalIgnoreCase);
  27. protected BaseTunerHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder)
  28. {
  29. Config = config;
  30. Logger = logger;
  31. JsonSerializer = jsonSerializer;
  32. MediaEncoder = mediaEncoder;
  33. }
  34. protected abstract Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken);
  35. public abstract string Type { get; }
  36. public async Task<IEnumerable<ChannelInfo>> GetChannels(TunerHostInfo tuner, bool enableCache, CancellationToken cancellationToken)
  37. {
  38. ChannelCache cache = null;
  39. var key = tuner.Id;
  40. if (enableCache && !string.IsNullOrWhiteSpace(key) && _channelCache.TryGetValue(key, out cache))
  41. {
  42. if (DateTime.UtcNow - cache.Date < TimeSpan.FromMinutes(60))
  43. {
  44. return cache.Channels.ToList();
  45. }
  46. }
  47. var result = await GetChannelsInternal(tuner, cancellationToken).ConfigureAwait(false);
  48. var list = result.ToList();
  49. Logger.Debug("Channels from {0}: {1}", tuner.Url, JsonSerializer.SerializeToString(list));
  50. if (!string.IsNullOrWhiteSpace(key) && list.Count > 0)
  51. {
  52. cache = cache ?? new ChannelCache();
  53. cache.Date = DateTime.UtcNow;
  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 => i.IsEnabled && string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase))
  63. .ToList();
  64. }
  65. public async Task<IEnumerable<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. try
  72. {
  73. var channels = await GetChannels(host, enableCache, cancellationToken).ConfigureAwait(false);
  74. var newChannels = channels.Where(i => !list.Any(l => string.Equals(i.Id, l.Id, StringComparison.OrdinalIgnoreCase))).ToList();
  75. list.AddRange(newChannels);
  76. }
  77. catch (Exception ex)
  78. {
  79. Logger.ErrorException("Error getting channel list", ex);
  80. }
  81. }
  82. return list;
  83. }
  84. protected abstract Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken);
  85. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  86. {
  87. if (IsValidChannelId(channelId))
  88. {
  89. var hosts = GetTunerHosts();
  90. var hostsWithChannel = new List<TunerHostInfo>();
  91. foreach (var host in hosts)
  92. {
  93. try
  94. {
  95. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  96. if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
  97. {
  98. hostsWithChannel.Add(host);
  99. }
  100. }
  101. catch (Exception ex)
  102. {
  103. Logger.Error("Error getting channels", ex);
  104. }
  105. }
  106. foreach (var host in hostsWithChannel)
  107. {
  108. try
  109. {
  110. // Check to make sure the tuner is available
  111. // If there's only one tuner, don't bother with the check and just let the tuner be the one to throw an error
  112. if (hostsWithChannel.Count > 1 &&
  113. !await IsAvailable(host, channelId, cancellationToken).ConfigureAwait(false))
  114. {
  115. Logger.Error("Tuner is not currently available");
  116. continue;
  117. }
  118. var mediaSources = await GetChannelStreamMediaSources(host, channelId, cancellationToken).ConfigureAwait(false);
  119. // Prefix the id with the host Id so that we can easily find it
  120. foreach (var mediaSource in mediaSources)
  121. {
  122. mediaSource.Id = host.Id + mediaSource.Id;
  123. }
  124. return mediaSources;
  125. }
  126. catch (Exception ex)
  127. {
  128. Logger.Error("Error opening tuner", ex);
  129. }
  130. }
  131. }
  132. return new List<MediaSourceInfo>();
  133. }
  134. protected abstract Task<LiveStream> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken);
  135. public async Task<LiveStream> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  136. {
  137. if (!IsValidChannelId(channelId))
  138. {
  139. throw new FileNotFoundException();
  140. }
  141. var hosts = GetTunerHosts();
  142. var hostsWithChannel = new List<TunerHostInfo>();
  143. foreach (var host in hosts)
  144. {
  145. if (string.IsNullOrWhiteSpace(streamId))
  146. {
  147. try
  148. {
  149. var channels = await GetChannels(host, true, cancellationToken).ConfigureAwait(false);
  150. if (channels.Any(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase)))
  151. {
  152. hostsWithChannel.Add(host);
  153. }
  154. }
  155. catch (Exception ex)
  156. {
  157. Logger.Error("Error getting channels", ex);
  158. }
  159. }
  160. else if (streamId.StartsWith(host.Id, StringComparison.OrdinalIgnoreCase))
  161. {
  162. hostsWithChannel = new List<TunerHostInfo> { host };
  163. streamId = streamId.Substring(host.Id.Length);
  164. break;
  165. }
  166. }
  167. foreach (var host in hostsWithChannel)
  168. {
  169. try
  170. {
  171. var liveStream = await GetChannelStream(host, channelId, streamId, cancellationToken).ConfigureAwait(false);
  172. await liveStream.Open(cancellationToken).ConfigureAwait(false);
  173. return liveStream;
  174. }
  175. catch (Exception ex)
  176. {
  177. Logger.Error("Error opening tuner", ex);
  178. }
  179. }
  180. throw new LiveTvConflictException();
  181. }
  182. protected virtual bool EnableMediaProbing
  183. {
  184. get { return false; }
  185. }
  186. protected async Task<bool> IsAvailable(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken)
  187. {
  188. try
  189. {
  190. return await IsAvailableInternal(tuner, channelId, cancellationToken).ConfigureAwait(false);
  191. }
  192. catch (Exception ex)
  193. {
  194. Logger.ErrorException("Error checking tuner availability", ex);
  195. return false;
  196. }
  197. }
  198. protected abstract Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken);
  199. private async Task AddMediaInfo(LiveStream stream, bool isAudio, CancellationToken cancellationToken)
  200. {
  201. //await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  202. //try
  203. //{
  204. // await AddMediaInfoInternal(mediaSource, isAudio, cancellationToken).ConfigureAwait(false);
  205. // // Leave the resource locked. it will be released upstream
  206. //}
  207. //catch (Exception)
  208. //{
  209. // // Release the resource if there's some kind of failure.
  210. // resourcePool.Release();
  211. // throw;
  212. //}
  213. }
  214. private async Task AddMediaInfoInternal(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken)
  215. {
  216. var originalRuntime = mediaSource.RunTimeTicks;
  217. var info = await MediaEncoder.GetMediaInfo(new MediaInfoRequest
  218. {
  219. InputPath = mediaSource.Path,
  220. Protocol = mediaSource.Protocol,
  221. MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
  222. ExtractChapters = false
  223. }, cancellationToken).ConfigureAwait(false);
  224. mediaSource.Bitrate = info.Bitrate;
  225. mediaSource.Container = info.Container;
  226. mediaSource.Formats = info.Formats;
  227. mediaSource.MediaStreams = info.MediaStreams;
  228. mediaSource.RunTimeTicks = info.RunTimeTicks;
  229. mediaSource.Size = info.Size;
  230. mediaSource.Timestamp = info.Timestamp;
  231. mediaSource.Video3DFormat = info.Video3DFormat;
  232. mediaSource.VideoType = info.VideoType;
  233. mediaSource.DefaultSubtitleStreamIndex = null;
  234. // Null this out so that it will be treated like a live stream
  235. if (!originalRuntime.HasValue)
  236. {
  237. mediaSource.RunTimeTicks = null;
  238. }
  239. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Audio);
  240. if (audioStream == null || audioStream.Index == -1)
  241. {
  242. mediaSource.DefaultAudioStreamIndex = null;
  243. }
  244. else
  245. {
  246. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  247. }
  248. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == Model.Entities.MediaStreamType.Video);
  249. if (videoStream != null)
  250. {
  251. if (!videoStream.BitRate.HasValue)
  252. {
  253. var width = videoStream.Width ?? 1920;
  254. if (width >= 1900)
  255. {
  256. videoStream.BitRate = 8000000;
  257. }
  258. else if (width >= 1260)
  259. {
  260. videoStream.BitRate = 3000000;
  261. }
  262. else if (width >= 700)
  263. {
  264. videoStream.BitRate = 1000000;
  265. }
  266. }
  267. }
  268. // Try to estimate this
  269. if (!mediaSource.Bitrate.HasValue)
  270. {
  271. var total = mediaSource.MediaStreams.Select(i => i.BitRate ?? 0).Sum();
  272. if (total > 0)
  273. {
  274. mediaSource.Bitrate = total;
  275. }
  276. }
  277. }
  278. protected abstract bool IsValidChannelId(string channelId);
  279. protected LiveTvOptions GetConfiguration()
  280. {
  281. return Config.GetConfiguration<LiveTvOptions>("livetv");
  282. }
  283. private class ChannelCache
  284. {
  285. public DateTime Date;
  286. public List<ChannelInfo> Channels;
  287. }
  288. }
  289. }