SharedHttpStream.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  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 IHttpClient _httpClient;
  22. private readonly IServerApplicationHost _appHost;
  23. public SharedHttpStream(
  24. MediaSourceInfo mediaSource,
  25. TunerHostInfo tunerHostInfo,
  26. string originalStreamId,
  27. IFileSystem fileSystem,
  28. IHttpClient httpClient,
  29. ILogger logger,
  30. IConfigurationManager configurationManager,
  31. IServerApplicationHost appHost,
  32. IStreamHelper streamHelper)
  33. : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
  34. {
  35. _httpClient = httpClient;
  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));
  46. var typeName = GetType().Name;
  47. Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url);
  48. var httpRequestOptions = new HttpRequestOptions
  49. {
  50. Url = url,
  51. CancellationToken = CancellationToken.None,
  52. BufferContent = false,
  53. DecompressionMethod = CompressionMethods.None
  54. };
  55. foreach (var header in mediaSource.RequiredHttpHeaders)
  56. {
  57. httpRequestOptions.RequestHeaders[header.Key] = header.Value;
  58. }
  59. var response = await _httpClient.SendAsync(httpRequestOptions, HttpMethod.Get).ConfigureAwait(false);
  60. var extension = "ts";
  61. var requiresRemux = false;
  62. var contentType = response.ContentType ?? string.Empty;
  63. if (contentType.IndexOf("matroska", StringComparison.OrdinalIgnoreCase) != -1)
  64. {
  65. requiresRemux = true;
  66. }
  67. else if (contentType.IndexOf("mp4", StringComparison.OrdinalIgnoreCase) != -1 ||
  68. contentType.IndexOf("dash", StringComparison.OrdinalIgnoreCase) != -1 ||
  69. contentType.IndexOf("mpegURL", StringComparison.OrdinalIgnoreCase) != -1 ||
  70. contentType.IndexOf("text/", StringComparison.OrdinalIgnoreCase) != -1)
  71. {
  72. requiresRemux = true;
  73. }
  74. // Close the stream without any sharing features
  75. if (requiresRemux)
  76. {
  77. using (response)
  78. {
  79. return;
  80. }
  81. }
  82. SetTempFilePath(extension);
  83. var taskCompletionSource = new TaskCompletionSource<bool>();
  84. var now = DateTime.UtcNow;
  85. _ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
  86. //OpenedMediaSource.Protocol = MediaProtocol.File;
  87. //OpenedMediaSource.Path = tempFile;
  88. //OpenedMediaSource.ReadAtNativeFramerate = true;
  89. MediaSource.Path = _appHost.GetLoopbackHttpApiUrl() + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  90. MediaSource.Protocol = MediaProtocol.Http;
  91. //OpenedMediaSource.Path = TempFilePath;
  92. //OpenedMediaSource.Protocol = MediaProtocol.File;
  93. //OpenedMediaSource.Path = _tempFilePath;
  94. //OpenedMediaSource.Protocol = MediaProtocol.File;
  95. //OpenedMediaSource.SupportsDirectPlay = false;
  96. //OpenedMediaSource.SupportsDirectStream = true;
  97. //OpenedMediaSource.SupportsTranscoding = true;
  98. await taskCompletionSource.Task.ConfigureAwait(false);
  99. }
  100. private Task StartStreaming(HttpResponseInfo response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  101. {
  102. return Task.Run(async () =>
  103. {
  104. try
  105. {
  106. Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath);
  107. using (response)
  108. using (var stream = response.Content)
  109. using (var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  110. {
  111. await StreamHelper.CopyToAsync(
  112. stream,
  113. fileStream,
  114. IODefaults.CopyToBufferSize,
  115. () => Resolve(openTaskCompletionSource),
  116. cancellationToken).ConfigureAwait(false);
  117. }
  118. }
  119. catch (OperationCanceledException)
  120. {
  121. }
  122. catch (Exception ex)
  123. {
  124. Logger.LogError(ex, "Error copying live stream.");
  125. }
  126. EnableStreamSharing = false;
  127. await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
  128. });
  129. }
  130. private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
  131. {
  132. DateOpened = DateTime.UtcNow;
  133. openTaskCompletionSource.TrySetResult(true);
  134. }
  135. }
  136. }