LiveStream.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.LiveTv;
  13. using Microsoft.Extensions.Logging;
  14. namespace Emby.Server.Implementations.LiveTv.TunerHosts
  15. {
  16. public class LiveStream : ILiveStream
  17. {
  18. private readonly IConfigurationManager _configurationManager;
  19. protected readonly IFileSystem FileSystem;
  20. protected readonly IStreamHelper StreamHelper;
  21. protected string TempFilePath;
  22. protected readonly ILogger Logger;
  23. protected readonly CancellationTokenSource LiveStreamCancellationTokenSource = new CancellationTokenSource();
  24. public LiveStream(
  25. MediaSourceInfo mediaSource,
  26. TunerHostInfo tuner,
  27. IFileSystem fileSystem,
  28. ILogger logger,
  29. IConfigurationManager configurationManager,
  30. IStreamHelper streamHelper)
  31. {
  32. OriginalMediaSource = mediaSource;
  33. FileSystem = fileSystem;
  34. MediaSource = mediaSource;
  35. Logger = logger;
  36. EnableStreamSharing = true;
  37. UniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
  38. if (tuner != null)
  39. {
  40. TunerHostId = tuner.Id;
  41. }
  42. _configurationManager = configurationManager;
  43. StreamHelper = streamHelper;
  44. ConsumerCount = 1;
  45. SetTempFilePath("ts");
  46. }
  47. protected virtual int EmptyReadLimit => 1000;
  48. public MediaSourceInfo OriginalMediaSource { get; set; }
  49. public MediaSourceInfo MediaSource { get; set; }
  50. public int ConsumerCount { get; set; }
  51. public string OriginalStreamId { get; set; }
  52. public bool EnableStreamSharing { get; set; }
  53. public string UniqueId { get; }
  54. public string TunerHostId { get; }
  55. public DateTime DateOpened { get; protected set; }
  56. protected void SetTempFilePath(string extension)
  57. {
  58. TempFilePath = Path.Combine(_configurationManager.GetTranscodePath(), UniqueId + "." + extension);
  59. }
  60. public virtual Task Open(CancellationToken openCancellationToken)
  61. {
  62. DateOpened = DateTime.UtcNow;
  63. return Task.CompletedTask;
  64. }
  65. public Task Close()
  66. {
  67. EnableStreamSharing = false;
  68. Logger.LogInformation("Closing {Type}", GetType().Name);
  69. LiveStreamCancellationTokenSource.Cancel();
  70. return Task.CompletedTask;
  71. }
  72. protected FileStream GetInputStream(string path, bool allowAsyncFileRead)
  73. => new FileStream(
  74. path,
  75. FileMode.Open,
  76. FileAccess.Read,
  77. FileShare.ReadWrite,
  78. StreamDefaults.DefaultFileStreamBufferSize,
  79. allowAsyncFileRead ? FileOptions.SequentialScan | FileOptions.Asynchronous : FileOptions.SequentialScan);
  80. public Task DeleteTempFiles()
  81. {
  82. return DeleteTempFiles(GetStreamFilePaths());
  83. }
  84. protected async Task DeleteTempFiles(IEnumerable<string> paths, int retryCount = 0)
  85. {
  86. if (retryCount == 0)
  87. {
  88. Logger.LogInformation("Deleting temp files {0}", paths);
  89. }
  90. var failedFiles = new List<string>();
  91. foreach (var path in paths)
  92. {
  93. if (!File.Exists(path))
  94. {
  95. continue;
  96. }
  97. try
  98. {
  99. FileSystem.DeleteFile(path);
  100. }
  101. catch (Exception ex)
  102. {
  103. Logger.LogError(ex, "Error deleting file {path}", path);
  104. failedFiles.Add(path);
  105. }
  106. }
  107. if (failedFiles.Count > 0 && retryCount <= 40)
  108. {
  109. await Task.Delay(500).ConfigureAwait(false);
  110. await DeleteTempFiles(failedFiles, retryCount + 1).ConfigureAwait(false);
  111. }
  112. }
  113. protected virtual List<string> GetStreamFilePaths()
  114. {
  115. return new List<string> { TempFilePath };
  116. }
  117. public async Task CopyToAsync(Stream stream, CancellationToken cancellationToken)
  118. {
  119. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, LiveStreamCancellationTokenSource.Token).Token;
  120. // use non-async filestream on windows along with read due to https://github.com/dotnet/corefx/issues/6039
  121. var allowAsync = Environment.OSVersion.Platform != PlatformID.Win32NT;
  122. bool seekFile = (DateTime.UtcNow - DateOpened).TotalSeconds > 10;
  123. var nextFileInfo = GetNextFile(null);
  124. var nextFile = nextFileInfo.file;
  125. var isLastFile = nextFileInfo.isLastFile;
  126. while (!string.IsNullOrEmpty(nextFile))
  127. {
  128. var emptyReadLimit = isLastFile ? EmptyReadLimit : 1;
  129. await CopyFile(nextFile, seekFile, emptyReadLimit, allowAsync, stream, cancellationToken).ConfigureAwait(false);
  130. seekFile = false;
  131. nextFileInfo = GetNextFile(nextFile);
  132. nextFile = nextFileInfo.file;
  133. isLastFile = nextFileInfo.isLastFile;
  134. }
  135. Logger.LogInformation("Live Stream ended.");
  136. }
  137. private (string file, bool isLastFile) GetNextFile(string currentFile)
  138. {
  139. var files = GetStreamFilePaths();
  140. if (string.IsNullOrEmpty(currentFile))
  141. {
  142. return (files.Last(), true);
  143. }
  144. var nextIndex = files.FindIndex(i => string.Equals(i, currentFile, StringComparison.OrdinalIgnoreCase)) + 1;
  145. var isLastFile = nextIndex == files.Count - 1;
  146. return (files.ElementAtOrDefault(nextIndex), isLastFile);
  147. }
  148. private async Task CopyFile(string path, bool seekFile, int emptyReadLimit, bool allowAsync, Stream stream, CancellationToken cancellationToken)
  149. {
  150. using (var inputStream = GetInputStream(path, allowAsync))
  151. {
  152. if (seekFile)
  153. {
  154. TrySeek(inputStream, -20000);
  155. }
  156. await StreamHelper.CopyToAsync(
  157. inputStream,
  158. stream,
  159. StreamDefaults.DefaultCopyToBufferSize,
  160. emptyReadLimit,
  161. cancellationToken).ConfigureAwait(false);
  162. }
  163. }
  164. private void TrySeek(FileStream stream, long offset)
  165. {
  166. if (!stream.CanSeek)
  167. {
  168. return;
  169. }
  170. try
  171. {
  172. stream.Seek(offset, SeekOrigin.End);
  173. }
  174. catch (IOException)
  175. {
  176. }
  177. catch (ArgumentException)
  178. {
  179. }
  180. catch (Exception ex)
  181. {
  182. Logger.LogError(ex, "Error seeking stream");
  183. }
  184. }
  185. }
  186. }