SharedHttpStream.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Net.Http;
  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
  19. {
  20. public class SharedHttpStream : LiveStream, IDirectStreamProvider
  21. {
  22. private readonly IHttpClientFactory _httpClientFactory;
  23. private readonly IServerApplicationHost _appHost;
  24. public SharedHttpStream(
  25. MediaSourceInfo mediaSource,
  26. TunerHostInfo tunerHostInfo,
  27. string originalStreamId,
  28. IFileSystem fileSystem,
  29. IHttpClientFactory httpClientFactory,
  30. ILogger logger,
  31. IConfigurationManager configurationManager,
  32. IServerApplicationHost appHost,
  33. IStreamHelper streamHelper)
  34. : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
  35. {
  36. _httpClientFactory = httpClientFactory;
  37. _appHost = appHost;
  38. OriginalStreamId = originalStreamId;
  39. EnableStreamSharing = true;
  40. }
  41. public override async Task Open(CancellationToken openCancellationToken)
  42. {
  43. LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  44. var mediaSource = OriginalMediaSource;
  45. var url = mediaSource.Path;
  46. Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath));
  47. var typeName = GetType().Name;
  48. Logger.LogInformation("Opening {StreamType} Live stream from {Url}", typeName, url);
  49. // Response stream is disposed manually.
  50. var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  51. .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None)
  52. .ConfigureAwait(false);
  53. var contentType = response.Content.Headers.ContentType?.ToString() ?? string.Empty;
  54. if (contentType.Contains("matroska", StringComparison.OrdinalIgnoreCase)
  55. || contentType.Contains("mp4", StringComparison.OrdinalIgnoreCase)
  56. || contentType.Contains("dash", StringComparison.OrdinalIgnoreCase)
  57. || contentType.Contains("mpegURL", StringComparison.OrdinalIgnoreCase)
  58. || contentType.Contains("text/", StringComparison.OrdinalIgnoreCase))
  59. {
  60. // Close the stream without any sharing features
  61. response.Dispose();
  62. return;
  63. }
  64. SetTempFilePath("ts");
  65. var taskCompletionSource = new TaskCompletionSource<bool>();
  66. _ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
  67. // OpenedMediaSource.Protocol = MediaProtocol.File;
  68. // OpenedMediaSource.Path = tempFile;
  69. // OpenedMediaSource.ReadAtNativeFramerate = true;
  70. MediaSource.Path = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  71. MediaSource.Protocol = MediaProtocol.Http;
  72. // OpenedMediaSource.Path = TempFilePath;
  73. // OpenedMediaSource.Protocol = MediaProtocol.File;
  74. // OpenedMediaSource.Path = _tempFilePath;
  75. // OpenedMediaSource.Protocol = MediaProtocol.File;
  76. // OpenedMediaSource.SupportsDirectPlay = false;
  77. // OpenedMediaSource.SupportsDirectStream = true;
  78. // OpenedMediaSource.SupportsTranscoding = true;
  79. await taskCompletionSource.Task.ConfigureAwait(false);
  80. if (taskCompletionSource.Task.Exception != null)
  81. {
  82. // Error happened while opening the stream so raise the exception again to inform the caller
  83. throw taskCompletionSource.Task.Exception;
  84. }
  85. if (!taskCompletionSource.Task.Result)
  86. {
  87. Logger.LogWarning("Zero bytes copied from stream {StreamType} to {FilePath} but no exception raised", GetType().Name, TempFilePath);
  88. throw new EndOfStreamException(string.Format(CultureInfo.InvariantCulture, "Zero bytes copied from stream {0}", GetType().Name));
  89. }
  90. }
  91. private Task StartStreaming(HttpResponseMessage response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  92. {
  93. return Task.Run(
  94. async () =>
  95. {
  96. try
  97. {
  98. Logger.LogInformation("Beginning {StreamType} stream to {FilePath}", GetType().Name, TempFilePath);
  99. using var message = response;
  100. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  101. await using var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  102. await StreamHelper.CopyToAsync(
  103. stream,
  104. fileStream,
  105. IODefaults.CopyToBufferSize,
  106. () => Resolve(openTaskCompletionSource),
  107. cancellationToken).ConfigureAwait(false);
  108. }
  109. catch (OperationCanceledException ex)
  110. {
  111. Logger.LogInformation("Copying of {StreamType} to {FilePath} was canceled", GetType().Name, TempFilePath);
  112. openTaskCompletionSource.TrySetException(ex);
  113. }
  114. catch (Exception ex)
  115. {
  116. Logger.LogError(ex, "Error copying live stream {StreamType} to {FilePath}", GetType().Name, TempFilePath);
  117. openTaskCompletionSource.TrySetException(ex);
  118. }
  119. openTaskCompletionSource.TrySetResult(false);
  120. EnableStreamSharing = false;
  121. await DeleteTempFiles(TempFilePath).ConfigureAwait(false);
  122. },
  123. CancellationToken.None);
  124. }
  125. private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
  126. {
  127. DateOpened = DateTime.UtcNow;
  128. openTaskCompletionSource.TrySetResult(true);
  129. }
  130. }
  131. }