SharedHttpStream.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. }
  39. public override async Task Open(CancellationToken openCancellationToken)
  40. {
  41. LiveStreamCancellationTokenSource.Token.ThrowIfCancellationRequested();
  42. var mediaSource = OriginalMediaSource;
  43. var url = mediaSource.Path;
  44. Directory.CreateDirectory(Path.GetDirectoryName(TempFilePath) ?? throw new InvalidOperationException("Path can't be a root directory."));
  45. var typeName = GetType().Name;
  46. Logger.LogInformation("Opening {StreamType} Live stream from {Url}", typeName, url);
  47. // Response stream is disposed manually.
  48. var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  49. .GetAsync(url, HttpCompletionOption.ResponseHeadersRead, CancellationToken.None)
  50. .ConfigureAwait(false);
  51. var taskCompletionSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
  52. _ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
  53. MediaSource.Path = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  54. MediaSource.Protocol = MediaProtocol.Http;
  55. var res = await taskCompletionSource.Task.ConfigureAwait(false);
  56. if (!res)
  57. {
  58. Logger.LogWarning("Zero bytes copied from stream {StreamType} to {FilePath} but no exception raised", GetType().Name, TempFilePath);
  59. throw new EndOfStreamException(string.Format(CultureInfo.InvariantCulture, "Zero bytes copied from stream {0}", GetType().Name));
  60. }
  61. }
  62. private Task StartStreaming(HttpResponseMessage response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  63. {
  64. return Task.Run(
  65. async () =>
  66. {
  67. try
  68. {
  69. Logger.LogInformation("Beginning {StreamType} stream to {FilePath}", GetType().Name, TempFilePath);
  70. using (response)
  71. {
  72. var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  73. await using (stream.ConfigureAwait(false))
  74. {
  75. var fileStream = new FileStream(
  76. TempFilePath,
  77. FileMode.Create,
  78. FileAccess.Write,
  79. FileShare.Read,
  80. IODefaults.FileStreamBufferSize,
  81. FileOptions.Asynchronous);
  82. await using (fileStream.ConfigureAwait(false))
  83. {
  84. await StreamHelper.CopyToAsync(
  85. stream,
  86. fileStream,
  87. IODefaults.CopyToBufferSize,
  88. () => Resolve(openTaskCompletionSource),
  89. cancellationToken).ConfigureAwait(false);
  90. }
  91. }
  92. }
  93. }
  94. catch (OperationCanceledException ex)
  95. {
  96. Logger.LogInformation("Copying of {StreamType} to {FilePath} was canceled", GetType().Name, TempFilePath);
  97. openTaskCompletionSource.TrySetException(ex);
  98. }
  99. catch (Exception ex)
  100. {
  101. Logger.LogError(ex, "Error copying live stream {StreamType} to {FilePath}", GetType().Name, TempFilePath);
  102. openTaskCompletionSource.TrySetException(ex);
  103. }
  104. openTaskCompletionSource.TrySetResult(false);
  105. EnableStreamSharing = false;
  106. await DeleteTempFiles(TempFilePath).ConfigureAwait(false);
  107. },
  108. CancellationToken.None);
  109. }
  110. private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
  111. {
  112. DateOpened = DateTime.UtcNow;
  113. openTaskCompletionSource.TrySetResult(true);
  114. }
  115. }
  116. }