M3UTunerHost.cs 7.6 KB

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