M3UTunerHost.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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).Parse(info.Url, channelIdPrefix, info.Id, cancellationToken).ConfigureAwait(false);
  61. }
  62. public Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken)
  63. {
  64. var list = GetTunerHosts()
  65. .Select(i => new LiveTvTunerInfo()
  66. {
  67. Name = Name,
  68. SourceType = Type,
  69. Status = LiveTvTunerStatus.Available,
  70. Id = i.Url.GetMD5().ToString("N", CultureInfo.InvariantCulture),
  71. Url = i.Url
  72. })
  73. .ToList();
  74. return Task.FromResult(list);
  75. }
  76. private static readonly string[] _disallowedSharedStreamExtensions =
  77. {
  78. ".mkv",
  79. ".mp4",
  80. ".m3u8",
  81. ".mpd"
  82. };
  83. protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  84. {
  85. var tunerCount = info.TunerCount;
  86. if (tunerCount > 0)
  87. {
  88. var tunerHostId = info.Id;
  89. var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase));
  90. if (liveStreams.Count() >= tunerCount)
  91. {
  92. throw new LiveTvConflictException("M3U simultaneous stream limit has been reached.");
  93. }
  94. }
  95. var sources = await GetChannelStreamMediaSources(info, channelInfo, cancellationToken).ConfigureAwait(false);
  96. var mediaSource = sources[0];
  97. if (mediaSource.Protocol == MediaProtocol.Http && !mediaSource.RequiresLooping)
  98. {
  99. var extension = Path.GetExtension(mediaSource.Path) ?? string.Empty;
  100. if (!_disallowedSharedStreamExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  101. {
  102. return new SharedHttpStream(mediaSource, info, streamId, FileSystem, _httpClientFactory, Logger, Config, _appHost, _streamHelper);
  103. }
  104. }
  105. return new LiveStream(mediaSource, info, FileSystem, Logger, Config, _streamHelper);
  106. }
  107. public async Task Validate(TunerHostInfo info)
  108. {
  109. using (var stream = await new M3uParser(Logger, _httpClientFactory, _appHost).GetListingsStream(info.Url, CancellationToken.None).ConfigureAwait(false))
  110. {
  111. }
  112. }
  113. protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, ChannelInfo channelInfo, CancellationToken cancellationToken)
  114. {
  115. return Task.FromResult(new List<MediaSourceInfo> { CreateMediaSourceInfo(info, channelInfo) });
  116. }
  117. protected virtual MediaSourceInfo CreateMediaSourceInfo(TunerHostInfo info, ChannelInfo channel)
  118. {
  119. var path = channel.Path;
  120. var supportsDirectPlay = !info.EnableStreamLooping && info.TunerCount == 0;
  121. var supportsDirectStream = !info.EnableStreamLooping;
  122. var protocol = _mediaSourceManager.GetPathProtocol(path);
  123. var isRemote = true;
  124. if (Uri.TryCreate(path, UriKind.Absolute, out var uri))
  125. {
  126. isRemote = !_networkManager.IsInLocalNetwork(uri.Host);
  127. }
  128. var httpHeaders = new Dictionary<string, string>();
  129. if (protocol == MediaProtocol.Http)
  130. {
  131. // Use user-defined user-agent. If there isn't one, make it look like a browser.
  132. httpHeaders[HeaderNames.UserAgent] = string.IsNullOrWhiteSpace(info.UserAgent) ?
  133. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
  134. info.UserAgent;
  135. }
  136. var mediaSource = new MediaSourceInfo
  137. {
  138. Path = path,
  139. Protocol = protocol,
  140. MediaStreams = new List<MediaStream>
  141. {
  142. new MediaStream
  143. {
  144. Type = MediaStreamType.Video,
  145. // Set the index to -1 because we don't know the exact index of the video stream within the container
  146. Index = -1,
  147. IsInterlaced = true
  148. },
  149. new MediaStream
  150. {
  151. Type = MediaStreamType.Audio,
  152. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  153. Index = -1
  154. }
  155. },
  156. RequiresOpening = true,
  157. RequiresClosing = true,
  158. RequiresLooping = info.EnableStreamLooping,
  159. ReadAtNativeFramerate = false,
  160. Id = channel.Path.GetMD5().ToString("N", CultureInfo.InvariantCulture),
  161. IsInfiniteStream = true,
  162. IsRemote = isRemote,
  163. IgnoreDts = true,
  164. SupportsDirectPlay = supportsDirectPlay,
  165. SupportsDirectStream = supportsDirectStream,
  166. RequiredHttpHeaders = httpHeaders
  167. };
  168. mediaSource.InferTotalBitrate();
  169. return mediaSource;
  170. }
  171. public Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken)
  172. {
  173. return Task.FromResult(new List<TunerHostInfo>());
  174. }
  175. }
  176. }