HdHomerunHost.cs 28 KB

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