M3UTunerHost.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Extensions;
  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.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 static readonly string[] _disallowedMimeTypes =
  29. {
  30. "video/x-matroska",
  31. "video/mp4",
  32. "application/vnd.apple.mpegurl",
  33. "application/mpegurl",
  34. "application/x-mpegurl",
  35. "video/vnd.mpeg.dash.mpd"
  36. };
  37. private readonly IHttpClientFactory _httpClientFactory;
  38. private readonly IServerApplicationHost _appHost;
  39. private readonly INetworkManager _networkManager;
  40. private readonly IMediaSourceManager _mediaSourceManager;
  41. private readonly IStreamHelper _streamHelper;
  42. public M3UTunerHost(
  43. IServerConfigurationManager config,
  44. IMediaSourceManager mediaSourceManager,
  45. ILogger<M3UTunerHost> logger,
  46. IFileSystem fileSystem,
  47. IHttpClientFactory httpClientFactory,
  48. IServerApplicationHost appHost,
  49. INetworkManager networkManager,
  50. IStreamHelper streamHelper)
  51. : base(config, logger, fileSystem)
  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 tuner, CancellationToken cancellationToken)
  66. {
  67. var channelIdPrefix = GetFullChannelIdPrefix(tuner);
  68. return await new M3uParser(Logger, _httpClientFactory)
  69. .Parse(tuner, 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 tunerHost, ChannelInfo channel, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  87. {
  88. var tunerCount = tunerHost.TunerCount;
  89. if (tunerCount > 0)
  90. {
  91. var tunerHostId = tunerHost.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(tunerHost, channel, cancellationToken).ConfigureAwait(false);
  99. var mediaSource = sources[0];
  100. if (mediaSource.Protocol == MediaProtocol.Http && !mediaSource.RequiresLooping)
  101. {
  102. using var message = new HttpRequestMessage(HttpMethod.Head, mediaSource.Path);
  103. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  104. .SendAsync(message, cancellationToken)
  105. .ConfigureAwait(false);
  106. response.EnsureSuccessStatusCode();
  107. if (!_disallowedMimeTypes.Contains(response.Content.Headers.ContentType?.ToString(), StringComparison.OrdinalIgnoreCase))
  108. {
  109. return new SharedHttpStream(mediaSource, tunerHost, streamId, FileSystem, _httpClientFactory, Logger, Config, _appHost, _streamHelper);
  110. }
  111. }
  112. return new LiveStream(mediaSource, tunerHost, FileSystem, Logger, Config, _streamHelper);
  113. }
  114. public async Task Validate(TunerHostInfo info)
  115. {
  116. using (await new M3uParser(Logger, _httpClientFactory).GetListingsStream(info, CancellationToken.None).ConfigureAwait(false))
  117. {
  118. }
  119. }
  120. protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, ChannelInfo channel, CancellationToken cancellationToken)
  121. {
  122. return Task.FromResult(new List<MediaSourceInfo> { CreateMediaSourceInfo(tuner, channel) });
  123. }
  124. protected virtual MediaSourceInfo CreateMediaSourceInfo(TunerHostInfo info, ChannelInfo channel)
  125. {
  126. var path = channel.Path;
  127. var supportsDirectPlay = !info.EnableStreamLooping && info.TunerCount == 0;
  128. var supportsDirectStream = !info.EnableStreamLooping;
  129. var protocol = _mediaSourceManager.GetPathProtocol(path);
  130. var isRemote = true;
  131. if (Uri.TryCreate(path, UriKind.Absolute, out var uri))
  132. {
  133. isRemote = !_networkManager.IsInLocalNetwork(uri.Host);
  134. }
  135. var httpHeaders = new Dictionary<string, string>();
  136. if (protocol == MediaProtocol.Http)
  137. {
  138. // Use user-defined user-agent. If there isn't one, make it look like a browser.
  139. httpHeaders[HeaderNames.UserAgent] = string.IsNullOrWhiteSpace(info.UserAgent) ?
  140. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.85 Safari/537.36" :
  141. info.UserAgent;
  142. }
  143. var mediaSource = new MediaSourceInfo
  144. {
  145. Path = path,
  146. Protocol = protocol,
  147. MediaStreams = new MediaStream[]
  148. {
  149. new MediaStream
  150. {
  151. Type = MediaStreamType.Video,
  152. // Set the index to -1 because we don't know the exact index of the video stream within the container
  153. Index = -1,
  154. IsInterlaced = true
  155. },
  156. new MediaStream
  157. {
  158. Type = MediaStreamType.Audio,
  159. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  160. Index = -1
  161. }
  162. },
  163. RequiresOpening = true,
  164. RequiresClosing = true,
  165. RequiresLooping = info.EnableStreamLooping,
  166. ReadAtNativeFramerate = false,
  167. Id = channel.Path.GetMD5().ToString("N", CultureInfo.InvariantCulture),
  168. IsInfiniteStream = true,
  169. IsRemote = isRemote,
  170. IgnoreDts = info.IgnoreDts,
  171. SupportsDirectPlay = supportsDirectPlay,
  172. SupportsDirectStream = supportsDirectStream,
  173. RequiredHttpHeaders = httpHeaders
  174. };
  175. mediaSource.InferTotalBitrate();
  176. return mediaSource;
  177. }
  178. public Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken)
  179. {
  180. return Task.FromResult(new List<TunerHostInfo>());
  181. }
  182. }
  183. }