M3UTunerHost.cs 7.6 KB

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