HdHomerunUdpStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.LiveTv;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.MediaInfo;
  16. using MediaBrowser.Model.Net;
  17. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  18. {
  19. public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
  20. {
  21. private readonly ILogger _logger;
  22. private readonly IHttpClient _httpClient;
  23. private readonly IFileSystem _fileSystem;
  24. private readonly IServerApplicationPaths _appPaths;
  25. private readonly IServerApplicationHost _appHost;
  26. private readonly ISocketFactory _socketFactory;
  27. private readonly CancellationTokenSource _liveStreamCancellationTokenSource = new CancellationTokenSource();
  28. private readonly TaskCompletionSource<bool> _liveStreamTaskCompletionSource = new TaskCompletionSource<bool>();
  29. private readonly MulticastStream _multicastStream;
  30. private readonly IHdHomerunChannelCommands _channelCommands;
  31. private readonly int _numTuners;
  32. private readonly INetworkManager _networkManager;
  33. public HdHomerunUdpStream(MediaSourceInfo mediaSource, string originalStreamId, IHdHomerunChannelCommands channelCommands, int numTuners, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost, ISocketFactory socketFactory, INetworkManager networkManager)
  34. : base(mediaSource)
  35. {
  36. _fileSystem = fileSystem;
  37. _httpClient = httpClient;
  38. _logger = logger;
  39. _appPaths = appPaths;
  40. _appHost = appHost;
  41. _socketFactory = socketFactory;
  42. _networkManager = networkManager;
  43. OriginalStreamId = originalStreamId;
  44. _multicastStream = new MulticastStream(_logger);
  45. _channelCommands = channelCommands;
  46. _numTuners = numTuners;
  47. }
  48. protected override async Task OpenInternal(CancellationToken openCancellationToken)
  49. {
  50. _liveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  51. var mediaSource = OriginalMediaSource;
  52. var uri = new Uri(mediaSource.Path);
  53. var localPort = _networkManager.GetRandomUnusedUdpPort();
  54. _logger.Info("Opening HDHR UDP Live stream from {0}", uri.Host);
  55. var taskCompletionSource = new TaskCompletionSource<bool>();
  56. StartStreaming(uri.Host, localPort, taskCompletionSource, _liveStreamCancellationTokenSource.Token);
  57. //OpenedMediaSource.Protocol = MediaProtocol.File;
  58. //OpenedMediaSource.Path = tempFile;
  59. //OpenedMediaSource.ReadAtNativeFramerate = true;
  60. OpenedMediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  61. OpenedMediaSource.Protocol = MediaProtocol.Http;
  62. OpenedMediaSource.SupportsDirectPlay = false;
  63. OpenedMediaSource.SupportsDirectStream = true;
  64. OpenedMediaSource.SupportsTranscoding = true;
  65. await taskCompletionSource.Task.ConfigureAwait(false);
  66. //await Task.Delay(5000).ConfigureAwait(false);
  67. }
  68. public override Task Close()
  69. {
  70. _logger.Info("Closing HDHR UDP live stream");
  71. _liveStreamCancellationTokenSource.Cancel();
  72. return _liveStreamTaskCompletionSource.Task;
  73. }
  74. private async Task StartStreaming(string remoteIp, int localPort, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  75. {
  76. await Task.Run(async () =>
  77. {
  78. var isFirstAttempt = true;
  79. using (var udpClient = _socketFactory.CreateUdpSocket(localPort))
  80. {
  81. using (var hdHomerunManager = new HdHomerunManager(_socketFactory))
  82. {
  83. var remoteAddress = _networkManager.ParseIpAddress(remoteIp);
  84. IpAddressInfo localAddress = null;
  85. using (var tcpSocket = _socketFactory.CreateSocket(remoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp, false))
  86. {
  87. try
  88. {
  89. tcpSocket.Connect(new IpEndPointInfo(remoteAddress, HdHomerunManager.HdHomeRunPort));
  90. localAddress = tcpSocket.LocalEndPoint.IpAddress;
  91. tcpSocket.Close();
  92. }
  93. catch (Exception)
  94. {
  95. _logger.Error("Unable to determine local ip address for Legacy HDHomerun stream.");
  96. return;
  97. }
  98. }
  99. while (!cancellationToken.IsCancellationRequested)
  100. {
  101. try
  102. {
  103. // send url to start streaming
  104. await hdHomerunManager.StartStreaming(remoteAddress, localAddress, localPort, _channelCommands, _numTuners, cancellationToken).ConfigureAwait(false);
  105. _logger.Info("Opened HDHR UDP stream from {0}", remoteAddress);
  106. if (!cancellationToken.IsCancellationRequested)
  107. {
  108. Action onStarted = null;
  109. if (isFirstAttempt)
  110. {
  111. onStarted = () => openTaskCompletionSource.TrySetResult(true);
  112. }
  113. await _multicastStream.CopyUntilCancelled(new UdpClientStream(udpClient), onStarted, cancellationToken).ConfigureAwait(false);
  114. }
  115. }
  116. catch (OperationCanceledException ex)
  117. {
  118. _logger.Info("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
  119. openTaskCompletionSource.TrySetException(ex);
  120. break;
  121. }
  122. catch (Exception ex)
  123. {
  124. if (isFirstAttempt)
  125. {
  126. _logger.ErrorException("Error opening live stream:", ex);
  127. openTaskCompletionSource.TrySetException(ex);
  128. break;
  129. }
  130. _logger.ErrorException("Error copying live stream, will reopen", ex);
  131. }
  132. isFirstAttempt = false;
  133. }
  134. await hdHomerunManager.StopStreaming().ConfigureAwait(false);
  135. _liveStreamTaskCompletionSource.TrySetResult(true);
  136. }
  137. }
  138. }).ConfigureAwait(false);
  139. }
  140. public Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  141. {
  142. return _multicastStream.CopyToAsync(stream);
  143. }
  144. }
  145. // This handles the ReadAsync function only of a Stream object
  146. // This is used to wrap a UDP socket into a stream for MulticastStream which only uses ReadAsync
  147. public class UdpClientStream : Stream
  148. {
  149. private static int RtpHeaderBytes = 12;
  150. private static int PacketSize = 1316;
  151. private readonly ISocket _udpClient;
  152. bool disposed;
  153. public UdpClientStream(ISocket udpClient) : base()
  154. {
  155. _udpClient = udpClient;
  156. }
  157. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  158. {
  159. if (buffer == null)
  160. throw new ArgumentNullException("buffer");
  161. if (offset + count < 0)
  162. throw new ArgumentOutOfRangeException("offset + count must not be negative", "offset+count");
  163. if (offset + count > buffer.Length)
  164. throw new ArgumentException("offset + count must not be greater than the length of buffer", "offset+count");
  165. if (disposed)
  166. throw new ObjectDisposedException(typeof(UdpClientStream).ToString());
  167. // This will always receive a 1328 packet size (PacketSize + RtpHeaderSize)
  168. // The RTP header will be stripped so see how many reads we need to make to fill the buffer.
  169. int numReads = count / PacketSize;
  170. int totalBytesRead = 0;
  171. for (int i = 0; i < numReads; ++i)
  172. {
  173. var data = await _udpClient.ReceiveAsync(cancellationToken).ConfigureAwait(false);
  174. var bytesRead = data.ReceivedBytes - RtpHeaderBytes;
  175. // remove rtp header
  176. Buffer.BlockCopy(data.Buffer, RtpHeaderBytes, buffer, offset, bytesRead);
  177. offset += bytesRead;
  178. totalBytesRead += bytesRead;
  179. }
  180. return totalBytesRead;
  181. }
  182. protected override void Dispose(bool disposing)
  183. {
  184. disposed = true;
  185. }
  186. public override bool CanRead
  187. {
  188. get
  189. {
  190. throw new NotImplementedException();
  191. }
  192. }
  193. public override bool CanSeek
  194. {
  195. get
  196. {
  197. throw new NotImplementedException();
  198. }
  199. }
  200. public override bool CanWrite
  201. {
  202. get
  203. {
  204. throw new NotImplementedException();
  205. }
  206. }
  207. public override long Length
  208. {
  209. get
  210. {
  211. throw new NotImplementedException();
  212. }
  213. }
  214. public override long Position
  215. {
  216. get
  217. {
  218. throw new NotImplementedException();
  219. }
  220. set
  221. {
  222. throw new NotImplementedException();
  223. }
  224. }
  225. public override void Flush()
  226. {
  227. throw new NotImplementedException();
  228. }
  229. public override int Read(byte[] buffer, int offset, int count)
  230. {
  231. throw new NotImplementedException();
  232. }
  233. public override long Seek(long offset, SeekOrigin origin)
  234. {
  235. throw new NotImplementedException();
  236. }
  237. public override void SetLength(long value)
  238. {
  239. throw new NotImplementedException();
  240. }
  241. public override void Write(byte[] buffer, int offset, int count)
  242. {
  243. throw new NotImplementedException();
  244. }
  245. }
  246. }