2
0

JellyfinApiEntryPoint.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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.TranscodingDtos;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Plugins;
  13. using MediaBrowser.Controller.Session;
  14. using MediaBrowser.Model.IO;
  15. using Microsoft.Extensions.Logging;
  16. namespace Jellyfin.Api
  17. {
  18. /// <summary>
  19. /// The jellyfin api entry point.
  20. /// </summary>
  21. public class JellyfinApiEntryPoint : IServerEntryPoint
  22. {
  23. private readonly ILogger _logger;
  24. private readonly IServerConfigurationManager _serverConfigurationManager;
  25. private readonly ISessionManager _sessionManager;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly IMediaSourceManager _mediaSourceManager;
  28. private readonly List<TranscodingJob> _activeTranscodingJobs;
  29. private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks;
  30. private bool _disposed = false;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="JellyfinApiEntryPoint" /> class.
  33. /// </summary>
  34. /// <param name="logger">The logger.</param>
  35. /// <param name="sessionManager">The session manager.</param>
  36. /// <param name="config">The configuration.</param>
  37. /// <param name="fileSystem">The file system.</param>
  38. /// <param name="mediaSourceManager">The media source manager.</param>
  39. public JellyfinApiEntryPoint(
  40. ILogger<JellyfinApiEntryPoint> logger,
  41. ISessionManager sessionManager,
  42. IServerConfigurationManager config,
  43. IFileSystem fileSystem,
  44. IMediaSourceManager mediaSourceManager)
  45. {
  46. _logger = logger;
  47. _sessionManager = sessionManager;
  48. _serverConfigurationManager = config;
  49. _fileSystem = fileSystem;
  50. _mediaSourceManager = mediaSourceManager;
  51. _activeTranscodingJobs = new List<TranscodingJob>();
  52. _transcodingLocks = new Dictionary<string, SemaphoreSlim>();
  53. _sessionManager!.PlaybackProgress += OnPlaybackProgress;
  54. _sessionManager!.PlaybackStart += OnPlaybackProgress;
  55. Instance = this;
  56. }
  57. /// <summary>
  58. /// Gets the initialized instance of <see cref="JellyfinApiEntryPoint"/>.
  59. /// </summary>
  60. public static JellyfinApiEntryPoint? Instance { get; private set; }
  61. /// <inheritdoc />
  62. public void Dispose()
  63. {
  64. Dispose(true);
  65. GC.SuppressFinalize(this);
  66. }
  67. /// <summary>
  68. /// Releases unmanaged and - optionally - managed resources.
  69. /// </summary>
  70. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  71. protected virtual void Dispose(bool dispose)
  72. {
  73. if (_disposed)
  74. {
  75. return;
  76. }
  77. if (dispose)
  78. {
  79. // TODO: dispose
  80. }
  81. List<TranscodingJob> jobs;
  82. lock (_activeTranscodingJobs)
  83. {
  84. jobs = _activeTranscodingJobs.ToList();
  85. }
  86. var jobCount = jobs.Count;
  87. IEnumerable<Task> GetKillJobs()
  88. {
  89. foreach (var job in jobs)
  90. {
  91. yield return KillTranscodingJob(job, false, path => true);
  92. }
  93. }
  94. // Wait for all processes to be killed
  95. if (jobCount > 0)
  96. {
  97. Task.WaitAll(GetKillJobs().ToArray());
  98. }
  99. lock (_activeTranscodingJobs)
  100. {
  101. _activeTranscodingJobs.Clear();
  102. }
  103. lock (_transcodingLocks)
  104. {
  105. _transcodingLocks.Clear();
  106. }
  107. _sessionManager.PlaybackProgress -= OnPlaybackProgress;
  108. _sessionManager.PlaybackStart -= OnPlaybackProgress;
  109. _disposed = true;
  110. }
  111. /// <inheritdoc />
  112. public Task RunAsync()
  113. {
  114. try
  115. {
  116. DeleteEncodedMediaCache();
  117. }
  118. catch (Exception ex)
  119. {
  120. _logger.LogError(ex, "Error deleting encoded media cache");
  121. }
  122. return Task.CompletedTask;
  123. }
  124. private void OnPlaybackProgress(object sender, PlaybackProgressEventArgs e)
  125. {
  126. if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
  127. {
  128. PingTranscodingJob(e.PlaySessionId, e.IsPaused);
  129. }
  130. }
  131. /// <summary>
  132. /// Deletes the encoded media cache.
  133. /// </summary>
  134. private void DeleteEncodedMediaCache()
  135. {
  136. var path = _serverConfigurationManager.GetTranscodePath();
  137. if (!Directory.Exists(path))
  138. {
  139. return;
  140. }
  141. foreach (var file in _fileSystem.GetFilePaths(path, true))
  142. {
  143. _fileSystem.DeleteFile(file);
  144. }
  145. }
  146. internal void PingTranscodingJob(string playSessionId, bool? isUserPaused)
  147. {
  148. if (string.IsNullOrEmpty(playSessionId))
  149. {
  150. throw new ArgumentNullException(nameof(playSessionId));
  151. }
  152. _logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
  153. List<TranscodingJob> jobs;
  154. lock (_activeTranscodingJobs)
  155. {
  156. // This is really only needed for HLS.
  157. // Progressive streams can stop on their own reliably
  158. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
  159. }
  160. foreach (var job in jobs)
  161. {
  162. if (isUserPaused.HasValue)
  163. {
  164. _logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
  165. job.IsUserPaused = isUserPaused.Value;
  166. }
  167. PingTimer(job, true);
  168. }
  169. }
  170. private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
  171. {
  172. if (job.HasExited)
  173. {
  174. job.StopKillTimer();
  175. return;
  176. }
  177. var timerDuration = 10000;
  178. if (job.Type != TranscodingJobType.Progressive)
  179. {
  180. timerDuration = 60000;
  181. }
  182. job.PingTimeout = timerDuration;
  183. job.LastPingDate = DateTime.UtcNow;
  184. // Don't start the timer for playback checkins with progressive streaming
  185. if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
  186. {
  187. job.StartKillTimer(OnTranscodeKillTimerStopped);
  188. }
  189. else
  190. {
  191. job.ChangeKillTimerIfStarted();
  192. }
  193. }
  194. /// <summary>
  195. /// Called when [transcode kill timer stopped].
  196. /// </summary>
  197. /// <param name="state">The state.</param>
  198. private async void OnTranscodeKillTimerStopped(object state)
  199. {
  200. var job = (TranscodingJob)state;
  201. if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
  202. {
  203. var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
  204. if (timeSinceLastPing < job.PingTimeout)
  205. {
  206. job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
  207. return;
  208. }
  209. }
  210. _logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  211. await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
  212. }
  213. /// <summary>
  214. /// Kills the transcoding job.
  215. /// </summary>
  216. /// <param name="job">The job.</param>
  217. /// <param name="closeLiveStream">if set to <c>true</c> [close live stream].</param>
  218. /// <param name="delete">The delete.</param>
  219. private async Task KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
  220. {
  221. job.DisposeKillTimer();
  222. _logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  223. lock (_activeTranscodingJobs)
  224. {
  225. _activeTranscodingJobs.Remove(job);
  226. if (!job.CancellationTokenSource!.IsCancellationRequested)
  227. {
  228. job.CancellationTokenSource.Cancel();
  229. }
  230. }
  231. lock (_transcodingLocks)
  232. {
  233. _transcodingLocks.Remove(job.Path!);
  234. }
  235. lock (job)
  236. {
  237. job.TranscodingThrottler?.Stop().GetAwaiter().GetResult();
  238. var process = job.Process;
  239. var hasExited = job.HasExited;
  240. if (!hasExited)
  241. {
  242. try
  243. {
  244. _logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
  245. process?.StandardInput.WriteLine("q");
  246. // Need to wait (an arbitrary amount of time) because killing is asynchronous
  247. if (!process!.WaitForExit(5000))
  248. {
  249. _logger.LogInformation("Killing ffmpeg process for {Path}", job.Path);
  250. process.Kill();
  251. }
  252. }
  253. catch (InvalidOperationException)
  254. {
  255. }
  256. }
  257. }
  258. if (delete(job.Path!))
  259. {
  260. await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
  261. }
  262. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  263. {
  264. try
  265. {
  266. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
  267. }
  268. catch (Exception ex)
  269. {
  270. _logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
  271. }
  272. }
  273. }
  274. private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  275. {
  276. if (retryCount >= 10)
  277. {
  278. return;
  279. }
  280. _logger.LogInformation("Deleting partial stream file(s) {Path}", path);
  281. await Task.Delay(delayMs).ConfigureAwait(false);
  282. try
  283. {
  284. if (jobType == TranscodingJobType.Progressive)
  285. {
  286. DeleteProgressivePartialStreamFiles(path);
  287. }
  288. else
  289. {
  290. DeleteHlsPartialStreamFiles(path);
  291. }
  292. }
  293. catch (IOException ex)
  294. {
  295. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  296. await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
  297. }
  298. catch (Exception ex)
  299. {
  300. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  301. }
  302. }
  303. /// <summary>
  304. /// Deletes the progressive partial stream files.
  305. /// </summary>
  306. /// <param name="outputFilePath">The output file path.</param>
  307. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  308. {
  309. if (File.Exists(outputFilePath))
  310. {
  311. _fileSystem.DeleteFile(outputFilePath);
  312. }
  313. }
  314. /// <summary>
  315. /// Deletes the HLS partial stream files.
  316. /// </summary>
  317. /// <param name="outputFilePath">The output file path.</param>
  318. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  319. {
  320. var directory = Path.GetDirectoryName(outputFilePath);
  321. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  322. var filesToDelete = _fileSystem.GetFilePaths(directory)
  323. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
  324. List<Exception>? exs = null;
  325. foreach (var file in filesToDelete)
  326. {
  327. try
  328. {
  329. _logger.LogDebug("Deleting HLS file {0}", file);
  330. _fileSystem.DeleteFile(file);
  331. }
  332. catch (IOException ex)
  333. {
  334. (exs ??= new List<Exception>(4)).Add(ex);
  335. _logger.LogError(ex, "Error deleting HLS file {Path}", file);
  336. }
  337. }
  338. if (exs != null)
  339. {
  340. throw new AggregateException("Error deleting HLS files", exs);
  341. }
  342. }
  343. }
  344. }