HdHomerunManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Buffers;
  5. using System.Buffers.Binary;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using MediaBrowser.Common;
  15. using MediaBrowser.Controller.LiveTv;
  16. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  17. {
  18. public interface IHdHomerunChannelCommands
  19. {
  20. IEnumerable<(string, string)> GetCommands();
  21. }
  22. public class LegacyHdHomerunChannelCommands : IHdHomerunChannelCommands
  23. {
  24. private string _channel;
  25. private string _program;
  26. public LegacyHdHomerunChannelCommands(string url)
  27. {
  28. // parse url for channel and program
  29. var regExp = new Regex(@"\/ch([0-9]+)-?([0-9]*)");
  30. var match = regExp.Match(url);
  31. if (match.Success)
  32. {
  33. _channel = match.Groups[1].Value;
  34. _program = match.Groups[2].Value;
  35. }
  36. }
  37. public IEnumerable<(string, string)> GetCommands()
  38. {
  39. if (!string.IsNullOrEmpty(_channel))
  40. {
  41. yield return ("channel", _channel);
  42. }
  43. if (!string.IsNullOrEmpty(_program))
  44. {
  45. yield return ("program", _program);
  46. }
  47. }
  48. }
  49. public class HdHomerunChannelCommands : IHdHomerunChannelCommands
  50. {
  51. private string _channel;
  52. private string _profile;
  53. public HdHomerunChannelCommands(string channel, string profile)
  54. {
  55. _channel = channel;
  56. _profile = profile;
  57. }
  58. public IEnumerable<(string, string)> GetCommands()
  59. {
  60. if (!string.IsNullOrEmpty(_channel))
  61. {
  62. if (!string.IsNullOrEmpty(_profile)
  63. && !string.Equals(_profile, "native", StringComparison.OrdinalIgnoreCase))
  64. {
  65. yield return ("vchannel", $"{_channel} transcode={_profile}");
  66. }
  67. else
  68. {
  69. yield return ("vchannel", _channel);
  70. }
  71. }
  72. }
  73. }
  74. public sealed class HdHomerunManager : IDisposable
  75. {
  76. public const int HdHomeRunPort = 65001;
  77. // Message constants
  78. private const byte GetSetName = 3;
  79. private const byte GetSetValue = 4;
  80. private const byte GetSetLockkey = 21;
  81. private const ushort GetSetRequest = 4;
  82. private const ushort GetSetReply = 5;
  83. private uint? _lockkey = null;
  84. private int _activeTuner = -1;
  85. private IPEndPoint _remoteEndPoint;
  86. private TcpClient _tcpClient;
  87. public void Dispose()
  88. {
  89. using (var socket = _tcpClient)
  90. {
  91. if (socket != null)
  92. {
  93. _tcpClient = null;
  94. StopStreaming(socket).GetAwaiter().GetResult();
  95. }
  96. }
  97. GC.SuppressFinalize(this);
  98. }
  99. public async Task<bool> CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken)
  100. {
  101. using var client = new TcpClient();
  102. client.Connect(remoteIp, HdHomeRunPort);
  103. using var stream = client.GetStream();
  104. return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false);
  105. }
  106. private static async Task<bool> CheckTunerAvailability(NetworkStream stream, int tuner, CancellationToken cancellationToken)
  107. {
  108. byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
  109. try
  110. {
  111. var msgLen = WriteGetMessage(buffer, tuner, "lockkey");
  112. await stream.WriteAsync(buffer.AsMemory(0, msgLen), cancellationToken).ConfigureAwait(false);
  113. int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
  114. return VerifyReturnValueOfGetSet(buffer.AsSpan(receivedBytes), "none");
  115. }
  116. finally
  117. {
  118. ArrayPool<byte>.Shared.Return(buffer);
  119. }
  120. }
  121. public async Task StartStreaming(IPAddress remoteIp, IPAddress localIp, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken)
  122. {
  123. _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort);
  124. _tcpClient = new TcpClient();
  125. _tcpClient.Connect(_remoteEndPoint);
  126. if (!_lockkey.HasValue)
  127. {
  128. var rand = new Random();
  129. _lockkey = (uint)rand.Next();
  130. }
  131. var lockKeyValue = _lockkey.Value;
  132. var stream = _tcpClient.GetStream();
  133. byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
  134. try
  135. {
  136. for (int i = 0; i < numTuners; ++i)
  137. {
  138. if (!await CheckTunerAvailability(stream, i, cancellationToken).ConfigureAwait(false))
  139. {
  140. continue;
  141. }
  142. _activeTuner = i;
  143. var lockKeyString = string.Format(CultureInfo.InvariantCulture, "{0:d}", lockKeyValue);
  144. var lockkeyMsgLen = WriteSetMessage(buffer, i, "lockkey", lockKeyString, null);
  145. await stream.WriteAsync(buffer.AsMemory(0, lockkeyMsgLen), cancellationToken).ConfigureAwait(false);
  146. int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
  147. // parse response to make sure it worked
  148. if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
  149. {
  150. continue;
  151. }
  152. foreach (var command in commands.GetCommands())
  153. {
  154. var channelMsgLen = WriteSetMessage(buffer, i, command.Item1, command.Item2, lockKeyValue);
  155. await stream.WriteAsync(buffer.AsMemory(0, channelMsgLen), cancellationToken).ConfigureAwait(false);
  156. receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
  157. // parse response to make sure it worked
  158. if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
  159. {
  160. await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false);
  161. continue;
  162. }
  163. }
  164. var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIp, localPort);
  165. var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue);
  166. await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false);
  167. receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
  168. // parse response to make sure it worked
  169. if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
  170. {
  171. await ReleaseLockkey(_tcpClient, lockKeyValue).ConfigureAwait(false);
  172. continue;
  173. }
  174. return;
  175. }
  176. }
  177. finally
  178. {
  179. ArrayPool<byte>.Shared.Return(buffer);
  180. }
  181. _activeTuner = -1;
  182. throw new LiveTvConflictException();
  183. }
  184. public async Task ChangeChannel(IHdHomerunChannelCommands commands, CancellationToken cancellationToken)
  185. {
  186. if (!_lockkey.HasValue)
  187. {
  188. return;
  189. }
  190. using var tcpClient = new TcpClient();
  191. tcpClient.Connect(_remoteEndPoint);
  192. using var stream = tcpClient.GetStream();
  193. var commandList = commands.GetCommands();
  194. byte[] buffer = ArrayPool<byte>.Shared.Rent(8192);
  195. try
  196. {
  197. foreach (var command in commandList)
  198. {
  199. var channelMsgLen = WriteSetMessage(buffer, _activeTuner, command.Item1, command.Item2, _lockkey);
  200. await stream.WriteAsync(buffer.AsMemory(0, channelMsgLen), cancellationToken).ConfigureAwait(false);
  201. int receivedBytes = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
  202. // parse response to make sure it worked
  203. if (!TryGetReturnValueOfGetSet(buffer.AsSpan(0, receivedBytes), out _))
  204. {
  205. return;
  206. }
  207. }
  208. }
  209. finally
  210. {
  211. ArrayPool<byte>.Shared.Return(buffer);
  212. }
  213. }
  214. public Task StopStreaming(TcpClient client)
  215. {
  216. var lockKey = _lockkey;
  217. if (!lockKey.HasValue)
  218. {
  219. return Task.CompletedTask;
  220. }
  221. return ReleaseLockkey(client, lockKey.Value);
  222. }
  223. private async Task ReleaseLockkey(TcpClient client, uint lockKeyValue)
  224. {
  225. var stream = client.GetStream();
  226. var buffer = ArrayPool<byte>.Shared.Rent(8192);
  227. try
  228. {
  229. var releaseTargetLen = WriteSetMessage(buffer, _activeTuner, "target", "none", lockKeyValue);
  230. await stream.WriteAsync(buffer.AsMemory(0, releaseTargetLen)).ConfigureAwait(false);
  231. await stream.ReadAsync(buffer).ConfigureAwait(false);
  232. var releaseKeyMsgLen = WriteSetMessage(buffer, _activeTuner, "lockkey", "none", lockKeyValue);
  233. _lockkey = null;
  234. await stream.WriteAsync(buffer.AsMemory(0, releaseKeyMsgLen)).ConfigureAwait(false);
  235. await stream.ReadAsync(buffer).ConfigureAwait(false);
  236. }
  237. finally
  238. {
  239. ArrayPool<byte>.Shared.Return(buffer);
  240. }
  241. }
  242. internal static int WriteGetMessage(Span<byte> buffer, int tuner, string name)
  243. {
  244. var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name);
  245. int offset = WriteHeaderAndPayload(buffer, byteName);
  246. return FinishPacket(buffer, offset);
  247. }
  248. internal static int WriteSetMessage(Span<byte> buffer, int tuner, string name, string value, uint? lockkey)
  249. {
  250. var byteName = string.Format(CultureInfo.InvariantCulture, "/tuner{0}/{1}", tuner, name);
  251. int offset = WriteHeaderAndPayload(buffer, byteName);
  252. buffer[offset++] = GetSetValue;
  253. offset += WriteNullTerminatedString(buffer.Slice(offset), value);
  254. if (lockkey.HasValue)
  255. {
  256. buffer[offset++] = GetSetLockkey;
  257. buffer[offset++] = 4;
  258. BinaryPrimitives.WriteUInt32BigEndian(buffer.Slice(offset), lockkey.Value);
  259. offset += 4;
  260. }
  261. return FinishPacket(buffer, offset);
  262. }
  263. internal static int WriteNullTerminatedString(Span<byte> buffer, ReadOnlySpan<char> payload)
  264. {
  265. int len = Encoding.UTF8.GetBytes(payload, buffer.Slice(1)) + 1;
  266. // TODO: variable length: this can be 2 bytes if len > 127
  267. // Write length in front of value
  268. buffer[0] = Convert.ToByte(len);
  269. // null-terminate
  270. buffer[len++] = 0;
  271. return len;
  272. }
  273. private static int WriteHeaderAndPayload(Span<byte> buffer, ReadOnlySpan<char> payload)
  274. {
  275. // Packet type
  276. BinaryPrimitives.WriteUInt16BigEndian(buffer, GetSetRequest);
  277. // We write the payload length at the end
  278. int offset = 4;
  279. // Tag
  280. buffer[offset++] = GetSetName;
  281. // Payload length + data
  282. int strLen = WriteNullTerminatedString(buffer.Slice(offset), payload);
  283. offset += strLen;
  284. return offset;
  285. }
  286. private static int FinishPacket(Span<byte> buffer, int offset)
  287. {
  288. // Payload length
  289. BinaryPrimitives.WriteUInt16BigEndian(buffer.Slice(2), (ushort)(offset - 4));
  290. // calculate crc and insert at the end of the message
  291. var crc = Crc32.Compute(buffer.Slice(0, offset));
  292. BinaryPrimitives.WriteUInt32LittleEndian(buffer.Slice(offset), crc);
  293. return offset + 4;
  294. }
  295. internal static bool VerifyReturnValueOfGetSet(ReadOnlySpan<byte> buffer, string expected)
  296. {
  297. return TryGetReturnValueOfGetSet(buffer, out var value)
  298. && string.Equals(Encoding.UTF8.GetString(value), expected, StringComparison.OrdinalIgnoreCase);
  299. }
  300. internal static bool TryGetReturnValueOfGetSet(ReadOnlySpan<byte> buffer, out ReadOnlySpan<byte> value)
  301. {
  302. value = ReadOnlySpan<byte>.Empty;
  303. if (buffer.Length < 8)
  304. {
  305. return false;
  306. }
  307. uint crc = BinaryPrimitives.ReadUInt32LittleEndian(buffer[^4..]);
  308. if (crc != Crc32.Compute(buffer[..^4]))
  309. {
  310. return false;
  311. }
  312. if (BinaryPrimitives.ReadUInt16BigEndian(buffer) != GetSetReply)
  313. {
  314. return false;
  315. }
  316. var msgLength = BinaryPrimitives.ReadUInt16BigEndian(buffer.Slice(2));
  317. if (buffer.Length != 2 + 2 + 4 + msgLength)
  318. {
  319. return false;
  320. }
  321. var offset = 4;
  322. if (buffer[offset++] != GetSetName)
  323. {
  324. return false;
  325. }
  326. var nameLength = buffer[offset++];
  327. if (buffer.Length < 4 + 1 + offset + nameLength)
  328. {
  329. return false;
  330. }
  331. offset += nameLength;
  332. if (buffer[offset++] != GetSetValue)
  333. {
  334. return false;
  335. }
  336. var valueLength = buffer[offset++];
  337. if (buffer.Length < 4 + offset + valueLength)
  338. {
  339. return false;
  340. }
  341. // remove null terminator
  342. value = buffer.Slice(offset, valueLength - 1);
  343. return true;
  344. }
  345. }
  346. }