HdHomerunHost.cs 15 KB

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