HdHomerunUdpStream.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.LiveTv;
  16. using MediaBrowser.Model.MediaInfo;
  17. using Microsoft.Extensions.Logging;
  18. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  19. {
  20. public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
  21. {
  22. private const int RtpHeaderBytes = 12;
  23. private readonly IServerApplicationHost _appHost;
  24. private readonly IHdHomerunChannelCommands _channelCommands;
  25. private readonly int _numTuners;
  26. private readonly INetworkManager _networkManager;
  27. public HdHomerunUdpStream(
  28. MediaSourceInfo mediaSource,
  29. TunerHostInfo tunerHostInfo,
  30. string originalStreamId,
  31. IHdHomerunChannelCommands channelCommands,
  32. int numTuners,
  33. IFileSystem fileSystem,
  34. ILogger logger,
  35. IConfigurationManager configurationManager,
  36. IServerApplicationHost appHost,
  37. INetworkManager networkManager,
  38. IStreamHelper streamHelper)
  39. : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
  40. {
  41. _appHost = appHost;
  42. _networkManager = networkManager;
  43. OriginalStreamId = originalStreamId;
  44. _channelCommands = channelCommands;
  45. _numTuners = numTuners;
  46. EnableStreamSharing = true;
  47. }
  48. public override async Task Open(CancellationToken openCancellationToken)
  49. {
  50. LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  51. var mediaSource = OriginalMediaSource;
  52. var uri = new Uri(mediaSource.Path);
  53. var localPort = _networkManager.GetRandomUnusedUdpPort();
  54. Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
  55. Logger.LogInformation("Opening HDHR UDP Live stream from {host}", uri.Host);
  56. var remoteAddress = IPAddress.Parse(uri.Host);
  57. IPAddress localAddress = null;
  58. using (var tcpClient = new TcpClient())
  59. {
  60. try
  61. {
  62. await tcpClient.ConnectAsync(remoteAddress, HdHomerunManager.HdHomeRunPort).ConfigureAwait(false);
  63. localAddress = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address;
  64. tcpClient.Close();
  65. }
  66. catch (Exception ex)
  67. {
  68. Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream.");
  69. return;
  70. }
  71. }
  72. var udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);
  73. var hdHomerunManager = new HdHomerunManager();
  74. try
  75. {
  76. // send url to start streaming
  77. await hdHomerunManager.StartStreaming(
  78. remoteAddress,
  79. localAddress,
  80. localPort,
  81. _channelCommands,
  82. _numTuners,
  83. openCancellationToken).ConfigureAwait(false);
  84. }
  85. catch (Exception ex)
  86. {
  87. using (udpClient)
  88. using (hdHomerunManager)
  89. {
  90. if (!(ex is OperationCanceledException))
  91. {
  92. Logger.LogError(ex, "Error opening live stream:");
  93. }
  94. throw;
  95. }
  96. }
  97. var taskCompletionSource = new TaskCompletionSource<bool>();
  98. await StartStreaming(
  99. udpClient,
  100. hdHomerunManager,
  101. remoteAddress,
  102. taskCompletionSource,
  103. LiveStreamCancellationTokenSource.Token).ConfigureAwait(false);
  104. // OpenedMediaSource.Protocol = MediaProtocol.File;
  105. // OpenedMediaSource.Path = tempFile;
  106. // OpenedMediaSource.ReadAtNativeFramerate = true;
  107. MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  108. MediaSource.Protocol = MediaProtocol.Http;
  109. // OpenedMediaSource.SupportsDirectPlay = false;
  110. // OpenedMediaSource.SupportsDirectStream = true;
  111. // OpenedMediaSource.SupportsTranscoding = true;
  112. // await Task.Delay(5000).ConfigureAwait(false);
  113. await taskCompletionSource.Task.ConfigureAwait(false);
  114. }
  115. private Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  116. {
  117. return Task.Run(async () =>
  118. {
  119. using (udpClient)
  120. using (hdHomerunManager)
  121. {
  122. try
  123. {
  124. await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
  125. }
  126. catch (OperationCanceledException ex)
  127. {
  128. Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
  129. openTaskCompletionSource.TrySetException(ex);
  130. }
  131. catch (Exception ex)
  132. {
  133. Logger.LogError(ex, "Error opening live stream:");
  134. openTaskCompletionSource.TrySetException(ex);
  135. }
  136. EnableStreamSharing = false;
  137. }
  138. await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
  139. });
  140. }
  141. private async Task CopyTo(UdpClient udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  142. {
  143. var resolved = false;
  144. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
  145. {
  146. while (true)
  147. {
  148. cancellationToken.ThrowIfCancellationRequested();
  149. using (var timeOutSource = new CancellationTokenSource())
  150. using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(
  151. cancellationToken,
  152. timeOutSource.Token))
  153. {
  154. var resTask = udpClient.ReceiveAsync();
  155. if (await Task.WhenAny(resTask, Task.Delay(30000, linkedSource.Token)).ConfigureAwait(false) != resTask)
  156. {
  157. resTask.Dispose();
  158. break;
  159. }
  160. // We don't want all these delay tasks to keep running
  161. timeOutSource.Cancel();
  162. var res = await resTask.ConfigureAwait(false);
  163. var buffer = res.Buffer;
  164. var read = buffer.Length - RtpHeaderBytes;
  165. if (read > 0)
  166. {
  167. fileStream.Write(buffer, RtpHeaderBytes, read);
  168. }
  169. if (!resolved)
  170. {
  171. resolved = true;
  172. DateOpened = DateTime.UtcNow;
  173. openTaskCompletionSource.TrySetResult(true);
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. }