SharedHttpStream.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Http;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Controller;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Model.Dto;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.LiveTv;
  14. using MediaBrowser.Model.MediaInfo;
  15. using Microsoft.Extensions.Logging;
  16. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  17. {
  18. public class SharedHttpStream : LiveStream, IDirectStreamProvider
  19. {
  20. private readonly IHttpClient _httpClient;
  21. private readonly IServerApplicationHost _appHost;
  22. public SharedHttpStream(
  23. MediaSourceInfo mediaSource,
  24. TunerHostInfo tunerHostInfo,
  25. string originalStreamId,
  26. IFileSystem fileSystem,
  27. IHttpClient httpClient,
  28. ILogger logger,
  29. IConfigurationManager configurationManager,
  30. IServerApplicationHost appHost,
  31. IStreamHelper streamHelper)
  32. : base(mediaSource, tunerHostInfo, fileSystem, logger, configurationManager, streamHelper)
  33. {
  34. _httpClient = httpClient;
  35. _appHost = appHost;
  36. OriginalStreamId = originalStreamId;
  37. EnableStreamSharing = true;
  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));
  45. var typeName = GetType().Name;
  46. Logger.LogInformation("Opening " + typeName + " Live stream from {0}", url);
  47. var httpRequestOptions = new HttpRequestOptions
  48. {
  49. Url = url,
  50. CancellationToken = CancellationToken.None,
  51. BufferContent = false,
  52. DecompressionMethod = CompressionMethod.None
  53. };
  54. foreach (var header in mediaSource.RequiredHttpHeaders)
  55. {
  56. httpRequestOptions.RequestHeaders[header.Key] = header.Value;
  57. }
  58. var response = await _httpClient.SendAsync(httpRequestOptions, HttpMethod.Get).ConfigureAwait(false);
  59. var extension = "ts";
  60. var requiresRemux = false;
  61. var contentType = response.ContentType ?? string.Empty;
  62. if (contentType.IndexOf("matroska", StringComparison.OrdinalIgnoreCase) != -1)
  63. {
  64. requiresRemux = true;
  65. }
  66. else if (contentType.IndexOf("mp4", StringComparison.OrdinalIgnoreCase) != -1 ||
  67. contentType.IndexOf("dash", StringComparison.OrdinalIgnoreCase) != -1 ||
  68. contentType.IndexOf("mpegURL", StringComparison.OrdinalIgnoreCase) != -1 ||
  69. contentType.IndexOf("text/", StringComparison.OrdinalIgnoreCase) != -1)
  70. {
  71. requiresRemux = true;
  72. }
  73. // Close the stream without any sharing features
  74. if (requiresRemux)
  75. {
  76. using (response)
  77. {
  78. return;
  79. }
  80. }
  81. SetTempFilePath(extension);
  82. var taskCompletionSource = new TaskCompletionSource<bool>();
  83. var now = DateTime.UtcNow;
  84. _ = StartStreaming(response, taskCompletionSource, LiveStreamCancellationTokenSource.Token);
  85. //OpenedMediaSource.Protocol = MediaProtocol.File;
  86. //OpenedMediaSource.Path = tempFile;
  87. //OpenedMediaSource.ReadAtNativeFramerate = true;
  88. MediaSource.Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveStreamFiles/" + UniqueId + "/stream.ts";
  89. MediaSource.Protocol = MediaProtocol.Http;
  90. //OpenedMediaSource.Path = TempFilePath;
  91. //OpenedMediaSource.Protocol = MediaProtocol.File;
  92. //OpenedMediaSource.Path = _tempFilePath;
  93. //OpenedMediaSource.Protocol = MediaProtocol.File;
  94. //OpenedMediaSource.SupportsDirectPlay = false;
  95. //OpenedMediaSource.SupportsDirectStream = true;
  96. //OpenedMediaSource.SupportsTranscoding = true;
  97. await taskCompletionSource.Task.ConfigureAwait(false);
  98. }
  99. private Task StartStreaming(HttpResponseInfo response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  100. {
  101. return Task.Run(async () =>
  102. {
  103. try
  104. {
  105. Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath);
  106. using (response)
  107. using (var stream = response.Content)
  108. using (var fileStream = FileSystem.GetFileStream(TempFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, FileOpenOptions.None))
  109. {
  110. await StreamHelper.CopyToAsync(
  111. stream,
  112. fileStream,
  113. StreamDefaults.DefaultCopyToBufferSize,
  114. () => Resolve(openTaskCompletionSource),
  115. cancellationToken).ConfigureAwait(false);
  116. }
  117. }
  118. catch (OperationCanceledException)
  119. {
  120. }
  121. catch (Exception ex)
  122. {
  123. Logger.LogError(ex, "Error copying live stream.");
  124. }
  125. EnableStreamSharing = false;
  126. await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
  127. });
  128. }
  129. private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
  130. {
  131. DateOpened = DateTime.UtcNow;
  132. openTaskCompletionSource.TrySetResult(true);
  133. }
  134. }
  135. }