ProgressiveStreamWriter.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using CommonIO;
  7. namespace MediaBrowser.Api.Playback.Progressive
  8. {
  9. public class ProgressiveFileCopier
  10. {
  11. private readonly IFileSystem _fileSystem;
  12. private readonly TranscodingJob _job;
  13. private readonly ILogger _logger;
  14. // 256k
  15. private const int BufferSize = 81920;
  16. private long _bytesWritten = 0;
  17. public ProgressiveFileCopier(IFileSystem fileSystem, TranscodingJob job, ILogger logger)
  18. {
  19. _fileSystem = fileSystem;
  20. _job = job;
  21. _logger = logger;
  22. }
  23. public async Task StreamFile(string path, Stream outputStream, CancellationToken cancellationToken)
  24. {
  25. var eofCount = 0;
  26. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  27. {
  28. while (eofCount < 15)
  29. {
  30. var bytesRead = await CopyToAsyncInternal(fs, outputStream, BufferSize, cancellationToken).ConfigureAwait(false);
  31. //var position = fs.Position;
  32. //_logger.Debug("Streamed {0} bytes to position {1} from file {2}", bytesRead, position, path);
  33. if (bytesRead == 0)
  34. {
  35. if (_job == null || _job.HasExited)
  36. {
  37. eofCount++;
  38. }
  39. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  40. }
  41. else
  42. {
  43. eofCount = 0;
  44. }
  45. }
  46. }
  47. }
  48. private async Task<int> CopyToAsyncInternal(Stream source, Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
  49. {
  50. byte[] buffer = new byte[bufferSize];
  51. int bytesRead;
  52. int totalBytesRead = 0;
  53. while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0)
  54. {
  55. await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
  56. _bytesWritten += bytesRead;
  57. totalBytesRead += bytesRead;
  58. if (_job != null)
  59. {
  60. _job.BytesDownloaded = Math.Max(_job.BytesDownloaded ?? _bytesWritten, _bytesWritten);
  61. }
  62. }
  63. return totalBytesRead;
  64. }
  65. }
  66. }