HdHomerunLiveStream.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. public HdHomerunLiveStream(MediaSourceInfo mediaSource, IFileSystem fileSystem, IHttpClient httpClient, ILogger logger, IServerApplicationPaths appPaths, IServerApplicationHost appHost)
  24. : base(mediaSource)
  25. {
  26. _fileSystem = fileSystem;
  27. _httpClient = httpClient;
  28. _logger = logger;
  29. _appPaths = appPaths;
  30. _appHost = appHost;
  31. }
  32. public override async Task Open(CancellationToken openCancellationToken)
  33. {
  34. _liveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  35. var mediaSource = OriginalMediaSource;
  36. var url = mediaSource.Path;
  37. var tempFile = Path.Combine(_appPaths.TranscodingTempPath, Guid.NewGuid().ToString("N") + ".ts");
  38. Directory.CreateDirectory(Path.GetDirectoryName(tempFile));
  39. _logger.Info("Opening HDHR Live stream from {0} to {1}", url, tempFile);
  40. var output = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read);
  41. var taskCompletionSource = new TaskCompletionSource<bool>();
  42. StartStreamingToTempFile(output, tempFile, url, taskCompletionSource, _liveStreamCancellationTokenSource.Token);
  43. await taskCompletionSource.Task.ConfigureAwait(false);
  44. PublicMediaSource.Path = _appHost.GetLocalApiUrl("localhost") + "/LiveTv/LiveStreamFiles/" + Path.GetFileNameWithoutExtension(tempFile) + "/stream.ts";
  45. PublicMediaSource.Protocol = MediaProtocol.Http;
  46. }
  47. public override Task Close()
  48. {
  49. _liveStreamCancellationTokenSource.Cancel();
  50. return base.Close();
  51. }
  52. private async Task StartStreamingToTempFile(Stream outputStream, string tempFilePath, string url, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  53. {
  54. await Task.Run(async () =>
  55. {
  56. using (outputStream)
  57. {
  58. var isFirstAttempt = true;
  59. while (!cancellationToken.IsCancellationRequested)
  60. {
  61. try
  62. {
  63. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  64. {
  65. Url = url,
  66. CancellationToken = cancellationToken,
  67. BufferContent = false
  68. }, "GET").ConfigureAwait(false))
  69. {
  70. _logger.Info("Opened HDHR stream from {0}", url);
  71. if (!cancellationToken.IsCancellationRequested)
  72. {
  73. _logger.Info("Beginning DirectRecorder.CopyUntilCancelled");
  74. Action onStarted = null;
  75. if (isFirstAttempt)
  76. {
  77. onStarted = () => openTaskCompletionSource.TrySetResult(true);
  78. }
  79. await DirectRecorder.CopyUntilCancelled(response.Content, outputStream, onStarted, cancellationToken).ConfigureAwait(false);
  80. }
  81. }
  82. }
  83. catch (OperationCanceledException)
  84. {
  85. break;
  86. }
  87. catch (Exception ex)
  88. {
  89. if (isFirstAttempt)
  90. {
  91. _logger.ErrorException("Error opening live stream:", ex);
  92. openTaskCompletionSource.TrySetException(ex);
  93. break;
  94. }
  95. _logger.ErrorException("Error copying live stream, will reopen", ex);
  96. }
  97. isFirstAttempt = false;
  98. }
  99. }
  100. await Task.Delay(5000).ConfigureAwait(false);
  101. DeleteTempFile(tempFilePath);
  102. }).ConfigureAwait(false);
  103. }
  104. private async void DeleteTempFile(string path)
  105. {
  106. for (var i = 0; i < 10; i++)
  107. {
  108. try
  109. {
  110. File.Delete(path);
  111. return;
  112. }
  113. catch (FileNotFoundException)
  114. {
  115. return;
  116. }
  117. catch (DirectoryNotFoundException)
  118. {
  119. return;
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  124. }
  125. await Task.Delay(1000).ConfigureAwait(false);
  126. }
  127. }
  128. }
  129. }