SharedHttpStream.cs 6.5 KB

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