HdHomerunHost.cs 15 KB

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