TranscodingThrottler.cs 6.5 KB

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