M3UTunerHost.cs 7.5 KB

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