SharedHttpStream.cs 5.5 KB

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