HdHomerunHost.cs 16 KB

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