SharedHttpStream.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  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 = CompressionMethods.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.GetLoopbackHttpApiUrl() + "/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. if (taskCompletionSource.Task.Exception != null)
  101. {
  102. // Error happened while opening the stream so raise the exception again to inform the caller
  103. throw taskCompletionSource.Task.Exception;
  104. }
  105. if (!taskCompletionSource.Task.Result)
  106. {
  107. Logger.LogWarning("Zero bytes copied from stream {0} to {1} but no exception raised", GetType().Name, TempFilePath);
  108. throw new EndOfStreamException(String.Format(CultureInfo.InvariantCulture, "Zero bytes copied from stream {0}", GetType().Name));
  109. }
  110. }
  111. private Task StartStreaming(HttpResponseInfo response, TaskCompletionSource<bool> openTaskCompletionSource, CancellationToken cancellationToken)
  112. {
  113. return Task.Run(async () =>
  114. {
  115. try
  116. {
  117. Logger.LogInformation("Beginning {0} stream to {1}", GetType().Name, TempFilePath);
  118. using (response)
  119. using (var stream = response.Content)
  120. using (var fileStream = new FileStream(TempFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  121. {
  122. await StreamHelper.CopyToAsync(
  123. stream,
  124. fileStream,
  125. IODefaults.CopyToBufferSize,
  126. () => Resolve(openTaskCompletionSource),
  127. cancellationToken).ConfigureAwait(false);
  128. }
  129. }
  130. catch (OperationCanceledException ex)
  131. {
  132. Logger.LogInformation("Copying of {0} to {1} was canceled", GetType().Name, TempFilePath);
  133. openTaskCompletionSource.TrySetException(ex);
  134. }
  135. catch (Exception ex)
  136. {
  137. Logger.LogError(ex, "Error copying live stream {0} to {1}.", GetType().Name, TempFilePath);
  138. openTaskCompletionSource.TrySetException(ex);
  139. }
  140. openTaskCompletionSource.TrySetResult(false);
  141. EnableStreamSharing = false;
  142. await DeleteTempFiles(new List<string> { TempFilePath }).ConfigureAwait(false);
  143. });
  144. }
  145. private void Resolve(TaskCompletionSource<bool> openTaskCompletionSource)
  146. {
  147. DateOpened = DateTime.UtcNow;
  148. openTaskCompletionSource.TrySetResult(true);
  149. }
  150. }
  151. }