HdHomerunHost.cs 17 KB

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