M3UTunerHost.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Common.Extensions;
  12. using MediaBrowser.Common.Net;
  13. using MediaBrowser.Controller;
  14. using MediaBrowser.Controller.Configuration;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.LiveTv;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.LiveTv;
  21. using MediaBrowser.Model.MediaInfo;
  22. using Microsoft.Extensions.Caching.Memory;
  23. using Microsoft.Extensions.Logging;
  24. using Microsoft.Net.Http.Headers;
  25. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  26. {
  27. public class M3UTunerHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
  28. {
  29. private static readonly string[] _disallowedSharedStreamExtensions =
  30. {
  31. ".mkv",
  32. ".mp4",
  33. ".m3u8",
  34. ".mpd"
  35. };
  36. private readonly IHttpClientFactory _httpClientFactory;
  37. private readonly IServerApplicationHost _appHost;
  38. private readonly INetworkManager _networkManager;
  39. private readonly IMediaSourceManager _mediaSourceManager;
  40. private readonly IStreamHelper _streamHelper;
  41. public M3UTunerHost(
  42. IServerConfigurationManager config,
  43. IMediaSourceManager mediaSourceManager,
  44. ILogger<M3UTunerHost> logger,
  45. IFileSystem fileSystem,
  46. IHttpClientFactory httpClientFactory,
  47. IServerApplicationHost appHost,
  48. INetworkManager networkManager,
  49. IStreamHelper streamHelper,
  50. IMemoryCache memoryCache)
  51. : base(config, logger, fileSystem, memoryCache)
  52. {
  53. _httpClientFactory = httpClientFactory;
  54. _appHost = appHost;
  55. _networkManager = networkManager;
  56. _mediaSourceManager = mediaSourceManager;
  57. _streamHelper = streamHelper;
  58. }
  59. public override string Type => "m3u";
  60. public virtual string Name => "M3U Tuner";
  61. private string GetFullChannelIdPrefix(TunerHostInfo info)
  62. {
  63. return ChannelIdPrefix + info.Url.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  64. }
  65. protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken)
  66. {
  67. var channelIdPrefix = GetFullChannelIdPrefix(info);
  68. return await new M3uParser(Logger, _httpClientFactory)
  69. .Parse(info, channelIdPrefix, cancellationToken)
  70. .ConfigureAwait(false);
  71. }
  72. public Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken)
  73. {
  74. var list = GetTunerHosts()
  75. .Select(i => new LiveTvTunerInfo()
  76. {
  77. Name = Name,
  78. SourceType = Type,
  79. Status = LiveTvTunerStatus.Available,
  80. Id = i.Url.GetMD5().ToString("N", CultureInfo.InvariantCulture),
  81. Url = i.Url
  82. })
  83. .ToList();
  84. return Task.FromResult(list);
  85. }
  86. protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  87. {
  88. var tunerCount = info.TunerCount;
  89. if (tunerCount > 0)
  90. {
  91. var tunerHostId = info.Id;
  92. var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase));
  93. if (liveStreams.Count() >= tunerCount)
  94. {
  95. throw new LiveTvConflictException("M3U simultaneous stream limit has been reached.");
  96. }
  97. }
  98. var sources = await GetChannelStreamMediaSources(info, channelInfo, cancellationToken).ConfigureAwait(false);
  99. var mediaSource = sources[0];
  100. if (mediaSource.Protocol == MediaProtocol.Http && !mediaSource.RequiresLooping)
  101. {
  102. var extension = Path.GetExtension(mediaSource.Path) ?? string.Empty;
  103. if (!_disallowedSharedStreamExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  104. {
  105. return new SharedHttpStream(mediaSource, info, streamId, FileSystem, _httpClientFactory, Logger, Config, _appHost, _streamHelper);
  106. }
  107. }
  108. return new LiveStream(mediaSource, info, FileSystem, Logger, Config, _streamHelper);
  109. }
  110. public async Task Validate(TunerHostInfo info)
  111. {
  112. using (var stream = await new M3uParser(Logger, _httpClientFactory).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false))
  113. {
  114. }
  115. }
  116. protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, ChannelInfo channelInfo, CancellationToken cancellationToken)
  117. {
  118. return Task.FromResult(new List<MediaSourceInfo> { CreateMediaSourceInfo(info, channelInfo) });
  119. }
  120. protected virtual MediaSourceInfo CreateMediaSourceInfo(TunerHostInfo info, ChannelInfo channel)
  121. {
  122. var path = channel.Path;
  123. var supportsDirectPlay = !info.EnableStreamLooping && info.TunerCount == 0;
  124. var supportsDirectStream = !info.EnableStreamLooping;
  125. var protocol = _mediaSourceManager.GetPathProtocol(path);
  126. var isRemote = true;
  127. if (Uri.TryCreate(path, UriKind.Absolute, out var uri))
  128. {
  129. isRemote = !_networkManager.IsInLocalNetwork(uri.Host);
  130. }
  131. var httpHeaders = new Dictionary<string, string>();
  132. if (protocol == MediaProtocol.Http)
  133. {
  134. // Use user-defined user-agent. If there isn't one, make it look like a browser.
  135. httpHeaders[HeaderNames.UserAgent] = string.IsNullOrWhiteSpace(info.UserAgent) ?
  136. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
  137. info.UserAgent;
  138. }
  139. var mediaSource = new MediaSourceInfo
  140. {
  141. Path = path,
  142. Protocol = protocol,
  143. MediaStreams = new List<MediaStream>
  144. {
  145. new MediaStream
  146. {
  147. Type = MediaStreamType.Video,
  148. // Set the index to -1 because we don't know the exact index of the video stream within the container
  149. Index = -1,
  150. IsInterlaced = true
  151. },
  152. new MediaStream
  153. {
  154. Type = MediaStreamType.Audio,
  155. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  156. Index = -1
  157. }
  158. },
  159. RequiresOpening = true,
  160. RequiresClosing = true,
  161. RequiresLooping = info.EnableStreamLooping,
  162. ReadAtNativeFramerate = false,
  163. Id = channel.Path.GetMD5().ToString("N", CultureInfo.InvariantCulture),
  164. IsInfiniteStream = true,
  165. IsRemote = isRemote,
  166. IgnoreDts = true,
  167. SupportsDirectPlay = supportsDirectPlay,
  168. SupportsDirectStream = supportsDirectStream,
  169. RequiredHttpHeaders = httpHeaders
  170. };
  171. mediaSource.InferTotalBitrate();
  172. return mediaSource;
  173. }
  174. public Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken)
  175. {
  176. return Task.FromResult(new List<TunerHostInfo>());
  177. }
  178. }
  179. }