TranscodingJob.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4. using MediaBrowser.Model.Dto;
  5. using Microsoft.Extensions.Logging;
  6. namespace MediaBrowser.Controller.MediaEncoding;
  7. /// <summary>
  8. /// Class TranscodingJob.
  9. /// </summary>
  10. public sealed class TranscodingJob : IDisposable
  11. {
  12. private readonly ILogger<TranscodingJob> _logger;
  13. private readonly Lock _processLock = new();
  14. private readonly Lock _timerLock = new();
  15. private Timer? _killTimer;
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="TranscodingJob"/> class.
  18. /// </summary>
  19. /// <param name="logger">Instance of the <see cref="ILogger{TranscodingJobDto}"/> interface.</param>
  20. public TranscodingJob(ILogger<TranscodingJob> logger)
  21. {
  22. _logger = logger;
  23. }
  24. /// <summary>
  25. /// Gets or sets the play session identifier.
  26. /// </summary>
  27. public string? PlaySessionId { get; set; }
  28. /// <summary>
  29. /// Gets or sets the live stream identifier.
  30. /// </summary>
  31. public string? LiveStreamId { get; set; }
  32. /// <summary>
  33. /// Gets or sets a value indicating whether is live output.
  34. /// </summary>
  35. public bool IsLiveOutput { get; set; }
  36. /// <summary>
  37. /// Gets or sets the path.
  38. /// </summary>
  39. public MediaSourceInfo? MediaSource { get; set; }
  40. /// <summary>
  41. /// Gets or sets path.
  42. /// </summary>
  43. public string? Path { get; set; }
  44. /// <summary>
  45. /// Gets or sets the type.
  46. /// </summary>
  47. public TranscodingJobType Type { get; set; }
  48. /// <summary>
  49. /// Gets or sets the process.
  50. /// </summary>
  51. public Process? Process { get; set; }
  52. /// <summary>
  53. /// Gets or sets the active request count.
  54. /// </summary>
  55. public int ActiveRequestCount { get; set; }
  56. /// <summary>
  57. /// Gets or sets device id.
  58. /// </summary>
  59. public string? DeviceId { get; set; }
  60. /// <summary>
  61. /// Gets or sets cancellation token source.
  62. /// </summary>
  63. public CancellationTokenSource? CancellationTokenSource { get; set; }
  64. /// <summary>
  65. /// Gets or sets a value indicating whether has exited.
  66. /// </summary>
  67. public bool HasExited { get; set; }
  68. /// <summary>
  69. /// Gets or sets exit code.
  70. /// </summary>
  71. public int ExitCode { get; set; }
  72. /// <summary>
  73. /// Gets or sets a value indicating whether is user paused.
  74. /// </summary>
  75. public bool IsUserPaused { get; set; }
  76. /// <summary>
  77. /// Gets or sets id.
  78. /// </summary>
  79. public string? Id { get; set; }
  80. /// <summary>
  81. /// Gets or sets framerate.
  82. /// </summary>
  83. public float? Framerate { get; set; }
  84. /// <summary>
  85. /// Gets or sets completion percentage.
  86. /// </summary>
  87. public double? CompletionPercentage { get; set; }
  88. /// <summary>
  89. /// Gets or sets bytes downloaded.
  90. /// </summary>
  91. public long BytesDownloaded { get; set; }
  92. /// <summary>
  93. /// Gets or sets bytes transcoded.
  94. /// </summary>
  95. public long? BytesTranscoded { get; set; }
  96. /// <summary>
  97. /// Gets or sets bit rate.
  98. /// </summary>
  99. public int? BitRate { get; set; }
  100. /// <summary>
  101. /// Gets or sets transcoding position ticks.
  102. /// </summary>
  103. public long? TranscodingPositionTicks { get; set; }
  104. /// <summary>
  105. /// Gets or sets download position ticks.
  106. /// </summary>
  107. public long? DownloadPositionTicks { get; set; }
  108. /// <summary>
  109. /// Gets or sets transcoding throttler.
  110. /// </summary>
  111. public TranscodingThrottler? TranscodingThrottler { get; set; }
  112. /// <summary>
  113. /// Gets or sets transcoding segment cleaner.
  114. /// </summary>
  115. public TranscodingSegmentCleaner? TranscodingSegmentCleaner { get; set; }
  116. /// <summary>
  117. /// Gets or sets last ping date.
  118. /// </summary>
  119. public DateTime LastPingDate { get; set; }
  120. /// <summary>
  121. /// Gets or sets ping timeout.
  122. /// </summary>
  123. public int PingTimeout { get; set; }
  124. /// <summary>
  125. /// Stop kill timer.
  126. /// </summary>
  127. public void StopKillTimer()
  128. {
  129. lock (_timerLock)
  130. {
  131. _killTimer?.Change(Timeout.Infinite, Timeout.Infinite);
  132. }
  133. }
  134. /// <summary>
  135. /// Dispose kill timer.
  136. /// </summary>
  137. public void DisposeKillTimer()
  138. {
  139. lock (_timerLock)
  140. {
  141. if (_killTimer is not null)
  142. {
  143. _killTimer.Dispose();
  144. _killTimer = null;
  145. }
  146. }
  147. }
  148. /// <summary>
  149. /// Start kill timer.
  150. /// </summary>
  151. /// <param name="callback">Callback action.</param>
  152. public void StartKillTimer(Action<object?> callback)
  153. {
  154. StartKillTimer(callback, PingTimeout);
  155. }
  156. /// <summary>
  157. /// Start kill timer.
  158. /// </summary>
  159. /// <param name="callback">Callback action.</param>
  160. /// <param name="intervalMs">Callback interval.</param>
  161. public void StartKillTimer(Action<object?> callback, int intervalMs)
  162. {
  163. if (HasExited)
  164. {
  165. return;
  166. }
  167. lock (_timerLock)
  168. {
  169. if (_killTimer is null)
  170. {
  171. _logger.LogDebug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  172. _killTimer = new Timer(new TimerCallback(callback), this, intervalMs, Timeout.Infinite);
  173. }
  174. else
  175. {
  176. _logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  177. _killTimer.Change(intervalMs, Timeout.Infinite);
  178. }
  179. }
  180. }
  181. /// <summary>
  182. /// Change kill timer if started.
  183. /// </summary>
  184. public void ChangeKillTimerIfStarted()
  185. {
  186. if (HasExited)
  187. {
  188. return;
  189. }
  190. lock (_timerLock)
  191. {
  192. if (_killTimer is not null)
  193. {
  194. var intervalMs = PingTimeout;
  195. _logger.LogDebug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
  196. _killTimer.Change(intervalMs, Timeout.Infinite);
  197. }
  198. }
  199. }
  200. /// <summary>
  201. /// Stops the transcoding job.
  202. /// </summary>
  203. public void Stop()
  204. {
  205. lock (_processLock)
  206. {
  207. #pragma warning disable CA1849 // Can't await in lock block
  208. TranscodingThrottler?.Stop().GetAwaiter().GetResult();
  209. TranscodingSegmentCleaner?.Stop();
  210. var process = Process;
  211. if (!HasExited)
  212. {
  213. try
  214. {
  215. _logger.LogInformation("Stopping ffmpeg process with q command for {Path}", Path);
  216. process!.StandardInput.WriteLine("q");
  217. // Need to wait because killing is asynchronous.
  218. if (!process.WaitForExit(5000))
  219. {
  220. _logger.LogInformation("Killing FFmpeg process for {Path}", Path);
  221. process.Kill();
  222. }
  223. }
  224. catch (InvalidOperationException)
  225. {
  226. }
  227. }
  228. #pragma warning restore CA1849
  229. }
  230. }
  231. /// <inheritdoc />
  232. public void Dispose()
  233. {
  234. Process?.Dispose();
  235. Process = null;
  236. _killTimer?.Dispose();
  237. _killTimer = null;
  238. CancellationTokenSource?.Dispose();
  239. CancellationTokenSource = null;
  240. TranscodingThrottler?.Dispose();
  241. TranscodingThrottler = null;
  242. TranscodingSegmentCleaner?.Dispose();
  243. TranscodingSegmentCleaner = null;
  244. }
  245. }