HdHomerunUdpStream.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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.LocalEndPoint).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. if (localAddress.IsIPv4MappedToIPv6) {
  73. localAddress = localAddress.MapToIPv4();
  74. }
  75. var udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);
  76. var hdHomerunManager = new HdHomerunManager();
  77. try
  78. {
  79. // send url to start streaming
  80. await hdHomerunManager.StartStreaming(
  81. remoteAddress,
  82. localAddress,
  83. localPort,
  84. _channelCommands,
  85. _numTuners,
  86. openCancellationToken).ConfigureAwait(false);
  87. }
  88. catch (Exception ex)
  89. {
  90. using (udpClient)
  91. using (hdHomerunManager)
  92. {
  93. if (!(ex is OperationCanceledException))
  94. {
  95. Logger.LogError(ex, "Error opening live stream:");
  96. }
  97. throw;
  98. }
  99. }
  100. var taskCompletionSource = new TaskCompletionSource<bool>();
  101. _ = StartStreaming(
  102. udpClient,
  103. hdHomerunManager,
  104. remoteAddress,
  105. taskCompletionSource,
  106. LiveStreamCancellationTokenSource.Token);
  107. // OpenedMediaSource.Protocol = MediaProtocol.File;
  108. // OpenedMediaSource.Path = tempFile;
  109. // OpenedMediaSource.ReadAtNativeFramerate = true;
  110. MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  111. MediaSource.Protocol = MediaProtocol.Http;
  112. // OpenedMediaSource.SupportsDirectPlay = false;
  113. // OpenedMediaSource.SupportsDirectStream = true;
  114. // OpenedMediaSource.SupportsTranscoding = true;
  115. // await Task.Delay(5000).ConfigureAwait(false);
  116. await taskCompletionSource.Task.ConfigureAwait(false);
  117. }
  118. public string GetFilePath()
  119. {
  120. return TempFilePath;
  121. }
  122. private async Task StartStreaming(UdpClient udpClient, HdHomerunManager hdHomerunManager, IPAddress remoteAddress, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  123. {
  124. using (udpClient)
  125. using (hdHomerunManager)
  126. {
  127. try
  128. {
  129. await CopyTo(udpClient, TempFilePath, openTaskCompletionSource, cancellationToken).ConfigureAwait(false);
  130. }
  131. catch (OperationCanceledException ex)
  132. {
  133. Logger.LogInformation("HDHR UDP stream cancelled or timed out from {0}", remoteAddress);
  134. openTaskCompletionSource.TrySetException(ex);
  135. }
  136. catch (Exception ex)
  137. {
  138. Logger.LogError(ex, "Error opening live stream:");
  139. openTaskCompletionSource.TrySetException(ex);
  140. }
  141. EnableStreamSharing = false;
  142. }
  143. await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
  144. }
  145. private async Task CopyTo(UdpClient udpClient, string file, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  146. {
  147. var resolved = false;
  148. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
  149. {
  150. while (true)
  151. {
  152. cancellationToken.ThrowIfCancellationRequested();
  153. using (var timeOutSource = new CancellationTokenSource())
  154. using (var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(
  155. cancellationToken,
  156. timeOutSource.Token))
  157. {
  158. var resTask = udpClient.ReceiveAsync();
  159. if (await Task.WhenAny(resTask, Task.Delay(30000, linkedSource.Token)).ConfigureAwait(false) != resTask)
  160. {
  161. resTask.Dispose();
  162. break;
  163. }
  164. // We don't want all these delay tasks to keep running
  165. timeOutSource.Cancel();
  166. var res = await resTask.ConfigureAwait(false);
  167. var buffer = res.Buffer;
  168. var read = buffer.Length - RtpHeaderBytes;
  169. if (read > 0)
  170. {
  171. fileStream.Write(buffer, RtpHeaderBytes, read);
  172. }
  173. if (!resolved)
  174. {
  175. resolved = true;
  176. DateOpened = DateTime.UtcNow;
  177. openTaskCompletionSource.TrySetResult(true);
  178. }
  179. }
  180. }
  181. }
  182. }
  183. }
  184. }