HdHomerunUdpStream.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.NetworkInformation;
  8. using System.Net.Sockets;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.LiveTv;
  17. using MediaBrowser.Model.MediaInfo;
  18. using Microsoft.Extensions.Logging;
  19. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  20. {
  21. public class HdHomerunUdpStream : LiveStream, IDirectStreamProvider
  22. {
  23. private const int RtpHeaderBytes = 12;
  24. private readonly IServerApplicationHost _appHost;
  25. private readonly IHdHomerunChannelCommands _channelCommands;
  26. private readonly int _numTuners;
  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. IStreamHelper streamHelper)
  38. : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
  39. {
  40. _appHost = appHost;
  41. OriginalStreamId = originalStreamId;
  42. _channelCommands = channelCommands;
  43. _numTuners = numTuners;
  44. EnableStreamSharing = true;
  45. }
  46. /// <summary>
  47. /// Returns an unused UDP port number in the range specified.
  48. /// Temporarily placed here until future network PR merged.
  49. /// </summary>
  50. /// <param name="range">Upper and Lower boundary of ports to select.</param>
  51. /// <returns>System.Int32.</returns>
  52. private static int GetUdpPortFromRange((int Min, int Max) range)
  53. {
  54. var properties = IPGlobalProperties.GetIPGlobalProperties();
  55. // Get active udp listeners.
  56. var udpListenerPorts = properties.GetActiveUdpListeners()
  57. .Where(n => n.Port >= range.Min && n.Port <= range.Max)
  58. .Select(n => n.Port);
  59. return Enumerable
  60. .Range(range.Min, range.Max)
  61. .FirstOrDefault(i => !udpListenerPorts.Contains(i));
  62. }
  63. public override async Task Open(CancellationToken openCancellationToken)
  64. {
  65. LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  66. var mediaSource = OriginalMediaSource;
  67. var uri = new Uri(mediaSource.Path);
  68. // Temporary code to reduce PR size. This will be updated by a future network pr.
  69. var localPort = GetUdpPortFromRange((49152, 65535));
  70. Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
  71. Logger.LogInformation("Opening HDHR UDP Live stream from {Host}", uri.Host);
  72. var remoteAddress = IPAddress.Parse(uri.Host);
  73. IPAddress localAddress;
  74. using (var tcpClient = new TcpClient())
  75. {
  76. try
  77. {
  78. await tcpClient.ConnectAsync(remoteAddress, HdHomerunManager.HdHomeRunPort, openCancellationToken).ConfigureAwait(false);
  79. localAddress = ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address;
  80. tcpClient.Close();
  81. }
  82. catch (Exception ex)
  83. {
  84. Logger.LogError(ex, "Unable to determine local ip address for Legacy HDHomerun stream.");
  85. return;
  86. }
  87. }
  88. if (localAddress.IsIPv4MappedToIPv6)
  89. {
  90. localAddress = localAddress.MapToIPv4();
  91. }
  92. var udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);
  93. var hdHomerunManager = new HdHomerunManager();
  94. try
  95. {
  96. // send url to start streaming
  97. await hdHomerunManager.StartStreaming(
  98. remoteAddress,
  99. localAddress,
  100. localPort,
  101. _channelCommands,
  102. _numTuners,
  103. openCancellationToken).ConfigureAwait(false);
  104. }
  105. catch (Exception ex)
  106. {
  107. using (udpClient)
  108. using (hdHomerunManager)
  109. {
  110. if (ex is not OperationCanceledException)
  111. {
  112. Logger.LogError(ex, "Error opening live stream:");
  113. }
  114. throw;
  115. }
  116. }
  117. var taskCompletionSource = new TaskCompletionSource<bool>();
  118. _ = StartStreaming(
  119. udpClient,
  120. hdHomerunManager,
  121. remoteAddress,
  122. taskCompletionSource,
  123. LiveStreamCancellationTokenSource.Token);
  124. // OpenedMediaSource.Protocol = MediaProtocol.File;
  125. // OpenedMediaSource.Path = tempFile;
  126. // OpenedMediaSource.ReadAtNativeFramerate = true;
  127. MediaSource.Path = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  128. MediaSource.Protocol = MediaProtocol.Http;
  129. // OpenedMediaSource.SupportsDirectPlay = false;
  130. // OpenedMediaSource.SupportsDirectStream = true;
  131. // OpenedMediaSource.SupportsTranscoding = true;
  132. // await Task.Delay(5000).ConfigureAwait(false);
  133. await taskCompletionSource.Task.ConfigureAwait(false);
  134. }
  135. private async Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  136. {
  137. using (udpClient)
  138. using (hdHomerunManager)
  139. {
  140. try
  141. {
  142. await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
  143. }
  144. catch (OperationCanceledException ex)
  145. {
  146. Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
  147. openTaskCompletionSource.TrySetException(ex);
  148. }
  149. catch (Exception ex)
  150. {
  151. Logger.LogError(ex, "Error opening live stream:");
  152. openTaskCompletionSource.TrySetException(ex);
  153. }
  154. EnableStreamSharing = false;
  155. }
  156. await DeleteTempFiles(TempFilePath).ConfigureAwait(false);
  157. }
  158. private async Task CopyTo(UdpClient udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  159. {
  160. var resolved = false;
  161. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
  162. {
  163. while (true)
  164. {
  165. cancellationToken.ThrowIfCancellationRequested();
  166. using (var timeOutSource = new CancellationTokenSource())
  167. using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(
  168. cancellationToken,
  169. timeOutSource.Token))
  170. {
  171. var resTask = udpClient.ReceiveAsync(linkedSource.Token).AsTask();
  172. if (await Task.WhenAny(resTask, Task.Delay(30000, linkedSource.Token)).ConfigureAwait(false) != resTask)
  173. {
  174. resTask.Dispose();
  175. break;
  176. }
  177. // We don't want all these delay tasks to keep running
  178. timeOutSource.Cancel();
  179. var res = await resTask.ConfigureAwait(false);
  180. var buffer = res.Buffer;
  181. var read = buffer.Length - RtpHeaderBytes;
  182. if (read > 0)
  183. {
  184. await fileStream.WriteAsync(buffer.AsMemory(RtpHeaderBytes, read), linkedSource.Token).ConfigureAwait(false);
  185. }
  186. if (!resolved)
  187. {
  188. resolved = true;
  189. DateOpened = DateTime.UtcNow;
  190. openTaskCompletionSource.TrySetResult(true);
  191. }
  192. }
  193. }
  194. }
  195. }
  196. }
  197. }