HdHomerunHost.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using MediaBrowser.Common.Extensions;
  18. using MediaBrowser.Controller.MediaEncoding;
  19. using MediaBrowser.Model.Configuration;
  20. using MediaBrowser.Model.Net;
  21. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  22. {
  23. public class HdHomerunHost : BaseTunerHost, ITunerHost, IConfigurableTunerHost
  24. {
  25. private readonly IHttpClient _httpClient;
  26. public HdHomerunHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder, IHttpClient httpClient)
  27. : base(config, logger, jsonSerializer, mediaEncoder)
  28. {
  29. _httpClient = httpClient;
  30. }
  31. public string Name
  32. {
  33. get { return "HD Homerun"; }
  34. }
  35. public override string Type
  36. {
  37. get { return DeviceType; }
  38. }
  39. public static string DeviceType
  40. {
  41. get { return "hdhomerun"; }
  42. }
  43. private const string ChannelIdPrefix = "hdhr_";
  44. private string GetChannelId(TunerHostInfo info, Channels i)
  45. {
  46. var id = ChannelIdPrefix + i.GuideNumber.ToString(CultureInfo.InvariantCulture);
  47. if (info.DataVersion >= 1)
  48. {
  49. id += '_' + (i.GuideName ?? string.Empty).GetMD5().ToString("N");
  50. }
  51. return id;
  52. }
  53. public string ApplyDuration(string streamPath, TimeSpan duration)
  54. {
  55. streamPath += streamPath.IndexOf('?') == -1 ? "?" : "&";
  56. streamPath += "duration=" + Convert.ToInt32(duration.TotalSeconds).ToString(CultureInfo.InvariantCulture);
  57. return streamPath;
  58. }
  59. private async Task<IEnumerable<Channels>> GetLineup(TunerHostInfo info, CancellationToken cancellationToken)
  60. {
  61. var options = new HttpRequestOptions
  62. {
  63. Url = string.Format("{0}/lineup.json", GetApiUrl(info, false)),
  64. CancellationToken = cancellationToken
  65. };
  66. using (var stream = await _httpClient.Get(options))
  67. {
  68. var lineup = JsonSerializer.DeserializeFromStream<List<Channels>>(stream) ?? new List<Channels>();
  69. if (info.ImportFavoritesOnly)
  70. {
  71. lineup = lineup.Where(i => i.Favorite).ToList();
  72. }
  73. return lineup.Where(i => !i.DRM).ToList();
  74. }
  75. }
  76. protected override async Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken)
  77. {
  78. var lineup = await GetLineup(info, cancellationToken).ConfigureAwait(false);
  79. return lineup.Select(i => new ChannelInfo
  80. {
  81. Name = i.GuideName,
  82. Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture),
  83. Id = GetChannelId(info, i),
  84. IsFavorite = i.Favorite,
  85. TunerHostId = info.Id,
  86. IsHD = i.HD == 1,
  87. AudioCodec = i.AudioCodec,
  88. VideoCodec = i.VideoCodec
  89. });
  90. }
  91. private async Task<string> GetModelInfo(TunerHostInfo info, CancellationToken cancellationToken)
  92. {
  93. try
  94. {
  95. using (var stream = await _httpClient.Get(new HttpRequestOptions()
  96. {
  97. Url = string.Format("{0}/discover.json", GetApiUrl(info, false)),
  98. CancellationToken = cancellationToken,
  99. CacheLength = TimeSpan.FromDays(1),
  100. CacheMode = CacheMode.Unconditional,
  101. TimeoutMs = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds)
  102. }))
  103. {
  104. var response = JsonSerializer.DeserializeFromStream<DiscoverResponse>(stream);
  105. return response.ModelNumber;
  106. }
  107. }
  108. catch (HttpException ex)
  109. {
  110. if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
  111. {
  112. // HDHR4 doesn't have this api
  113. return "HDHR";
  114. }
  115. throw;
  116. }
  117. }
  118. public async Task<List<LiveTvTunerInfo>> GetTunerInfos(TunerHostInfo info, CancellationToken cancellationToken)
  119. {
  120. var model = await GetModelInfo(info, cancellationToken).ConfigureAwait(false);
  121. using (var stream = await _httpClient.Get(new HttpRequestOptions()
  122. {
  123. Url = string.Format("{0}/tuners.html", GetApiUrl(info, false)),
  124. CancellationToken = cancellationToken,
  125. TimeoutMs = Convert.ToInt32(TimeSpan.FromSeconds(5).TotalMilliseconds)
  126. }))
  127. {
  128. var tuners = new List<LiveTvTunerInfo>();
  129. using (var sr = new StreamReader(stream, System.Text.Encoding.UTF8))
  130. {
  131. while (!sr.EndOfStream)
  132. {
  133. string line = StripXML(sr.ReadLine());
  134. if (line.Contains("Channel"))
  135. {
  136. LiveTvTunerStatus status;
  137. var index = line.IndexOf("Channel", StringComparison.OrdinalIgnoreCase);
  138. var name = line.Substring(0, index - 1);
  139. var currentChannel = line.Substring(index + 7);
  140. if (currentChannel != "none") { status = LiveTvTunerStatus.LiveTv; } else { status = LiveTvTunerStatus.Available; }
  141. tuners.Add(new LiveTvTunerInfo
  142. {
  143. Name = name,
  144. SourceType = string.IsNullOrWhiteSpace(model) ? Name : model,
  145. ProgramName = currentChannel,
  146. Status = status
  147. });
  148. }
  149. }
  150. }
  151. return tuners;
  152. }
  153. }
  154. public async Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken)
  155. {
  156. var list = new List<LiveTvTunerInfo>();
  157. foreach (var host in GetConfiguration().TunerHosts
  158. .Where(i => i.IsEnabled && string.Equals(i.Type, Type, StringComparison.OrdinalIgnoreCase)))
  159. {
  160. try
  161. {
  162. list.AddRange(await GetTunerInfos(host, cancellationToken).ConfigureAwait(false));
  163. }
  164. catch (Exception ex)
  165. {
  166. Logger.ErrorException("Error getting tuner info", ex);
  167. }
  168. }
  169. return list;
  170. }
  171. private string GetApiUrl(TunerHostInfo info, bool isPlayback)
  172. {
  173. var url = info.Url;
  174. if (string.IsNullOrWhiteSpace(url))
  175. {
  176. throw new ArgumentException("Invalid tuner info");
  177. }
  178. if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  179. {
  180. url = "http://" + url;
  181. }
  182. var uri = new Uri(url);
  183. if (isPlayback)
  184. {
  185. var builder = new UriBuilder(uri);
  186. builder.Port = 5004;
  187. uri = builder.Uri;
  188. }
  189. return uri.AbsoluteUri.TrimEnd('/');
  190. }
  191. private static string StripXML(string source)
  192. {
  193. char[] buffer = new char[source.Length];
  194. int bufferIndex = 0;
  195. bool inside = false;
  196. for (int i = 0; i < source.Length; i++)
  197. {
  198. char let = source[i];
  199. if (let == '<')
  200. {
  201. inside = true;
  202. continue;
  203. }
  204. if (let == '>')
  205. {
  206. inside = false;
  207. continue;
  208. }
  209. if (!inside)
  210. {
  211. buffer[bufferIndex] = let;
  212. bufferIndex++;
  213. }
  214. }
  215. return new string(buffer, 0, bufferIndex);
  216. }
  217. private class Channels
  218. {
  219. public string GuideNumber { get; set; }
  220. public string GuideName { get; set; }
  221. public string VideoCodec { get; set; }
  222. public string AudioCodec { get; set; }
  223. public string URL { get; set; }
  224. public bool Favorite { get; set; }
  225. public bool DRM { get; set; }
  226. public int HD { get; set; }
  227. }
  228. private async Task<MediaSourceInfo> GetMediaSource(TunerHostInfo info, string channelId, string profile)
  229. {
  230. int? width = null;
  231. int? height = null;
  232. bool isInterlaced = true;
  233. string videoCodec = null;
  234. string audioCodec = "ac3";
  235. int? videoBitrate = null;
  236. int? audioBitrate = null;
  237. if (string.Equals(profile, "mobile", StringComparison.OrdinalIgnoreCase))
  238. {
  239. width = 1280;
  240. height = 720;
  241. isInterlaced = false;
  242. videoCodec = "h264";
  243. videoBitrate = 2000000;
  244. }
  245. else if (string.Equals(profile, "heavy", StringComparison.OrdinalIgnoreCase))
  246. {
  247. width = 1920;
  248. height = 1080;
  249. isInterlaced = false;
  250. videoCodec = "h264";
  251. videoBitrate = 15000000;
  252. }
  253. else if (string.Equals(profile, "internet540", StringComparison.OrdinalIgnoreCase))
  254. {
  255. width = 960;
  256. height = 546;
  257. isInterlaced = false;
  258. videoCodec = "h264";
  259. videoBitrate = 2500000;
  260. }
  261. else if (string.Equals(profile, "internet480", StringComparison.OrdinalIgnoreCase))
  262. {
  263. width = 848;
  264. height = 480;
  265. isInterlaced = false;
  266. videoCodec = "h264";
  267. videoBitrate = 2000000;
  268. }
  269. else if (string.Equals(profile, "internet360", StringComparison.OrdinalIgnoreCase))
  270. {
  271. width = 640;
  272. height = 360;
  273. isInterlaced = false;
  274. videoCodec = "h264";
  275. videoBitrate = 1500000;
  276. }
  277. else if (string.Equals(profile, "internet240", StringComparison.OrdinalIgnoreCase))
  278. {
  279. width = 432;
  280. height = 240;
  281. isInterlaced = false;
  282. videoCodec = "h264";
  283. videoBitrate = 1000000;
  284. }
  285. if (string.IsNullOrWhiteSpace(videoCodec))
  286. {
  287. var channels = await GetChannels(info, true, CancellationToken.None).ConfigureAwait(false);
  288. var channel = channels.FirstOrDefault(i => string.Equals(i.Number, channelId, StringComparison.OrdinalIgnoreCase));
  289. if (channel != null)
  290. {
  291. videoCodec = channel.VideoCodec;
  292. audioCodec = channel.AudioCodec;
  293. videoBitrate = (channel.IsHD ?? true) ? 15000000 : 2000000;
  294. audioBitrate = (channel.IsHD ?? true) ? 448000 : 192000;
  295. }
  296. }
  297. // normalize
  298. if (string.Equals(videoCodec, "mpeg2", StringComparison.OrdinalIgnoreCase))
  299. {
  300. videoCodec = "mpeg2video";
  301. }
  302. string nal = null;
  303. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  304. {
  305. nal = "0";
  306. }
  307. var url = GetApiUrl(info, true) + "/auto/v" + channelId;
  308. if (!string.IsNullOrWhiteSpace(profile) && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase))
  309. {
  310. url += "?transcode=" + profile;
  311. }
  312. var mediaSource = new MediaSourceInfo
  313. {
  314. Path = url,
  315. Protocol = MediaProtocol.Http,
  316. MediaStreams = new List<MediaStream>
  317. {
  318. new MediaStream
  319. {
  320. Type = MediaStreamType.Video,
  321. // Set the index to -1 because we don't know the exact index of the video stream within the container
  322. Index = -1,
  323. IsInterlaced = isInterlaced,
  324. Codec = videoCodec,
  325. Width = width,
  326. Height = height,
  327. BitRate = videoBitrate,
  328. NalLengthSize = nal
  329. },
  330. new MediaStream
  331. {
  332. Type = MediaStreamType.Audio,
  333. // Set the index to -1 because we don't know the exact index of the audio stream within the container
  334. Index = -1,
  335. Codec = audioCodec,
  336. BitRate = audioBitrate
  337. }
  338. },
  339. RequiresOpening = false,
  340. RequiresClosing = false,
  341. BufferMs = 0,
  342. Container = "ts",
  343. Id = profile,
  344. SupportsDirectPlay = true,
  345. SupportsDirectStream = false,
  346. SupportsTranscoding = true
  347. };
  348. return mediaSource;
  349. }
  350. protected EncodingOptions GetEncodingOptions()
  351. {
  352. return Config.GetConfiguration<EncodingOptions>("encoding");
  353. }
  354. private string GetHdHrIdFromChannelId(string channelId)
  355. {
  356. return channelId.Split('_')[1];
  357. }
  358. protected override async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo info, string channelId, CancellationToken cancellationToken)
  359. {
  360. var list = new List<MediaSourceInfo>();
  361. if (!channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase))
  362. {
  363. return list;
  364. }
  365. var hdhrId = GetHdHrIdFromChannelId(channelId);
  366. list.Add(await GetMediaSource(info, hdhrId, "native").ConfigureAwait(false));
  367. try
  368. {
  369. string model = await GetModelInfo(info, cancellationToken).ConfigureAwait(false);
  370. model = model ?? string.Empty;
  371. if (info.AllowHWTranscoding && (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1))
  372. {
  373. list.Add(await GetMediaSource(info, hdhrId, "heavy").ConfigureAwait(false));
  374. list.Add(await GetMediaSource(info, hdhrId, "internet540").ConfigureAwait(false));
  375. list.Add(await GetMediaSource(info, hdhrId, "internet480").ConfigureAwait(false));
  376. list.Add(await GetMediaSource(info, hdhrId, "internet360").ConfigureAwait(false));
  377. list.Add(await GetMediaSource(info, hdhrId, "internet240").ConfigureAwait(false));
  378. list.Add(await GetMediaSource(info, hdhrId, "mobile").ConfigureAwait(false));
  379. }
  380. }
  381. catch (Exception ex)
  382. {
  383. }
  384. return list;
  385. }
  386. protected override bool IsValidChannelId(string channelId)
  387. {
  388. if (string.IsNullOrWhiteSpace(channelId))
  389. {
  390. throw new ArgumentNullException("channelId");
  391. }
  392. return channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase);
  393. }
  394. protected override async Task<MediaSourceInfo> GetChannelStream(TunerHostInfo info, string channelId, string streamId, CancellationToken cancellationToken)
  395. {
  396. Logger.Info("GetChannelStream: channel id: {0}. stream id: {1}", channelId, streamId ?? string.Empty);
  397. if (!channelId.StartsWith(ChannelIdPrefix, StringComparison.OrdinalIgnoreCase))
  398. {
  399. throw new ArgumentException("Channel not found");
  400. }
  401. var hdhrId = GetHdHrIdFromChannelId(channelId);
  402. return await GetMediaSource(info, hdhrId, streamId).ConfigureAwait(false);
  403. }
  404. public async Task Validate(TunerHostInfo info)
  405. {
  406. if (!info.IsEnabled)
  407. {
  408. return;
  409. }
  410. try
  411. {
  412. // Test it by pulling down the lineup
  413. using (var stream = await _httpClient.Get(new HttpRequestOptions
  414. {
  415. Url = string.Format("{0}/discover.json", GetApiUrl(info, false)),
  416. CancellationToken = CancellationToken.None
  417. }))
  418. {
  419. var response = JsonSerializer.DeserializeFromStream<DiscoverResponse>(stream);
  420. info.DeviceId = response.DeviceID;
  421. }
  422. }
  423. catch (HttpException ex)
  424. {
  425. if (ex.StatusCode.HasValue && ex.StatusCode.Value == System.Net.HttpStatusCode.NotFound)
  426. {
  427. // HDHR4 doesn't have this api
  428. return;
  429. }
  430. throw;
  431. }
  432. }
  433. protected override async Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken)
  434. {
  435. var info = await GetTunerInfos(tuner, cancellationToken).ConfigureAwait(false);
  436. return info.Any(i => i.Status == LiveTvTunerStatus.Available);
  437. }
  438. public class DiscoverResponse
  439. {
  440. public string FriendlyName { get; set; }
  441. public string ModelNumber { get; set; }
  442. public string FirmwareName { get; set; }
  443. public string FirmwareVersion { get; set; }
  444. public string DeviceID { get; set; }
  445. public string DeviceAuth { get; set; }
  446. public string BaseURL { get; set; }
  447. public string LineupURL { get; set; }
  448. }
  449. }
  450. }