HdHomerunLiveStream.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using CommonIO;
  6. using MediaBrowser.Common.Net;
  7. using MediaBrowser.Controller;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.MediaInfo;
  12. using MediaBrowser.Server.Implementations.LiveTv.EmbyTV;
  13. namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun
  14. {
  15. public class HdHomerunLiveStream : LiveStream
  16. {
  17. private readonly ILogger _logger;
  18. private readonly IHttpClient _httpClient;
  19. private readonly IFileSystem _fileSystem;
  20. private readonly IServerApplicationPaths _appPaths;
  21. private readonly IServerApplicationHost _appHost;
  22. private readonly CancellationTokenSource _liveStreamCancellationTokenSource = new CancellationTokenSource();
  23. private readonly TaskCompletionSource<bool> _liveStreamTaskCompletionSource = new TaskCompletionSource<bool>();
  24. public HdHomerunLiveStream(MediaSourceInfo mediaSource, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost)
  25. : base(mediaSource)
  26. {
  27. _fileSystem = fileSystem;
  28. _httpClient = httpClient;
  29. _logger = logger;
  30. _appPaths = appPaths;
  31. _appHost = appHost;
  32. }
  33. protected override async Task OpenInternal(CancellationToken openCancellationToken)
  34. {
  35. _liveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  36. var mediaSource = OriginalMediaSource;
  37. var url = mediaSource.Path;
  38. var tempFile = Path.Combine(_appPaths.TranscodingTempPath, Guid.NewGuid().ToString("N") + ".ts");
  39. Directory.CreateDirectory(Path.GetDirectoryName(tempFile));
  40. _logger.Info("Opening HDHR Live stream from {0} to {1}", url, tempFile);
  41. var output = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read);
  42. var taskCompletionSource = new TaskCompletionSource<bool>();
  43. StartStreamingToTempFile(output, tempFile, url, taskCompletionSource, _liveStreamCancellationTokenSource.Token);
  44. //OpenedMediaSource.Protocol = MediaProtocol.File;
  45. //OpenedMediaSource.Path = tempFile;
  46. //OpenedMediaSource.ReadAtNativeFramerate = true;
  47. OpenedMediaSource.Path = _appHost.GetLocalApiUrl("localhost") + "/LiveTv/LiveStreamFiles/" + Path.GetFileNameWithoutExtension(tempFile) + "/stream.ts";
  48. OpenedMediaSource.Protocol = MediaProtocol.Http;
  49. OpenedMediaSource.SupportsDirectPlay = false;
  50. OpenedMediaSource.SupportsDirectStream = true;
  51. OpenedMediaSource.SupportsTranscoding = true;
  52. await taskCompletionSource.Task.ConfigureAwait(false);
  53. //await Task.Delay(5000).ConfigureAwait(false);
  54. }
  55. public override Task Close()
  56. {
  57. _logger.Info("Closing HDHR live stream");
  58. _liveStreamCancellationTokenSource.Cancel();
  59. return _liveStreamTaskCompletionSource.Task;
  60. }
  61. private async Task StartStreamingToTempFile(Stream outputStream, string tempFilePath, string url, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  62. {
  63. await Task.Run(async () =>
  64. {
  65. using (outputStream)
  66. {
  67. var isFirstAttempt = true;
  68. while (!cancellationToken.IsCancellationRequested)
  69. {
  70. try
  71. {
  72. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  73. {
  74. Url = url,
  75. CancellationToken = cancellationToken,
  76. BufferContent = false
  77. }, "GET").ConfigureAwait(false))
  78. {
  79. _logger.Info("Opened HDHR stream from {0}", url);
  80. if (!cancellationToken.IsCancellationRequested)
  81. {
  82. _logger.Info("Beginning DirectRecorder.CopyUntilCancelled");
  83. Action onStarted = null;
  84. if (isFirstAttempt)
  85. {
  86. onStarted = () => openTaskCompletionSource.TrySetResult(true);
  87. }
  88. await DirectRecorder.CopyUntilCancelled(response.Content, outputStream, onStarted, cancellationToken).ConfigureAwait(false);
  89. }
  90. }
  91. }
  92. catch (OperationCanceledException)
  93. {
  94. break;
  95. }
  96. catch (Exception ex)
  97. {
  98. if (isFirstAttempt)
  99. {
  100. _logger.ErrorException("Error opening live stream:", ex);
  101. openTaskCompletionSource.TrySetException(ex);
  102. break;
  103. }
  104. _logger.ErrorException("Error copying live stream, will reopen", ex);
  105. }
  106. isFirstAttempt = false;
  107. }
  108. }
  109. _liveStreamTaskCompletionSource.TrySetResult(true);
  110. DeleteTempFile(tempFilePath);
  111. }).ConfigureAwait(false);
  112. }
  113. private async void DeleteTempFile(string path)
  114. {
  115. for (var i = 0; i < 10; i++)
  116. {
  117. try
  118. {
  119. File.Delete(path);
  120. return;
  121. }
  122. catch (FileNotFoundException)
  123. {
  124. return;
  125. }
  126. catch (DirectoryNotFoundException)
  127. {
  128. return;
  129. }
  130. catch (Exception ex)
  131. {
  132. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  133. }
  134. await Task.Delay(1000).ConfigureAwait(false);
  135. }
  136. }
  137. }
  138. }