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