M3UTunerHost.cs 8.0 KB

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