DirectRecorder.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MediaBrowser.Model.IO;
  6. using MediaBrowser.Common.Net;
  7. using MediaBrowser.Controller.IO;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Logging;
  11. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  12. {
  13. public class DirectRecorder : IRecorder
  14. {
  15. private readonly ILogger _logger;
  16. private readonly IHttpClient _httpClient;
  17. private readonly IFileSystem _fileSystem;
  18. public DirectRecorder(ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  19. {
  20. _logger = logger;
  21. _httpClient = httpClient;
  22. _fileSystem = fileSystem;
  23. }
  24. public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile)
  25. {
  26. return targetFile;
  27. }
  28. public Task Record(IDirectStreamProvider directStreamProvider, MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  29. {
  30. if (directStreamProvider != null)
  31. {
  32. return RecordFromDirectStreamProvider(directStreamProvider, targetFile, duration, onStarted, cancellationToken);
  33. }
  34. return RecordFromMediaSource(mediaSource, targetFile, duration, onStarted, cancellationToken);
  35. }
  36. private async Task RecordFromDirectStreamProvider(IDirectStreamProvider directStreamProvider, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  37. {
  38. using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  39. {
  40. onStarted();
  41. _logger.Info("Copying recording stream to file {0}", targetFile);
  42. // The media source if infinite so we need to handle stopping ourselves
  43. var durationToken = new CancellationTokenSource(duration);
  44. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  45. await directStreamProvider.CopyToAsync(output, cancellationToken).ConfigureAwait(false);
  46. }
  47. _logger.Info("Recording completed to file {0}", targetFile);
  48. }
  49. private async Task RecordFromMediaSource(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken)
  50. {
  51. var httpRequestOptions = new HttpRequestOptions
  52. {
  53. Url = mediaSource.Path,
  54. BufferContent = false,
  55. // Some remote urls will expect a user agent to be supplied
  56. UserAgent = "Emby/3.0",
  57. // Shouldn't matter but may cause issues
  58. EnableHttpCompression = false
  59. };
  60. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
  61. {
  62. _logger.Info("Opened recording stream from tuner provider");
  63. using (var output = _fileSystem.GetFileStream(targetFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  64. {
  65. onStarted();
  66. _logger.Info("Copying recording stream to file {0}", targetFile);
  67. // The media source if infinite so we need to handle stopping ourselves
  68. var durationToken = new CancellationTokenSource(duration);
  69. cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  70. await CopyUntilCancelled(response.Content, output, cancellationToken).ConfigureAwait(false);
  71. }
  72. }
  73. _logger.Info("Recording completed to file {0}", targetFile);
  74. }
  75. private const int BufferSize = 81920;
  76. public static Task CopyUntilCancelled(Stream source, Stream target, CancellationToken cancellationToken)
  77. {
  78. return CopyUntilCancelled(source, target, null, cancellationToken);
  79. }
  80. public static async Task CopyUntilCancelled(Stream source, Stream target, Action onStarted, CancellationToken cancellationToken)
  81. {
  82. while (!cancellationToken.IsCancellationRequested)
  83. {
  84. var bytesRead = await CopyToAsyncInternal(source, target, BufferSize, onStarted, cancellationToken).ConfigureAwait(false);
  85. onStarted = null;
  86. //var position = fs.Position;
  87. //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
  88. if (bytesRead == 0)
  89. {
  90. await Task.Delay(100).ConfigureAwait(false);
  91. }
  92. }
  93. }
  94. private static async Task<int> CopyToAsyncInternal(Stream source, Stream destination, Int32 bufferSize, Action onStarted, CancellationToken cancellationToken)
  95. {
  96. byte[] buffer = new byte[bufferSize];
  97. int bytesRead;
  98. int totalBytesRead = 0;
  99. while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
  100. {
  101. await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
  102. totalBytesRead += bytesRead;
  103. if (onStarted != null)
  104. {
  105. onStarted();
  106. }
  107. onStarted = null;
  108. }
  109. return totalBytesRead;
  110. }
  111. }
  112. }