HdHomerunHost.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. if (!videoBitrate.HasValue)
  366. {
  367. videoBitrate = isHd ? 15000000 : 2000000;
  368. }
  369. int? audioBitrate = isHd ? 448000 : 192000;
  370. // normalize
  371. if (string.Equals(videoCodec, "mpeg2", StringComparison.OrdinalIgnoreCase))
  372. {
  373. videoCodec = "mpeg2video";
  374. }
  375. string nal = null;
  376. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  377. {
  378. nal = "0";
  379. }
  380. var url = GetApiUrl(info);
  381. var id = profile;
  382. if (string.IsNullOrWhiteSpace(id))
  383. {
  384. id = "native";
  385. }
  386. id += "_" + channelId.GetMD5().ToString("N", CultureInfo.InvariantCulture) + "_" + url.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  387. var mediaSource = new MediaSourceInfo
  388. {
  389. Path = url,
  390. Protocol = MediaProtocol.Udp,
  391. MediaStreams = new List<MediaStream>
  392. {
  393. new MediaStream
  394. {
  395. Type = MediaStreamType.Video,
  396. // Set the index to -1 because we don't know the exact index of the video stream within the container
  397. Index = -1,
  398. IsInterlaced = isInterlaced,
  399. Codec = videoCodec,
  400. Width = width,
  401. Height = height,
  402. BitRate = videoBitrate,
  403. NalLengthSize = nal
  404. },
  405. new MediaStream
  406. {
  407. Type = MediaStreamType.Audio,
  408. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  409. Index = -1,
  410. Codec = audioCodec,
  411. BitRate = audioBitrate
  412. }
  413. },
  414. RequiresOpening = true,
  415. RequiresClosing = true,
  416. BufferMs = 0,
  417. Container = "ts",
  418. Id = id,
  419. SupportsDirectPlay = false,
  420. SupportsDirectStream = true,
  421. SupportsTranscoding = true,
  422. IsInfiniteStream = true,
  423. IgnoreDts = true,
  424. // IgnoreIndex = true,
  425. // ReadAtNativeFramerate = true
  426. };
  427. mediaSource.InferTotalBitrate();
  428. return mediaSource;
  429. }
  430. protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, ChannelInfo channelInfo, CancellationToken cancellationToken)
  431. {
  432. var list = new List<MediaSourceInfo>();
  433. var channelId = channelInfo.Id;
  434. var hdhrId = GetHdHrIdFromChannelId(channelId);
  435. var hdHomerunChannelInfo = channelInfo as HdHomerunChannelInfo;
  436. var isLegacyTuner = hdHomerunChannelInfo != null && hdHomerunChannelInfo.IsLegacyTuner;
  437. if (isLegacyTuner)
  438. {
  439. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  440. }
  441. else
  442. {
  443. var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  444. if (modelInfo != null && modelInfo.SupportsTranscoding)
  445. {
  446. if (info.AllowHWTranscoding)
  447. {
  448. list.Add(GetMediaSource(info, hdhrId, channelInfo, "heavy"));
  449. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet540"));
  450. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet480"));
  451. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet360"));
  452. list.Add(GetMediaSource(info, hdhrId, channelInfo, "internet240"));
  453. list.Add(GetMediaSource(info, hdhrId, channelInfo, "mobile"));
  454. }
  455. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  456. }
  457. if (list.Count == 0)
  458. {
  459. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  460. }
  461. }
  462. return list;
  463. }
  464. protected override async Task<ILiveStream> GetChannelStream(TunerHostInfo info, ChannelInfo channelInfo, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  465. {
  466. var tunerCount = info.TunerCount;
  467. if (tunerCount > 0)
  468. {
  469. var tunerHostId = info.Id;
  470. var liveStreams = currentLiveStreams.Where(i => string.Equals(i.TunerHostId, tunerHostId, StringComparison.OrdinalIgnoreCase));
  471. if (liveStreams.Count() >= tunerCount)
  472. {
  473. throw new LiveTvConflictException("HDHomeRun simultaneous stream limit has been reached.");
  474. }
  475. }
  476. var profile = streamId.Split('_')[0];
  477. Logger.LogInformation("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelInfo.Id, streamId, profile);
  478. var hdhrId = GetHdHrIdFromChannelId(channelInfo.Id);
  479. var hdhomerunChannel = channelInfo as HdHomerunChannelInfo;
  480. var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  481. if (!modelInfo.SupportsTranscoding)
  482. {
  483. profile = "native";
  484. }
  485. var mediaSource = GetMediaSource(info, hdhrId, channelInfo, profile);
  486. if (hdhomerunChannel != null && hdhomerunChannel.IsLegacyTuner)
  487. {
  488. return new HdHomerunUdpStream(
  489. mediaSource,
  490. info,
  491. streamId,
  492. new LegacyHdHomerunChannelCommands(hdhomerunChannel.Path),
  493. modelInfo.TunerCount,
  494. FileSystem,
  495. Logger,
  496. Config,
  497. _appHost,
  498. _networkManager,
  499. _streamHelper);
  500. }
  501. var enableHttpStream = true;
  502. if (enableHttpStream)
  503. {
  504. mediaSource.Protocol = MediaProtocol.Http;
  505. var httpUrl = channelInfo.Path;
  506. // If raw was used, the tuner doesn't support params
  507. if (!string.IsNullOrWhiteSpace(profile) && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase))
  508. {
  509. httpUrl += "?transcode=" + profile;
  510. }
  511. mediaSource.Path = httpUrl;
  512. return new SharedHttpStream(
  513. mediaSource,
  514. info,
  515. streamId,
  516. FileSystem,
  517. _httpClientFactory,
  518. Logger,
  519. Config,
  520. _appHost,
  521. _streamHelper);
  522. }
  523. return new HdHomerunUdpStream(
  524. mediaSource,
  525. info,
  526. streamId,
  527. new HdHomerunChannelCommands(hdhomerunChannel.Number, profile),
  528. modelInfo.TunerCount,
  529. FileSystem,
  530. Logger,
  531. Config,
  532. _appHost,
  533. _networkManager,
  534. _streamHelper);
  535. }
  536. public async Task Validate(TunerHostInfo info)
  537. {
  538. lock (_modelCache)
  539. {
  540. _modelCache.Clear();
  541. }
  542. try
  543. {
  544. // Test it by pulling down the lineup
  545. var modelInfo = await GetModelInfo(info, true, CancellationToken.None).ConfigureAwait(false);
  546. info.DeviceId = modelInfo.DeviceID;
  547. }
  548. catch (HttpRequestException ex)
  549. {
  550. if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
  551. {
  552. // HDHR4 doesn't have this api
  553. return;
  554. }
  555. throw;
  556. }
  557. }
  558. public async Task<List<TunerHostInfo>> DiscoverDevices(int discoveryDurationMs, CancellationToken cancellationToken)
  559. {
  560. lock (_modelCache)
  561. {
  562. _modelCache.Clear();
  563. }
  564. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(new CancellationTokenSource(discoveryDurationMs).Token, cancellationToken).Token;
  565. var list = new List<TunerHostInfo>();
  566. // Create udp broadcast discovery message
  567. byte[] discBytes = { 0, 2, 0, 12, 1, 4, 255, 255, 255, 255, 2, 4, 255, 255, 255, 255, 115, 204, 125, 143 };
  568. using (var udpClient = _socketFactory.CreateUdpBroadcastSocket(0))
  569. {
  570. // Need a way to set the Receive timeout on the socket otherwise this might never timeout?
  571. try
  572. {
  573. await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false);
  574. var receiveBuffer = new byte[8192];
  575. while (!cancellationToken.IsCancellationRequested)
  576. {
  577. var response = await udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
  578. var deviceIp = response.RemoteEndPoint.Address.ToString();
  579. // 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
  580. if (response.ReceivedBytes > 13 && response.Buffer[1] == 3)
  581. {
  582. var deviceAddress = "http://" + deviceIp;
  583. var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false);
  584. if (info != null)
  585. {
  586. list.Add(info);
  587. }
  588. }
  589. }
  590. }
  591. catch (OperationCanceledException)
  592. {
  593. }
  594. catch (Exception ex)
  595. {
  596. // Socket timeout indicates all messages have been received.
  597. Logger.LogError(ex, "Error while sending discovery message");
  598. }
  599. }
  600. return list;
  601. }
  602. internal async Task<TunerHostInfo> TryGetTunerHostInfo(string url, CancellationToken cancellationToken)
  603. {
  604. var hostInfo = new TunerHostInfo
  605. {
  606. Type = Type,
  607. Url = url
  608. };
  609. var modelInfo = await GetModelInfo(hostInfo, false, cancellationToken).ConfigureAwait(false);
  610. hostInfo.DeviceId = modelInfo.DeviceID;
  611. hostInfo.FriendlyName = modelInfo.FriendlyName;
  612. hostInfo.TunerCount = modelInfo.TunerCount;
  613. return hostInfo;
  614. }
  615. }
  616. }