2
0

TranscodingThrottler.cs 7.2 KB

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