SharedHttpStream.cs 5.7 KB

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