M3UTunerHost.cs 8.0 KB

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