HdHomerunHost.cs 27 KB

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