HdHomerunUdpStream.cs 16 KB

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