M3UTunerHost.cs 7.8 KB

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