TranscodingThrottler.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Common.Configuration;
  5. using MediaBrowser.Model.Configuration;
  6. using MediaBrowser.Model.IO;
  7. using Microsoft.Extensions.Logging;
  8. namespace MediaBrowser.Api.Playback
  9. {
  10. public class TranscodingThrottler : IDisposable
  11. {
  12. private readonly TranscodingJob _job;
  13. private readonly ILogger _logger;
  14. private Timer _timer;
  15. private bool _isPaused;
  16. private readonly IConfigurationManager _config;
  17. private readonly IFileSystem _fileSystem;
  18. public TranscodingThrottler(TranscodingJob job, ILogger logger, IConfigurationManager config, IFileSystem fileSystem)
  19. {
  20. _job = job;
  21. _logger = logger;
  22. _config = config;
  23. _fileSystem = fileSystem;
  24. }
  25. private EncodingOptions GetOptions()
  26. {
  27. return _config.GetConfiguration<EncodingOptions>("encoding");
  28. }
  29. public void Start()
  30. {
  31. _timer = new Timer(TimerCallback, null, 5000, 5000);
  32. }
  33. private async void TimerCallback(object state)
  34. {
  35. if (_job.HasExited)
  36. {
  37. DisposeTimer();
  38. return;
  39. }
  40. var options = GetOptions();
  41. if (options.EnableThrottling && IsThrottleAllowed(_job, options.ThrottleDelaySeconds))
  42. {
  43. await PauseTranscoding();
  44. }
  45. else
  46. {
  47. await UnpauseTranscoding();
  48. }
  49. }
  50. private async Task PauseTranscoding()
  51. {
  52. if (!_isPaused)
  53. {
  54. _logger.LogDebug("Sending pause command to ffmpeg");
  55. try
  56. {
  57. await _job.Process.StandardInput.WriteAsync("c");
  58. _isPaused = true;
  59. }
  60. catch (Exception ex)
  61. {
  62. _logger.LogError(ex, "Error pausing transcoding");
  63. }
  64. }
  65. }
  66. public async Task UnpauseTranscoding()
  67. {
  68. if (_isPaused)
  69. {
  70. _logger.LogDebug("Sending resume command to ffmpeg");
  71. try
  72. {
  73. await _job.Process.StandardInput.WriteLineAsync();
  74. _isPaused = false;
  75. }
  76. catch (Exception ex)
  77. {
  78. _logger.LogError(ex, "Error resuming transcoding");
  79. }
  80. }
  81. }
  82. private bool IsThrottleAllowed(TranscodingJob job, int thresholdSeconds)
  83. {
  84. var bytesDownloaded = job.BytesDownloaded ?? 0;
  85. var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0;
  86. var downloadPositionTicks = job.DownloadPositionTicks ?? 0;
  87. var path = job.Path;
  88. var gapLengthInTicks = TimeSpan.FromSeconds(thresholdSeconds).Ticks;
  89. if (downloadPositionTicks > 0 && transcodingPositionTicks > 0)
  90. {
  91. // HLS - time-based consideration
  92. var targetGap = gapLengthInTicks;
  93. var gap = transcodingPositionTicks - downloadPositionTicks;
  94. if (gap < targetGap)
  95. {
  96. _logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap);
  97. return false;
  98. }
  99. _logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
  100. return true;
  101. }
  102. if (bytesDownloaded > 0 && transcodingPositionTicks > 0)
  103. {
  104. // Progressive Streaming - byte-based consideration
  105. try
  106. {
  107. var bytesTranscoded = job.BytesTranscoded ?? _fileSystem.GetFileInfo(path).Length;
  108. // Estimate the bytes the transcoder should be ahead
  109. double gapFactor = gapLengthInTicks;
  110. gapFactor /= transcodingPositionTicks;
  111. var targetGap = bytesTranscoded * gapFactor;
  112. var gap = bytesTranscoded - bytesDownloaded;
  113. if (gap < targetGap)
  114. {
  115. _logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
  116. return false;
  117. }
  118. _logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
  119. return true;
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.LogError(ex, "Error getting output size");
  124. return false;
  125. }
  126. }
  127. _logger.LogDebug("No throttle data for " + path);
  128. return false;
  129. }
  130. public async Task Stop()
  131. {
  132. DisposeTimer();
  133. await UnpauseTranscoding();
  134. }
  135. public void Dispose()
  136. {
  137. DisposeTimer();
  138. }
  139. private void DisposeTimer()
  140. {
  141. if (_timer != null)
  142. {
  143. _timer.Dispose();
  144. _timer = null;
  145. }
  146. }
  147. }
  148. }