SharedHttpStream.cs 6.0 KB

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