SharedHttpStream.cs 5.9 KB

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