HdHomerunUdpStream.cs 13 KB

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