HdHomerunHost.cs 27 KB

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