HdHomerunHttpStream.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Common.Net;
  7. using MediaBrowser.Controller;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.MediaInfo;
  13. using MediaBrowser.Model.System;
  14. namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  15. {
  16. public class HdHomerunHttpStream : LiveStream, IDirectStreamProvider
  17. {
  18. private readonly ILogger _logger;
  19. private readonly IHttpClient _httpClient;
  20. private readonly IServerApplicationHost _appHost;
  21. private readonly CancellationTokenSource _liveStreamCancellationTokenSource = new CancellationTokenSource();
  22. private readonly TaskCompletionSource<bool> _liveStreamTaskCompletionSource = new TaskCompletionSource<bool>();
  23. private readonly string _tempFilePath;
  24. public HdHomerunHttpStream(MediaSourceInfo mediaSource, string originalStreamId, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost, IEnvironmentInfo environment)
  25. : base(mediaSource, environment, fileSystem)
  26. {
  27. _httpClient = httpClient;
  28. _logger = logger;
  29. _appHost = appHost;
  30. OriginalStreamId = originalStreamId;
  31. _tempFilePath = Path.Combine(appPaths.TranscodingTempPath, UniqueId + ".ts");
  32. }
  33. protected override async Task OpenInternal(CancellationToken openCancellationToken)
  34. {
  35. _liveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  36. var mediaSource = OriginalMediaSource;
  37. var url = mediaSource.Path;
  38. _logger.Info("Opening HDHR Live stream from {0}", url);
  39. var taskCompletionSource = new TaskCompletionSource<bool>();
  40. StartStreaming(url, taskCompletionSource, _liveStreamCancellationTokenSource.Token);
  41. //OpenedMediaSource.Protocol = MediaProtocol.File;
  42. //OpenedMediaSource.Path = tempFile;
  43. //OpenedMediaSource.ReadAtNativeFramerate = true;
  44. OpenedMediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  45. OpenedMediaSource.Protocol = MediaProtocol.Http;
  46. //OpenedMediaSource.SupportsDirectPlay = false;
  47. //OpenedMediaSource.SupportsDirectStream = true;
  48. //OpenedMediaSource.SupportsTranscoding = true;
  49. await taskCompletionSource.Task.ConfigureAwait(false);
  50. //await Task.Delay(5000).ConfigureAwait(false);
  51. }
  52. public override Task Close()
  53. {
  54. _logger.Info("Closing HDHR live stream");
  55. _liveStreamCancellationTokenSource.Cancel();
  56. return _liveStreamTaskCompletionSource.Task;
  57. }
  58. private Task StartStreaming(string url, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  59. {
  60. return Task.Run(async () =>
  61. {
  62. var isFirstAttempt = true;
  63. while (!cancellationToken.IsCancellationRequested)
  64. {
  65. try
  66. {
  67. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  68. {
  69. Url = url,
  70. CancellationToken = cancellationToken,
  71. BufferContent = false,
  72. // Increase a little bit
  73. TimeoutMs = 30000
  74. }, "GET").ConfigureAwait(false))
  75. {
  76. _logger.Info("Opened HDHR stream from {0}", url);
  77. if (!cancellationToken.IsCancellationRequested)
  78. {
  79. _logger.Info("Beginning multicastStream.CopyUntilCancelled");
  80. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(_tempFilePath));
  81. using (var fileStream = FileSystem.GetFileStream(_tempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.Asynchronous | FileOpenOptions.SequentialScan))
  82. {
  83. ResolveAfterDelay(2000, openTaskCompletionSource);
  84. await response.Content.CopyToAsync(fileStream, 81920, cancellationToken).ConfigureAwait(false);
  85. }
  86. }
  87. }
  88. }
  89. catch (OperationCanceledException)
  90. {
  91. break;
  92. }
  93. catch (Exception ex)
  94. {
  95. if (isFirstAttempt)
  96. {
  97. _logger.ErrorException("Error opening live stream:", ex);
  98. openTaskCompletionSource.TrySetException(ex);
  99. break;
  100. }
  101. _logger.ErrorException("Error copying live stream, will reopen", ex);
  102. }
  103. isFirstAttempt = false;
  104. }
  105. _liveStreamTaskCompletionSource.TrySetResult(true);
  106. await DeleteTempFile(_tempFilePath).ConfigureAwait(false);
  107. });
  108. }
  109. private void ResolveAfterDelay(int delayMs, TaskCompletionSource<bool> openTaskCompletionSource)
  110. {
  111. Task.Run(async () =>
  112. {
  113. await Task.Delay(delayMs).ConfigureAwait(false);
  114. openTaskCompletionSource.TrySetResult(true);
  115. });
  116. }
  117. public Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  118. {
  119. return CopyFileTo(_tempFilePath, false, stream, cancellationToken);
  120. }
  121. }
  122. }