M3UTunerHost.cs 8.4 KB

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