HdHomerunHost.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.LiveTv;
  4. using MediaBrowser.Model.Dto;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.LiveTv;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Common.Extensions;
  18. using MediaBrowser.Controller;
  19. using MediaBrowser.Controller.Configuration;
  20. using MediaBrowser.Controller.MediaEncoding;
  21. using MediaBrowser.Model.Configuration;
  22. using MediaBrowser.Model.Net;
  23. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  24. {
  25. public class HdHomerunHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
  26. {
  27. private readonly IHttpClient _httpClient;
  28. private readonly IFileSystem _fileSystem;
  29. private readonly IServerApplicationHost _appHost;
  30. private readonly ISocketFactory _socketFactory;
  31. private readonly INetworkManager _networkManager;
  32. public HdHomerunHost(IServerConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IHttpClient httpClient, IFileSystem fileSystem, IServerApplicationHost appHost, ISocketFactory socketFactory, INetworkManager networkManager)
  33. : base(config, logger, jsonSerializer, mediaEncoder)
  34. {
  35. _httpClient = httpClient;
  36. _fileSystem = fileSystem;
  37. _appHost = appHost;
  38. _socketFactory = socketFactory;
  39. _networkManager = networkManager;
  40. }
  41. public string Name
  42. {
  43. get { return "HD Homerun"; }
  44. }
  45. public override string Type
  46. {
  47. get { return DeviceType; }
  48. }
  49. public static string DeviceType
  50. {
  51. get { return "hdhomerun"; }
  52. }
  53. private const string ChannelIdPrefix = "hdhr_";
  54. private string GetChannelId(TunerHostInfo info, Channels i)
  55. {
  56. var id = ChannelIdPrefix + i.GuideNumber;
  57. id += '_' + (i.GuideName ?? string.Empty).GetMD5().ToString("N");
  58. return id;
  59. }
  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 stream = await _httpClient.Get(options).ConfigureAwait(false))
  70. {
  71. var lineup = JsonSerializer.DeserializeFromStream<List<Channels>>(stream) ?? 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. public string Url { get; set; }
  83. }
  84. protected override async Task<List<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken)
  85. {
  86. var lineup = await GetLineup(info, cancellationToken).ConfigureAwait(false);
  87. return lineup.Select(i => new HdHomerunChannelInfo
  88. {
  89. Name = i.GuideName,
  90. Number = i.GuideNumber,
  91. Id = GetChannelId(info, i),
  92. IsFavorite = i.Favorite,
  93. TunerHostId = info.Id,
  94. IsHD = i.HD == 1,
  95. AudioCodec = i.AudioCodec,
  96. VideoCodec = i.VideoCodec,
  97. ChannelType = ChannelType.TV,
  98. IsLegacyTuner = (i.URL ?? string.Empty).StartsWith("hdhomerun", StringComparison.OrdinalIgnoreCase),
  99. Url = i.URL
  100. }).Cast<ChannelInfo>().ToList();
  101. }
  102. private readonly Dictionary<string, DiscoverResponse> _modelCache = new Dictionary<string, DiscoverResponse>();
  103. private async Task<DiscoverResponse> GetModelInfo(TunerHostInfo info, bool throwAllExceptions, CancellationToken cancellationToken)
  104. {
  105. lock (_modelCache)
  106. {
  107. DiscoverResponse response;
  108. if (_modelCache.TryGetValue(info.Url, out response))
  109. {
  110. return response;
  111. }
  112. }
  113. try
  114. {
  115. using (var stream = await _httpClient.Get(new HttpRequestOptions()
  116. {
  117. Url = string.Format("{0}/discover.json", GetApiUrl(info, false)),
  118. CancellationToken = cancellationToken,
  119. CacheLength = TimeSpan.FromDays(1),
  120. CacheMode = CacheMode.Unconditional,
  121. TimeoutMs = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds),
  122. BufferContent = false
  123. }).ConfigureAwait(false))
  124. {
  125. var response = JsonSerializer.DeserializeFromStream<DiscoverResponse>(stream);
  126. if (!string.IsNullOrWhiteSpace(info.Id))
  127. {
  128. lock (_modelCache)
  129. {
  130. _modelCache[info.Id] = response;
  131. }
  132. }
  133. return response;
  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.IsNullOrWhiteSpace(info.Id))
  146. {
  147. // HDHR4 doesn't have this api
  148. lock (_modelCache)
  149. {
  150. _modelCache[info.Id] = response;
  151. }
  152. }
  153. return response;
  154. }
  155. throw;
  156. }
  157. }
  158. private async Task<List<LiveTvTunerInfo>> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken)
  159. {
  160. var model = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  161. var tuners = new List<LiveTvTunerInfo>();
  162. var uri = new Uri(GetApiUrl(info, false));
  163. using (var manager = new HdHomerunManager(_socketFactory))
  164. {
  165. // Legacy HdHomeruns are IPv4 only
  166. var ipInfo = _networkManager.ParseIpAddress(uri.Host);
  167. for (int i = 0; i < model.TunerCount; ++i)
  168. {
  169. var name = String.Format("Tuner {0}", i + 1);
  170. var currentChannel = "none"; /// @todo Get current channel and map back to Station Id
  171. var isAvailable = await manager.CheckTunerAvailability(ipInfo, i, cancellationToken).ConfigureAwait(false);
  172. LiveTvTunerStatus status = isAvailable ? LiveTvTunerStatus.Available : LiveTvTunerStatus.LiveTv;
  173. tuners.Add(new LiveTvTunerInfo
  174. {
  175. Name = name,
  176. SourceType = string.IsNullOrWhiteSpace(model.ModelNumber) ? Name : model.ModelNumber,
  177. ProgramName = currentChannel,
  178. Status = status
  179. });
  180. }
  181. }
  182. return tuners;
  183. }
  184. public async Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken)
  185. {
  186. var list = new List<LiveTvTunerInfo>();
  187. foreach (var host in GetConfiguration().TunerHosts
  188. .Where(i => i.IsEnabled && string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase)))
  189. {
  190. try
  191. {
  192. list.AddRange(await GetTunerInfos(host, cancellationToken).ConfigureAwait(false));
  193. }
  194. catch (Exception ex)
  195. {
  196. Logger.ErrorException("Error getting tuner info", ex);
  197. }
  198. }
  199. return list;
  200. }
  201. private string GetApiUrl(TunerHostInfo info, bool isPlayback)
  202. {
  203. var url = info.Url;
  204. if (string.IsNullOrWhiteSpace(url))
  205. {
  206. throw new ArgumentException("Invalid tuner info");
  207. }
  208. if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  209. {
  210. url = "http://" + url;
  211. }
  212. var uri = new Uri(url);
  213. if (isPlayback)
  214. {
  215. var builder = new UriBuilder(uri);
  216. builder.Port = 5004;
  217. uri = builder.Uri;
  218. }
  219. return uri.AbsoluteUri.TrimEnd('/');
  220. }
  221. private class Channels
  222. {
  223. public string GuideNumber { get; set; }
  224. public string GuideName { get; set; }
  225. public string VideoCodec { get; set; }
  226. public string AudioCodec { get; set; }
  227. public string URL { get; set; }
  228. public bool Favorite { get; set; }
  229. public bool DRM { get; set; }
  230. public int HD { get; set; }
  231. }
  232. private MediaSourceInfo GetMediaSource(TunerHostInfo info, string channelId, ChannelInfo channelInfo, string profile)
  233. {
  234. int? width = null;
  235. int? height = null;
  236. bool isInterlaced = true;
  237. string videoCodec = null;
  238. string audioCodec = null;
  239. int? videoBitrate = null;
  240. int? audioBitrate = null;
  241. if (string.Equals(profile, "mobile", StringComparison.OrdinalIgnoreCase))
  242. {
  243. width = 1280;
  244. height = 720;
  245. isInterlaced = false;
  246. videoCodec = "h264";
  247. videoBitrate = 2000000;
  248. }
  249. else if (string.Equals(profile, "heavy", StringComparison.OrdinalIgnoreCase))
  250. {
  251. width = 1920;
  252. height = 1080;
  253. isInterlaced = false;
  254. videoCodec = "h264";
  255. videoBitrate = 15000000;
  256. }
  257. else if (string.Equals(profile, "internet540", StringComparison.OrdinalIgnoreCase))
  258. {
  259. width = 960;
  260. height = 546;
  261. isInterlaced = false;
  262. videoCodec = "h264";
  263. videoBitrate = 2500000;
  264. }
  265. else if (string.Equals(profile, "internet480", StringComparison.OrdinalIgnoreCase))
  266. {
  267. width = 848;
  268. height = 480;
  269. isInterlaced = false;
  270. videoCodec = "h264";
  271. videoBitrate = 2000000;
  272. }
  273. else if (string.Equals(profile, "internet360", StringComparison.OrdinalIgnoreCase))
  274. {
  275. width = 640;
  276. height = 360;
  277. isInterlaced = false;
  278. videoCodec = "h264";
  279. videoBitrate = 1500000;
  280. }
  281. else if (string.Equals(profile, "internet240", StringComparison.OrdinalIgnoreCase))
  282. {
  283. width = 432;
  284. height = 240;
  285. isInterlaced = false;
  286. videoCodec = "h264";
  287. videoBitrate = 1000000;
  288. }
  289. if (channelInfo != null)
  290. {
  291. if (string.IsNullOrWhiteSpace(videoCodec))
  292. {
  293. videoCodec = channelInfo.VideoCodec;
  294. }
  295. audioCodec = channelInfo.AudioCodec;
  296. if (!videoBitrate.HasValue)
  297. {
  298. videoBitrate = (channelInfo.IsHD ?? true) ? 15000000 : 2000000;
  299. }
  300. audioBitrate = (channelInfo.IsHD ?? true) ? 448000 : 192000;
  301. }
  302. // normalize
  303. if (string.Equals(videoCodec, "mpeg2", StringComparison.OrdinalIgnoreCase))
  304. {
  305. videoCodec = "mpeg2video";
  306. }
  307. string nal = null;
  308. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  309. {
  310. nal = "0";
  311. }
  312. var url = GetApiUrl(info, true) + "/auto/v" + channelId;
  313. // If raw was used, the tuner doesn't support params
  314. if (!string.IsNullOrWhiteSpace(profile)
  315. && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase))
  316. {
  317. url += "?transcode=" + profile;
  318. }
  319. var id = profile;
  320. if (string.IsNullOrWhiteSpace(id))
  321. {
  322. id = "native";
  323. }
  324. id += "_" + url.GetMD5().ToString("N");
  325. var mediaSource = new MediaSourceInfo
  326. {
  327. Path = url,
  328. Protocol = MediaProtocol.Http,
  329. MediaStreams = new List<MediaStream>
  330. {
  331. new MediaStream
  332. {
  333. Type = MediaStreamType.Video,
  334. // Set the index to -1 because we don't know the exact index of the video stream within the container
  335. Index = -1,
  336. IsInterlaced = isInterlaced,
  337. Codec = videoCodec,
  338. Width = width,
  339. Height = height,
  340. BitRate = videoBitrate,
  341. NalLengthSize = nal
  342. },
  343. new MediaStream
  344. {
  345. Type = MediaStreamType.Audio,
  346. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  347. Index = -1,
  348. Codec = audioCodec,
  349. BitRate = audioBitrate
  350. }
  351. },
  352. RequiresOpening = true,
  353. RequiresClosing = false,
  354. BufferMs = 0,
  355. Container = "ts",
  356. Id = id,
  357. SupportsDirectPlay = false,
  358. SupportsDirectStream = true,
  359. SupportsTranscoding = true,
  360. IsInfiniteStream = true
  361. };
  362. mediaSource.InferTotalBitrate();
  363. return mediaSource;
  364. }
  365. protected EncodingOptions GetEncodingOptions()
  366. {
  367. return Config.GetConfiguration<EncodingOptions>("encoding");
  368. }
  369. private string GetHdHrIdFromChannelId(string channelId)
  370. {
  371. return channelId.Split('_')[1];
  372. }
  373. private MediaSourceInfo GetLegacyMediaSource(TunerHostInfo info, string channelId, ChannelInfo channel)
  374. {
  375. int? width = null;
  376. int? height = null;
  377. bool isInterlaced = true;
  378. string videoCodec = null;
  379. string audioCodec = null;
  380. int? videoBitrate = null;
  381. int? audioBitrate = null;
  382. if (channel != null)
  383. {
  384. if (string.IsNullOrWhiteSpace(videoCodec))
  385. {
  386. videoCodec = channel.VideoCodec;
  387. }
  388. audioCodec = channel.AudioCodec;
  389. }
  390. // normalize
  391. if (string.Equals(videoCodec, "mpeg2", StringComparison.OrdinalIgnoreCase))
  392. {
  393. videoCodec = "mpeg2video";
  394. }
  395. string nal = null;
  396. var url = GetApiUrl(info, false);
  397. var id = channelId;
  398. id += "_" + url.GetMD5().ToString("N");
  399. var mediaSource = new MediaSourceInfo
  400. {
  401. Path = url,
  402. Protocol = MediaProtocol.Udp,
  403. MediaStreams = new List<MediaStream>
  404. {
  405. new MediaStream
  406. {
  407. Type = MediaStreamType.Video,
  408. // Set the index to -1 because we don't know the exact index of the video stream within the container
  409. Index = -1,
  410. IsInterlaced = isInterlaced,
  411. Codec = videoCodec,
  412. Width = width,
  413. Height = height,
  414. BitRate = videoBitrate,
  415. NalLengthSize = nal
  416. },
  417. new MediaStream
  418. {
  419. Type = MediaStreamType.Audio,
  420. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  421. Index = -1,
  422. Codec = audioCodec,
  423. BitRate = audioBitrate
  424. }
  425. },
  426. RequiresOpening = true,
  427. RequiresClosing = true,
  428. BufferMs = 0,
  429. Container = "ts",
  430. Id = id,
  431. SupportsDirectPlay = false,
  432. SupportsDirectStream = true,
  433. SupportsTranscoding = true,
  434. IsInfiniteStream = true
  435. };
  436. mediaSource.InferTotalBitrate();
  437. return mediaSource;
  438. }
  439. protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, string channelId, CancellationToken cancellationToken)
  440. {
  441. var list = new List<MediaSourceInfo>();
  442. if (!channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase))
  443. {
  444. return list;
  445. }
  446. var hdhrId = GetHdHrIdFromChannelId(channelId);
  447. var channels = await GetChannels(info, true, CancellationToken.None).ConfigureAwait(false);
  448. var channelInfo = channels.FirstOrDefault(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  449. var hdHomerunChannelInfo = channelInfo as HdHomerunChannelInfo;
  450. var isLegacyTuner = hdHomerunChannelInfo != null && hdHomerunChannelInfo.IsLegacyTuner;
  451. if (isLegacyTuner)
  452. {
  453. list.Add(GetLegacyMediaSource(info, hdhrId, channelInfo));
  454. }
  455. else
  456. {
  457. try
  458. {
  459. var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  460. var model = modelInfo == null ? string.Empty : (modelInfo.ModelNumber ?? string.Empty);
  461. if ((model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1))
  462. {
  463. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  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. }
  474. }
  475. catch
  476. {
  477. }
  478. if (list.Count == 0)
  479. {
  480. list.Add(GetMediaSource(info, hdhrId, channelInfo, "native"));
  481. }
  482. }
  483. return list;
  484. }
  485. protected override bool IsValidChannelId(string channelId)
  486. {
  487. if (string.IsNullOrWhiteSpace(channelId))
  488. {
  489. throw new ArgumentNullException("channelId");
  490. }
  491. return channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase);
  492. }
  493. protected override async Task<LiveStream> GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken)
  494. {
  495. var profile = streamId.Split('_')[0];
  496. Logger.Info("GetChannelStream: channel id: {0}. stream id: {1} profile: {2}", channelId, streamId, profile);
  497. if (!channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase))
  498. {
  499. throw new ArgumentException("Channel not found");
  500. }
  501. var hdhrId = GetHdHrIdFromChannelId(channelId);
  502. var channels = await GetChannels(info, true, CancellationToken.None).ConfigureAwait(false);
  503. var channelInfo = channels.FirstOrDefault(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  504. var hdhomerunChannel = channelInfo as HdHomerunChannelInfo;
  505. if (hdhomerunChannel != null && hdhomerunChannel.IsLegacyTuner)
  506. {
  507. var mediaSource = GetLegacyMediaSource(info, hdhrId, channelInfo);
  508. var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  509. return new HdHomerunUdpStream(mediaSource, streamId, new LegacyHdHomerunChannelCommands(hdhomerunChannel.Url), modelInfo.TunerCount, _fileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost, _socketFactory, _networkManager);
  510. }
  511. else
  512. {
  513. var mediaSource = GetMediaSource(info, hdhrId, channelInfo, profile);
  514. //var modelInfo = await GetModelInfo(info, false, cancellationToken).ConfigureAwait(false);
  515. return new HdHomerunHttpStream(mediaSource, streamId, _fileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost);
  516. //return new HdHomerunUdpStream(mediaSource, streamId, new HdHomerunChannelCommands(hdhomerunChannel.Number), modelInfo.TunerCount, _fileSystem, _httpClient, Logger, Config.ApplicationPaths, _appHost, _socketFactory, _networkManager);
  517. }
  518. }
  519. public async Task Validate(TunerHostInfo info)
  520. {
  521. if (!info.IsEnabled)
  522. {
  523. return;
  524. }
  525. lock (_modelCache)
  526. {
  527. _modelCache.Clear();
  528. }
  529. try
  530. {
  531. // Test it by pulling down the lineup
  532. var modelInfo = await GetModelInfo(info, true, CancellationToken.None).ConfigureAwait(false);
  533. info.DeviceId = modelInfo.DeviceID;
  534. }
  535. catch (HttpException ex)
  536. {
  537. if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
  538. {
  539. // HDHR4 doesn't have this api
  540. return;
  541. }
  542. throw;
  543. }
  544. }
  545. protected override async Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken)
  546. {
  547. var info = await GetTunerInfos(tuner, cancellationToken).ConfigureAwait(false);
  548. return info.Any(i => i.Status == LiveTvTunerStatus.Available);
  549. }
  550. public class DiscoverResponse
  551. {
  552. public string FriendlyName { get; set; }
  553. public string ModelNumber { get; set; }
  554. public string FirmwareName { get; set; }
  555. public string FirmwareVersion { get; set; }
  556. public string DeviceID { get; set; }
  557. public string DeviceAuth { get; set; }
  558. public string BaseURL { get; set; }
  559. public string LineupURL { get; set; }
  560. public int TunerCount { get; set; }
  561. }
  562. }
  563. }