M3UTunerHost.cs 8.4 KB

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