TranscodingThrottler.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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.Controller.MediaEncoding;
  9. /// <summary>
  10. /// Transcoding throttler.
  11. /// </summary>
  12. public class TranscodingThrottler : IDisposable
  13. {
  14. private readonly TranscodingJob _job;
  15. private readonly ILogger<TranscodingThrottler> _logger;
  16. private readonly IConfigurationManager _config;
  17. private readonly IFileSystem _fileSystem;
  18. private readonly IMediaEncoder _mediaEncoder;
  19. private Timer? _timer;
  20. private bool _isPaused;
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="TranscodingThrottler"/> class.
  23. /// </summary>
  24. /// <param name="job">Transcoding job dto.</param>
  25. /// <param name="logger">Instance of the <see cref="ILogger{TranscodingThrottler}"/> interface.</param>
  26. /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param>
  27. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  28. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  29. public TranscodingThrottler(TranscodingJob job, ILogger<TranscodingThrottler> logger, IConfigurationManager config, IFileSystem fileSystem, IMediaEncoder mediaEncoder)
  30. {
  31. _job = job;
  32. _logger = logger;
  33. _config = config;
  34. _fileSystem = fileSystem;
  35. _mediaEncoder = mediaEncoder;
  36. }
  37. /// <summary>
  38. /// Start timer.
  39. /// </summary>
  40. public void Start()
  41. {
  42. _timer = new Timer(TimerCallback, null, 5000, 5000);
  43. }
  44. /// <summary>
  45. /// Unpause transcoding.
  46. /// </summary>
  47. /// <returns>A <see cref="Task"/>.</returns>
  48. public async Task UnpauseTranscoding()
  49. {
  50. if (_isPaused)
  51. {
  52. _logger.LogDebug("Sending resume command to ffmpeg");
  53. try
  54. {
  55. var resumeKey = _mediaEncoder.IsPkeyPauseSupported ? "u" : Environment.NewLine;
  56. await _job.Process!.StandardInput.WriteAsync(resumeKey).ConfigureAwait(false);
  57. _isPaused = false;
  58. }
  59. catch (Exception ex)
  60. {
  61. _logger.LogError(ex, "Error resuming transcoding");
  62. }
  63. }
  64. }
  65. /// <summary>
  66. /// Stop throttler.
  67. /// </summary>
  68. /// <returns>A <see cref="Task"/>.</returns>
  69. public async Task Stop()
  70. {
  71. DisposeTimer();
  72. await UnpauseTranscoding().ConfigureAwait(false);
  73. }
  74. /// <summary>
  75. /// Dispose throttler.
  76. /// </summary>
  77. public void Dispose()
  78. {
  79. Dispose(true);
  80. GC.SuppressFinalize(this);
  81. }
  82. /// <summary>
  83. /// Dispose throttler.
  84. /// </summary>
  85. /// <param name="disposing">Disposing.</param>
  86. protected virtual void Dispose(bool disposing)
  87. {
  88. if (disposing)
  89. {
  90. DisposeTimer();
  91. }
  92. }
  93. private EncodingOptions GetOptions()
  94. {
  95. return _config.GetEncodingOptions();
  96. }
  97. private async void TimerCallback(object? state)
  98. {
  99. if (_job.HasExited)
  100. {
  101. DisposeTimer();
  102. return;
  103. }
  104. var options = GetOptions();
  105. if (options.EnableThrottling && IsThrottleAllowed(_job, Math.Max(options.ThrottleDelaySeconds, 60)))
  106. {
  107. await PauseTranscoding().ConfigureAwait(false);
  108. }
  109. else
  110. {
  111. await UnpauseTranscoding().ConfigureAwait(false);
  112. }
  113. }
  114. private async Task PauseTranscoding()
  115. {
  116. if (!_isPaused)
  117. {
  118. var pauseKey = _mediaEncoder.IsPkeyPauseSupported ? "p" : "c";
  119. _logger.LogDebug("Sending pause command [{Key}] to ffmpeg", pauseKey);
  120. try
  121. {
  122. await _job.Process!.StandardInput.WriteAsync(pauseKey).ConfigureAwait(false);
  123. _isPaused = true;
  124. }
  125. catch (Exception ex)
  126. {
  127. _logger.LogError(ex, "Error pausing transcoding");
  128. }
  129. }
  130. }
  131. private bool IsThrottleAllowed(TranscodingJob job, int thresholdSeconds)
  132. {
  133. var bytesDownloaded = job.BytesDownloaded;
  134. var transcodingPositionTicks = job.TranscodingPositionTicks ?? 0;
  135. var downloadPositionTicks = job.DownloadPositionTicks ?? 0;
  136. var path = job.Path ?? throw new ArgumentException("Path can't be null.");
  137. var gapLengthInTicks = TimeSpan.FromSeconds(thresholdSeconds).Ticks;
  138. if (downloadPositionTicks > 0 && transcodingPositionTicks > 0)
  139. {
  140. // HLS - time-based consideration
  141. var targetGap = gapLengthInTicks;
  142. var gap = transcodingPositionTicks - downloadPositionTicks;
  143. if (gap < targetGap)
  144. {
  145. _logger.LogDebug("Not throttling transcoder gap {0} target gap {1}", gap, targetGap);
  146. return false;
  147. }
  148. _logger.LogDebug("Throttling transcoder gap {0} target gap {1}", gap, targetGap);
  149. return true;
  150. }
  151. if (bytesDownloaded > 0 && transcodingPositionTicks > 0)
  152. {
  153. // Progressive Streaming - byte-based consideration
  154. try
  155. {
  156. var bytesTranscoded = job.BytesTranscoded ?? _fileSystem.GetFileInfo(path).Length;
  157. // Estimate the bytes the transcoder should be ahead
  158. double gapFactor = gapLengthInTicks;
  159. gapFactor /= transcodingPositionTicks;
  160. var targetGap = bytesTranscoded * gapFactor;
  161. var gap = bytesTranscoded - bytesDownloaded;
  162. if (gap < targetGap)
  163. {
  164. _logger.LogDebug("Not throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
  165. return false;
  166. }
  167. _logger.LogDebug("Throttling transcoder gap {0} target gap {1} bytes downloaded {2}", gap, targetGap, bytesDownloaded);
  168. return true;
  169. }
  170. catch (Exception ex)
  171. {
  172. _logger.LogError(ex, "Error getting output size");
  173. return false;
  174. }
  175. }
  176. _logger.LogDebug("No throttle data for {Path}", path);
  177. return false;
  178. }
  179. private void DisposeTimer()
  180. {
  181. if (_timer is not null)
  182. {
  183. _timer.Dispose();
  184. _timer = null;
  185. }
  186. }
  187. }