SharedHttpStream.cs 5.9 KB

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