TranscodingJobHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Api.Models.PlaybackDtos;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using MediaBrowser.Model.IO;
  11. using Microsoft.Extensions.Logging;
  12. namespace Jellyfin.Api.Helpers
  13. {
  14. /// <summary>
  15. /// Transcoding job helpers.
  16. /// </summary>
  17. public class TranscodingJobHelper
  18. {
  19. /// <summary>
  20. /// The active transcoding jobs.
  21. /// </summary>
  22. private static readonly List<TranscodingJobDto> _activeTranscodingJobs = new List<TranscodingJobDto>();
  23. /// <summary>
  24. /// The transcoding locks.
  25. /// </summary>
  26. private static readonly Dictionary<string, SemaphoreSlim> _transcodingLocks = new Dictionary<string, SemaphoreSlim>();
  27. private readonly ILogger<TranscodingJobHelper> _logger;
  28. private readonly IMediaSourceManager _mediaSourceManager;
  29. private readonly IFileSystem _fileSystem;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="TranscodingJobHelper"/> class.
  32. /// </summary>
  33. /// <param name="logger">Instance of the <see cref="ILogger{TranscodingJobHelpers}"/> interface.</param>
  34. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  35. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  36. public TranscodingJobHelper(
  37. ILogger<TranscodingJobHelper> logger,
  38. IMediaSourceManager mediaSourceManager,
  39. IFileSystem fileSystem)
  40. {
  41. _logger = logger;
  42. _mediaSourceManager = mediaSourceManager;
  43. _fileSystem = fileSystem;
  44. }
  45. /// <summary>
  46. /// Get transcoding job.
  47. /// </summary>
  48. /// <param name="playSessionId">Playback session id.</param>
  49. /// <returns>The transcoding job.</returns>
  50. public TranscodingJobDto GetTranscodingJob(string playSessionId)
  51. {
  52. lock (_activeTranscodingJobs)
  53. {
  54. return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
  55. }
  56. }
  57. /// <summary>
  58. /// Ping transcoding job.
  59. /// </summary>
  60. /// <param name="playSessionId">Play session id.</param>
  61. /// <param name="isUserPaused">Is user paused.</param>
  62. /// <exception cref="ArgumentNullException">Play session id is null.</exception>
  63. public void PingTranscodingJob(string playSessionId, bool? isUserPaused)
  64. {
  65. if (string.IsNullOrEmpty(playSessionId))
  66. {
  67. throw new ArgumentNullException(nameof(playSessionId));
  68. }
  69. _logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
  70. List<TranscodingJobDto> jobs;
  71. lock (_activeTranscodingJobs)
  72. {
  73. // This is really only needed for HLS.
  74. // Progressive streams can stop on their own reliably
  75. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
  76. }
  77. foreach (var job in jobs)
  78. {
  79. if (isUserPaused.HasValue)
  80. {
  81. _logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
  82. job.IsUserPaused = isUserPaused.Value;
  83. }
  84. PingTimer(job, true);
  85. }
  86. }
  87. private void PingTimer(TranscodingJobDto job, bool isProgressCheckIn)
  88. {
  89. if (job.HasExited)
  90. {
  91. job.StopKillTimer();
  92. return;
  93. }
  94. var timerDuration = 10000;
  95. if (job.Type != TranscodingJobType.Progressive)
  96. {
  97. timerDuration = 60000;
  98. }
  99. job.PingTimeout = timerDuration;
  100. job.LastPingDate = DateTime.UtcNow;
  101. // Don't start the timer for playback checkins with progressive streaming
  102. if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
  103. {
  104. job.StartKillTimer(OnTranscodeKillTimerStopped);
  105. }
  106. else
  107. {
  108. job.ChangeKillTimerIfStarted();
  109. }
  110. }
  111. /// <summary>
  112. /// Called when [transcode kill timer stopped].
  113. /// </summary>
  114. /// <param name="state">The state.</param>
  115. private async void OnTranscodeKillTimerStopped(object state)
  116. {
  117. var job = (TranscodingJobDto)state;
  118. if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
  119. {
  120. var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
  121. if (timeSinceLastPing < job.PingTimeout)
  122. {
  123. job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
  124. return;
  125. }
  126. }
  127. _logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  128. await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
  129. }
  130. /// <summary>
  131. /// Kills the single transcoding job.
  132. /// </summary>
  133. /// <param name="deviceId">The device id.</param>
  134. /// <param name="playSessionId">The play session identifier.</param>
  135. /// <param name="deleteFiles">The delete files.</param>
  136. /// <returns>Task.</returns>
  137. public Task KillTranscodingJobs(string deviceId, string playSessionId, Func<string, bool> deleteFiles)
  138. {
  139. return KillTranscodingJobs(
  140. j => string.IsNullOrWhiteSpace(playSessionId)
  141. ? string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase)
  142. : string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase), deleteFiles);
  143. }
  144. /// <summary>
  145. /// Kills the transcoding jobs.
  146. /// </summary>
  147. /// <param name="killJob">The kill job.</param>
  148. /// <param name="deleteFiles">The delete files.</param>
  149. /// <returns>Task.</returns>
  150. private Task KillTranscodingJobs(Func<TranscodingJobDto, bool> killJob, Func<string, bool> deleteFiles)
  151. {
  152. var jobs = new List<TranscodingJobDto>();
  153. lock (_activeTranscodingJobs)
  154. {
  155. // This is really only needed for HLS.
  156. // Progressive streams can stop on their own reliably
  157. jobs.AddRange(_activeTranscodingJobs.Where(killJob));
  158. }
  159. if (jobs.Count == 0)
  160. {
  161. return Task.CompletedTask;
  162. }
  163. IEnumerable<Task> GetKillJobs()
  164. {
  165. foreach (var job in jobs)
  166. {
  167. yield return KillTranscodingJob(job, false, deleteFiles);
  168. }
  169. }
  170. return Task.WhenAll(GetKillJobs());
  171. }
  172. /// <summary>
  173. /// Kills the transcoding job.
  174. /// </summary>
  175. /// <param name="job">The job.</param>
  176. /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
  177. /// <param name="delete">The delete.</param>
  178. private async Task KillTranscodingJob(TranscodingJobDto job, bool closeLiveStream, Func<string, bool> delete)
  179. {
  180. job.DisposeKillTimer();
  181. _logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  182. lock (_activeTranscodingJobs)
  183. {
  184. _activeTranscodingJobs.Remove(job);
  185. if (!job.CancellationTokenSource!.IsCancellationRequested)
  186. {
  187. job.CancellationTokenSource.Cancel();
  188. }
  189. }
  190. lock (_transcodingLocks)
  191. {
  192. _transcodingLocks.Remove(job.Path!);
  193. }
  194. lock (job.ProcessLock!)
  195. {
  196. job.TranscodingThrottler?.Stop().GetAwaiter().GetResult();
  197. var process = job.Process;
  198. var hasExited = job.HasExited;
  199. if (!hasExited)
  200. {
  201. try
  202. {
  203. _logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
  204. process!.StandardInput.WriteLine("q");
  205. // Need to wait because killing is asynchronous
  206. if (!process.WaitForExit(5000))
  207. {
  208. _logger.LogInformation("Killing ffmpeg process for {Path}", job.Path);
  209. process.Kill();
  210. }
  211. }
  212. catch (InvalidOperationException)
  213. {
  214. }
  215. }
  216. }
  217. if (delete(job.Path!))
  218. {
  219. await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
  220. }
  221. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  222. {
  223. try
  224. {
  225. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
  226. }
  227. catch (Exception ex)
  228. {
  229. _logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
  230. }
  231. }
  232. }
  233. private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  234. {
  235. if (retryCount >= 10)
  236. {
  237. return;
  238. }
  239. _logger.LogInformation("Deleting partial stream file(s) {Path}", path);
  240. await Task.Delay(delayMs).ConfigureAwait(false);
  241. try
  242. {
  243. if (jobType == TranscodingJobType.Progressive)
  244. {
  245. DeleteProgressivePartialStreamFiles(path);
  246. }
  247. else
  248. {
  249. DeleteHlsPartialStreamFiles(path);
  250. }
  251. }
  252. catch (IOException ex)
  253. {
  254. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  255. await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
  256. }
  257. catch (Exception ex)
  258. {
  259. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  260. }
  261. }
  262. /// <summary>
  263. /// Deletes the progressive partial stream files.
  264. /// </summary>
  265. /// <param name="outputFilePath">The output file path.</param>
  266. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  267. {
  268. if (File.Exists(outputFilePath))
  269. {
  270. _fileSystem.DeleteFile(outputFilePath);
  271. }
  272. }
  273. /// <summary>
  274. /// Deletes the HLS partial stream files.
  275. /// </summary>
  276. /// <param name="outputFilePath">The output file path.</param>
  277. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  278. {
  279. var directory = Path.GetDirectoryName(outputFilePath);
  280. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  281. var filesToDelete = _fileSystem.GetFilePaths(directory)
  282. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
  283. List<Exception>? exs = null;
  284. foreach (var file in filesToDelete)
  285. {
  286. try
  287. {
  288. _logger.LogDebug("Deleting HLS file {0}", file);
  289. _fileSystem.DeleteFile(file);
  290. }
  291. catch (IOException ex)
  292. {
  293. (exs ??= new List<Exception>(4)).Add(ex);
  294. _logger.LogError(ex, "Error deleting HLS file {Path}", file);
  295. }
  296. }
  297. if (exs != null)
  298. {
  299. throw new AggregateException("Error deleting HLS files", exs);
  300. }
  301. }
  302. }
  303. }