HdHomerunHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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.Net;
  8. using System.Net.Http;
  9. using System.Text.Json;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Common.Json;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Controller;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Library;
  18. using MediaBrowser.Controller.LiveTv;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.IO;
  22. using MediaBrowser.Model.LiveTv;
  23. using MediaBrowser.Model.MediaInfo;
  24. using MediaBrowser.Model.Net;
  25. using Microsoft.Extensions.Caching.Memory;
  26. using Microsoft.Extensions.Logging;
  27. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  28. {
  29. public class HdHomerunHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
  30. {
  31. private readonly IHttpClientFactory _httpClientFactory;
  32. private readonly IServerApplicationHost _appHost;
  33. private readonly ISocketFactory _socketFactory;
  34. private readonly INetworkManager _networkManager;
  35. private readonly IStreamHelper _streamHelper;
  36. private readonly JsonSerializerOptions _jsonOptions;
  37. private readonly Dictionary<string, DiscoverResponse> _modelCache = new Dictionary<string, DiscoverResponse>();
  38. public HdHomerunHost(
  39. IServerConfigurationManager config,
  40. ILogger<HdHomerunHost> logger,
  41. IFileSystem fileSystem,
  42. IHttpClientFactory httpClientFactory,
  43. IServerApplicationHost appHost,
  44. ISocketFactory socketFactory,
  45. INetworkManager networkManager,
  46. IStreamHelper streamHelper,
  47. IMemoryCache memoryCache)
  48. : base(config, logger, fileSystem, memoryCache)
  49. {
  50. _httpClientFactory = httpClientFactory;
  51. _appHost = appHost;
  52. _socketFactory = socketFactory;
  53. _networkManager = networkManager;
  54. _streamHelper = streamHelper;
  55. _jsonOptions = JsonDefaults.Options;
  56. }
  57. public string Name => "HD Homerun";
  58. public override string Type => "hdhomerun";
  59. protected override string ChannelIdPrefix => "hdhr_";
  60. private string GetChannelId(TunerHostInfo info, Channels i)
  61. => ChannelIdPrefix + i.GuideNumber;
  62. internal async Task<List<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken)
  63. {
  64. var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  65. using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(model.LineupURL, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  66. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  67. var lineup = await JsonSerializer.DeserializeAsync<List<Channels>>(stream, _jsonOptions, cancellationToken)
  68. .ConfigureAwait(false) ?? new List<Channels>();
  69. if (info.ImportFavoritesOnly)
  70. {
  71. lineup = lineup.Where(i => i.Favorite).ToList();
  72. }
  73. return lineup.Where(i => !i.DRM).ToList();
  74. }
  75. private class HdHomerunChannelInfo : ChannelInfo
  76. {
  77. public bool IsLegacyTuner { get; set; }
  78. }
  79. protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken)
  80. {
  81. var lineup = await GetLineup(info, cancellationToken).ConfigureAwait(false);
  82. return lineup.Select(i => new HdHomerunChannelInfo
  83. {
  84. Name = i.GuideName,
  85. Number = i.GuideNumber,
  86. Id = GetChannelId(info, i),
  87. IsFavorite = i.Favorite,
  88. TunerHostId = info.Id,
  89. IsHD = i.HD,
  90. AudioCodec = i.AudioCodec,
  91. VideoCodec = i.VideoCodec,
  92. ChannelType = ChannelType.TV,
  93. IsLegacyTuner = (i.URL ?? string.Empty).StartsWith("hdhomerun", StringComparison.OrdinalIgnoreCase),
  94. Path = i.URL
  95. }).Cast<ChannelInfo>().ToList();
  96. }
  97. internal async Task<DiscoverResponse> GetModelInfo(TunerHostInfo info, bool throwAllExceptions, CancellationToken cancellationToken)
  98. {
  99. var cacheKey = info.Id;
  100. lock (_modelCache)
  101. {
  102. if (!string.IsNullOrEmpty(cacheKey))
  103. {
  104. if (_modelCache.TryGetValue(cacheKey, out DiscoverResponse response))
  105. {
  106. return response;
  107. }
  108. }
  109. }
  110. try
  111. {
  112. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  113. .GetAsync(GetApiUrl(info) + "/discover.json", HttpCompletionOption.ResponseHeadersRead, cancellationToken)
  114. .ConfigureAwait(false);
  115. response.EnsureSuccessStatusCode();
  116. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  117. var discoverResponse = await JsonSerializer.DeserializeAsync<DiscoverResponse>(stream, _jsonOptions, cancellationToken)
  118. .ConfigureAwait(false);
  119. if (!string.IsNullOrEmpty(cacheKey))
  120. {
  121. lock (_modelCache)
  122. {
  123. _modelCache[cacheKey] = discoverResponse;
  124. }
  125. }
  126. return discoverResponse;
  127. }
  128. catch (HttpRequestException ex)
  129. {
  130. if (!throwAllExceptions && ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  131. {
  132. const string DefaultValue = "HDHR";
  133. var response = new DiscoverResponse
  134. {
  135. ModelNumber = DefaultValue
  136. };
  137. if (!string.IsNullOrEmpty(cacheKey))
  138. {
  139. // HDHR4 doesn't have this api
  140. lock (_modelCache)
  141. {
  142. _modelCache[cacheKey] = response;
  143. }
  144. }
  145. return response;
  146. }
  147. throw;
  148. }
  149. }
  150. private async Task<List<LiveTvTunerInfo>> GetTunerInfosHttp(TunerHostInfo info, CancellationToken cancellationToken)
  151. {
  152. var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  153. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  154. .GetAsync(string.Format(CultureInfo.InvariantCulture, "{0}/tuners.html", GetApiUrl(info)), HttpCompletionOption.ResponseHeadersRead, cancellationToken)
  155. .ConfigureAwait(false);
  156. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  157. using var sr = new StreamReader(stream, System.Text.Encoding.UTF8);
  158. var tuners = new List<LiveTvTunerInfo>();
  159. while (!sr.EndOfStream)
  160. {
  161. string line = StripXML(sr.ReadLine());
  162. if (line.Contains("Channel", StringComparison.Ordinal))
  163. {
  164. LiveTvTunerStatus status;
  165. var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase);
  166. var name = line.Substring(0, index - 1);
  167. var currentChannel = line.Substring(index + 7);
  168. if (currentChannel != "none")
  169. {
  170. status = LiveTvTunerStatus.LiveTv;
  171. }
  172. else
  173. {
  174. status = LiveTvTunerStatus.Available;
  175. }
  176. tuners.Add(new LiveTvTunerInfo
  177. {
  178. Name = name,
  179. SourceType = string.IsNullOrWhiteSpace(model.ModelNumber) ? Name : model.ModelNumber,
  180. ProgramName = currentChannel,
  181. Status = status
  182. });
  183. }
  184. }
  185. return tuners;
  186. }
  187. private static string StripXML(string source)
  188. {
  189. if (string.IsNullOrEmpty(source))
  190. {
  191. return string.Empty;
  192. }
  193. char[] buffer = new char[source.Length];
  194. int bufferIndex = 0;
  195. bool inside = false;
  196. for (int i = 0; i < source.Length; i++)
  197. {
  198. char let = source[i];
  199. if (let == '<')
  200. {
  201. inside = true;
  202. continue;
  203. }
  204. if (let == '>')
  205. {
  206. inside = false;
  207. continue;
  208. }
  209. if (!inside)
  210. {
  211. buffer[bufferIndex++] = let;
  212. }
  213. }
  214. return new string(buffer, 0, bufferIndex);
  215. }
  216. private async Task<List<LiveTvTunerInfo>> GetTunerInfosUdp(TunerHostInfo info, CancellationToken cancellationToken)
  217. {
  218. var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  219. var tuners = new List<LiveTvTunerInfo>();
  220. var uri = new Uri(GetApiUrl(info));
  221. using (var manager = new HdHomerunManager())
  222. {
  223. // Legacy HdHomeruns are IPv4 only
  224. var ipInfo = IPAddress.Parse(uri.Host);
  225. for (int i = 0; i < model.TunerCount; ++i)
  226. {
  227. var name = string.Format(CultureInfo.InvariantCulture, "Tuner {0}", i + 1);
  228. var currentChannel = "none"; // @todo Get current channel and map back to Station Id
  229. var isAvailable = await manager.CheckTunerAvailability(ipInfo, i, cancellationToken).ConfigureAwait(false);
  230. var status = isAvailable ? LiveTvTunerStatus.Available : LiveTvTunerStatus.LiveTv;
  231. tuners.Add(new LiveTvTunerInfo
  232. {
  233. Name = name,
  234. SourceType = string.IsNullOrWhiteSpace(model.ModelNumber) ? Name : model.ModelNumber,
  235. ProgramName = currentChannel,
  236. Status = status
  237. });
  238. }
  239. }
  240. return tuners;
  241. }
  242. public async Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken)
  243. {
  244. var list = new List<LiveTvTunerInfo>();
  245. foreach (var host in GetConfiguration().TunerHosts
  246. .Where(i => string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase)))
  247. {
  248. try
  249. {
  250. list.AddRange(await GetTunerInfos(host, cancellationToken).ConfigureAwait(false));
  251. }
  252. catch (Exception ex)
  253. {
  254. Logger.LogError(ex, "Error getting tuner info");
  255. }
  256. }
  257. return list;
  258. }
  259. public async Task<List<LiveTvTunerInfo>> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken)
  260. {
  261. // TODO Need faster way to determine UDP vs HTTP
  262. var channels = await GetChannels(info, true, cancellationToken).ConfigureAwait(false);
  263. var hdHomerunChannelInfo = channels.FirstOrDefault() as HdHomerunChannelInfo;
  264. if (hdHomerunChannelInfo == null || hdHomerunChannelInfo.IsLegacyTuner)
  265. {
  266. return await GetTunerInfosUdp(info, cancellationToken).ConfigureAwait(false);
  267. }
  268. return await GetTunerInfosHttp(info, cancellationToken).ConfigureAwait(false);
  269. }
  270. private static string GetApiUrl(TunerHostInfo info)
  271. {
  272. var url = info.Url;
  273. if (string.IsNullOrWhiteSpace(url))
  274. {
  275. throw new ArgumentException("Invalid tuner info");
  276. }
  277. if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  278. {
  279. url = "http://" + url;
  280. }
  281. return new Uri(url).AbsoluteUri.TrimEnd('/');
  282. }
  283. private static string GetHdHrIdFromChannelId(string channelId)
  284. {
  285. return channelId.Split('_')[1];
  286. }
  287. private MediaSourceInfo GetMediaSource(TunerHostInfo info, string channelId, ChannelInfo channelInfo, string profile)
  288. {
  289. int? width = null;
  290. int? height = null;
  291. bool isInterlaced = true;
  292. string videoCodec = null;
  293. int? videoBitrate = null;
  294. var isHd = channelInfo.IsHD ?? true;
  295. if (string.Equals(profile, "mobile", StringComparison.OrdinalIgnoreCase))
  296. {
  297. width = 1280;
  298. height = 720;
  299. isInterlaced = false;
  300. videoCodec = "h264";
  301. videoBitrate = 2000000;
  302. }
  303. else if (string.Equals(profile, "heavy", StringComparison.OrdinalIgnoreCase))
  304. {
  305. width = 1920;
  306. height = 1080;
  307. isInterlaced = false;
  308. videoCodec = "h264";
  309. videoBitrate = 15000000;
  310. }
  311. else if (string.Equals(profile, "internet720", StringComparison.OrdinalIgnoreCase))
  312. {
  313. width = 1280;
  314. height = 720;
  315. isInterlaced = false;
  316. videoCodec = "h264";
  317. videoBitrate = 8000000;
  318. }
  319. else if (string.Equals(profile, "internet540", StringComparison.OrdinalIgnoreCase))
  320. {
  321. width = 960;
  322. height = 540;
  323. isInterlaced = false;
  324. videoCodec = "h264";
  325. videoBitrate = 2500000;
  326. }
  327. else if (string.Equals(profile, "internet480", StringComparison.OrdinalIgnoreCase))
  328. {
  329. width = 848;
  330. height = 480;
  331. isInterlaced = false;
  332. videoCodec = "h264";
  333. videoBitrate = 2000000;
  334. }
  335. else if (string.Equals(profile, "internet360", StringComparison.OrdinalIgnoreCase))
  336. {
  337. width = 640;
  338. height = 360;
  339. isInterlaced = false;
  340. videoCodec = "h264";
  341. videoBitrate = 1500000;
  342. }
  343. else if (string.Equals(profile, "internet240", StringComparison.OrdinalIgnoreCase))
  344. {
  345. width = 432;
  346. height = 240;
  347. isInterlaced = false;
  348. videoCodec = "h264";
  349. videoBitrate = 1000000;
  350. }
  351. else
  352. {
  353. // This is for android tv's 1200 condition. Remove once not needed anymore so that we can avoid possible side effects of dummying up this data
  354. if (isHd)
  355. {
  356. width = 1920;
  357. height = 1080;
  358. }
  359. }
  360. if (string.IsNullOrWhiteSpace(videoCodec))
  361. {
  362. videoCodec = channelInfo.VideoCodec;
  363. }
  364. string audioCodec = channelInfo.AudioCodec;
  365. videoBitrate ??= isHd ? 15000000 : 2000000;
  366. int? audioBitrate = isHd ? 448000 : 192000;
  367. // normalize
  368. if (string.Equals(videoCodec, "mpeg2", StringComparison.OrdinalIgnoreCase))
  369. {
  370. videoCodec = "mpeg2video";
  371. }
  372. string nal = null;
  373. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  374. {
  375. nal = "0";
  376. }
  377. var url = GetApiUrl(info);
  378. var id = profile;
  379. if (string.IsNullOrWhiteSpace(id))
  380. {
  381. id = "native";
  382. }
  383. id += "_" + channelId.GetMD5().ToString("N", CultureInfo.InvariantCulture) + "_" + url.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  384. var mediaSource = new MediaSourceInfo
  385. {
  386. Path = url,
  387. Protocol = MediaProtocol.Udp,
  388. MediaStreams = new List<MediaStream>
  389. {
  390. new MediaStream
  391. {
  392. Type = MediaStreamType.Video,
  393. // Set the index to -1 because we don't know the exact index of the video stream within the container
  394. Index = -1,
  395. IsInterlaced = isInterlaced,
  396. Codec = videoCodec,
  397. Width = width,
  398. Height = height,
  399. BitRate = videoBitrate,
  400. NalLengthSize = nal
  401. },
  402. new MediaStream
  403. {
  404. Type = MediaStreamType.Audio,
  405. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  406. Index = -1,
  407. Codec = audioCodec,
  408. BitRate = audioBitrate
  409. }
  410. },
  411. RequiresOpening = true,
  412. RequiresClosing = true,
  413. BufferMs = 0,
  414. Container = "ts",
  415. Id = id,
  416. SupportsDirectPlay = false,
  417. SupportsDirectStream = true,
  418. SupportsTranscoding = true,
  419. IsInfiniteStream = true,
  420. IgnoreDts = true,
  421. // IgnoreIndex = true,
  422. // ReadAtNativeFramerate = true
  423. };
  424. mediaSource.InferTotalBitrate();
  425. return mediaSource;
  426. }
  427. protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, ChannelInfo channelInfo, CancellationToken cancellationToken)
  428. {
  429. var list = new List<MediaSourceInfo>();
  430. var channelId = channelInfo.Id;
  431. var hdhrId = GetHdHrIdFromChannelId(channelId);
  432. var hdHomerunChannelInfo = channelInfo as HdHomerunChannelInfo;
  433. var isLegacyTuner = hdHomerunChannelInfo != null && hdHomerunChannelInfo.IsLegacyTuner;
  434. if (isLegacyTuner)
  435. {
  436. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  437. }
  438. else
  439. {
  440. var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  441. if (modelInfo != null && modelInfo.SupportsTranscoding)
  442. {
  443. if (info.AllowHWTranscoding)
  444. {
  445. list.Add(GetMediaSource(info, hdhrId, channelInfo, "heavy"));
  446. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet540"));
  447. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet480"));
  448. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet360"));
  449. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet240"));
  450. list.Add(GetMediaSource(info, hdhrId, channelInfo, "mobile"));
  451. }
  452. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  453. }
  454. if (list.Count == 0)
  455. {
  456. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  457. }
  458. }
  459. return list;
  460. }
  461. protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  462. {
  463. var tunerCount = info.TunerCount;
  464. if (tunerCount > 0)
  465. {
  466. var tunerHostId = info.Id;
  467. var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase));
  468. if (liveStreams.Count() >= tunerCount)
  469. {
  470. throw new LiveTvConflictException("HDHomeRun simultaneous stream limit has been reached.");
  471. }
  472. }
  473. var profile = streamId.Split('_')[0];
  474. Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile);
  475. var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id);
  476. var hdhomerunChannel = channelInfo as HdHomerunChannelInfo;
  477. var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  478. if (!modelInfo.SupportsTranscoding)
  479. {
  480. profile = "native";
  481. }
  482. var mediaSource = GetMediaSource(info, hdhrId, channelInfo, profile);
  483. if (hdhomerunChannel != null && hdhomerunChannel.IsLegacyTuner)
  484. {
  485. return new HdHomerunUdpStream(
  486. mediaSource,
  487. info,
  488. streamId,
  489. new LegacyHdHomerunChannelCommands(hdhomerunChannel.Path),
  490. modelInfo.TunerCount,
  491. FileSystem,
  492. Logger,
  493. Config,
  494. _appHost,
  495. _networkManager,
  496. _streamHelper);
  497. }
  498. var enableHttpStream = true;
  499. if (enableHttpStream)
  500. {
  501. mediaSource.Protocol = MediaProtocol.Http;
  502. var httpUrl = channelInfo.Path;
  503. // If raw was used, the tuner doesn't support params
  504. if (!string.IsNullOrWhiteSpace(profile) && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase))
  505. {
  506. httpUrl += "?transcode=" + profile;
  507. }
  508. mediaSource.Path = httpUrl;
  509. return new SharedHttpStream(
  510. mediaSource,
  511. info,
  512. streamId,
  513. FileSystem,
  514. _httpClientFactory,
  515. Logger,
  516. Config,
  517. _appHost,
  518. _streamHelper);
  519. }
  520. return new HdHomerunUdpStream(
  521. mediaSource,
  522. info,
  523. streamId,
  524. new HdHomerunChannelCommands(hdhomerunChannel.Number, profile),
  525. modelInfo.TunerCount,
  526. FileSystem,
  527. Logger,
  528. Config,
  529. _appHost,
  530. _networkManager,
  531. _streamHelper);
  532. }
  533. public async Task Validate(TunerHostInfo info)
  534. {
  535. lock (_modelCache)
  536. {
  537. _modelCache.Clear();
  538. }
  539. try
  540. {
  541. // Test it by pulling down the lineup
  542. var modelInfo = await GetModelInfo(info, true, CancellationToken.None).ConfigureAwait(false);
  543. info.DeviceId = modelInfo.DeviceID;
  544. }
  545. catch (HttpRequestException ex)
  546. {
  547. if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
  548. {
  549. // HDHR4 doesn't have this api
  550. return;
  551. }
  552. throw;
  553. }
  554. }
  555. public async Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken)
  556. {
  557. lock (_modelCache)
  558. {
  559. _modelCache.Clear();
  560. }
  561. using var timedCancellationToken = new CancellationTokenSource(discoveryDurationMs);
  562. using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(timedCancellationToken.Token, cancellationToken);
  563. cancellationToken = linkedCancellationTokenSource.Token;
  564. var list = new List<TunerHostInfo>();
  565. // Create udp broadcast discovery message
  566. byte[] discBytes = { 0, 2, 0, 12, 1, 4, 255, 255, 255, 255, 2, 4, 255, 255, 255, 255, 115, 204, 125, 143 };
  567. using (var udpClient = _socketFactory.CreateUdpBroadcastSocket(0))
  568. {
  569. // Need a way to set the Receive timeout on the socket otherwise this might never timeout?
  570. try
  571. {
  572. await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false);
  573. var receiveBuffer = new byte[8192];
  574. while (!cancellationToken.IsCancellationRequested)
  575. {
  576. var response = await udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
  577. var deviceIp = response.RemoteEndPoint.Address.ToString();
  578. // check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte
  579. if (response.ReceivedBytes > 13 && response.Buffer[1] == 3)
  580. {
  581. var deviceAddress = "http://" + deviceIp;
  582. var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false);
  583. if (info != null)
  584. {
  585. list.Add(info);
  586. }
  587. }
  588. }
  589. }
  590. catch (OperationCanceledException)
  591. {
  592. }
  593. catch (Exception ex)
  594. {
  595. // Socket timeout indicates all messages have been received.
  596. Logger.LogError(ex, "Error while sending discovery message");
  597. }
  598. }
  599. return list;
  600. }
  601. internal async Task<TunerHostInfo> TryGetTunerHostInfo(string url, CancellationToken cancellationToken)
  602. {
  603. var hostInfo = new TunerHostInfo
  604. {
  605. Type = Type,
  606. Url = url
  607. };
  608. var modelInfo = await GetModelInfo(hostInfo, false, cancellationToken).ConfigureAwait(false);
  609. hostInfo.DeviceId = modelInfo.DeviceID;
  610. hostInfo.FriendlyName = modelInfo.FriendlyName;
  611. hostInfo.TunerCount = modelInfo.TunerCount;
  612. return hostInfo;
  613. }
  614. }
  615. }