2
0

TranscodingThrottler.cs 6.7 KB

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