TranscodingThrottler.cs 5.4 KB

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