HdHomerunLiveStream.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. public override async Task Open(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. await taskCompletionSource.Task.ConfigureAwait(false);
  45. PublicMediaSource.Path = _appHost.GetLocalApiUrl("localhost") + "/LiveTv/LiveStreamFiles/" + Path.GetFileNameWithoutExtension(tempFile) + "/stream.ts";
  46. PublicMediaSource.Protocol = MediaProtocol.Http;
  47. }
  48. public override Task Close()
  49. {
  50. _liveStreamCancellationTokenSource.Cancel();
  51. return _liveStreamTaskCompletionSource.Task;
  52. }
  53. private async Task StartStreamingToTempFile(Stream outputStream, string tempFilePath, string url, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  54. {
  55. await Task.Run(async () =>
  56. {
  57. using (outputStream)
  58. {
  59. var isFirstAttempt = true;
  60. while (!cancellationToken.IsCancellationRequested)
  61. {
  62. try
  63. {
  64. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  65. {
  66. Url = url,
  67. CancellationToken = cancellationToken,
  68. BufferContent = false
  69. }, "GET").ConfigureAwait(false))
  70. {
  71. _logger.Info("Opened HDHR stream from {0}", url);
  72. if (!cancellationToken.IsCancellationRequested)
  73. {
  74. _logger.Info("Beginning DirectRecorder.CopyUntilCancelled");
  75. Action onStarted = null;
  76. if (isFirstAttempt)
  77. {
  78. onStarted = () => openTaskCompletionSource.TrySetResult(true);
  79. }
  80. await DirectRecorder.CopyUntilCancelled(response.Content, outputStream, onStarted, cancellationToken).ConfigureAwait(false);
  81. }
  82. }
  83. }
  84. catch (OperationCanceledException)
  85. {
  86. break;
  87. }
  88. catch (Exception ex)
  89. {
  90. if (isFirstAttempt)
  91. {
  92. _logger.ErrorException("Error opening live stream:", ex);
  93. openTaskCompletionSource.TrySetException(ex);
  94. break;
  95. }
  96. _logger.ErrorException("Error copying live stream, will reopen", ex);
  97. }
  98. isFirstAttempt = false;
  99. }
  100. }
  101. _liveStreamTaskCompletionSource.TrySetResult(true);
  102. DeleteTempFile(tempFilePath);
  103. }).ConfigureAwait(false);
  104. }
  105. private async void DeleteTempFile(string path)
  106. {
  107. for (var i = 0; i < 10; i++)
  108. {
  109. try
  110. {
  111. File.Delete(path);
  112. return;
  113. }
  114. catch (FileNotFoundException)
  115. {
  116. return;
  117. }
  118. catch (DirectoryNotFoundException)
  119. {
  120. return;
  121. }
  122. catch (Exception ex)
  123. {
  124. _logger.ErrorException("Error deleting temp file {0}", ex, path);
  125. }
  126. await Task.Delay(1000).ConfigureAwait(false);
  127. }
  128. }
  129. }
  130. }