TranscodeManager.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Data.Enums;
  12. using MediaBrowser.Common;
  13. using MediaBrowser.Common.Configuration;
  14. using MediaBrowser.Common.Extensions;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.MediaEncoding;
  18. using MediaBrowser.Controller.Session;
  19. using MediaBrowser.Controller.Streaming;
  20. using MediaBrowser.Model.Dlna;
  21. using MediaBrowser.Model.Entities;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.MediaInfo;
  24. using MediaBrowser.Model.Session;
  25. using Microsoft.Extensions.Logging;
  26. namespace MediaBrowser.MediaEncoding.Transcoding;
  27. /// <inheritdoc cref="ITranscodeManager"/>
  28. public sealed class TranscodeManager : ITranscodeManager, IDisposable
  29. {
  30. private readonly ILoggerFactory _loggerFactory;
  31. private readonly ILogger<TranscodeManager> _logger;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IApplicationPaths _appPaths;
  34. private readonly IServerConfigurationManager _serverConfigurationManager;
  35. private readonly IUserManager _userManager;
  36. private readonly ISessionManager _sessionManager;
  37. private readonly EncodingHelper _encodingHelper;
  38. private readonly IMediaEncoder _mediaEncoder;
  39. private readonly IMediaSourceManager _mediaSourceManager;
  40. private readonly IAttachmentExtractor _attachmentExtractor;
  41. private readonly List<TranscodingJob> _activeTranscodingJobs = new();
  42. private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks = new();
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="TranscodeManager"/> class.
  45. /// </summary>
  46. /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
  47. /// <param name="fileSystem">The <see cref="IFileSystem"/>.</param>
  48. /// <param name="appPaths">The <see cref="IApplicationPaths"/>.</param>
  49. /// <param name="serverConfigurationManager">The <see cref="IServerConfigurationManager"/>.</param>
  50. /// <param name="userManager">The <see cref="IUserManager"/>.</param>
  51. /// <param name="sessionManager">The <see cref="ISessionManager"/>.</param>
  52. /// <param name="encodingHelper">The <see cref="EncodingHelper"/>.</param>
  53. /// <param name="mediaEncoder">The <see cref="IMediaEncoder"/>.</param>
  54. /// <param name="mediaSourceManager">The <see cref="IMediaSourceManager"/>.</param>
  55. /// <param name="attachmentExtractor">The <see cref="IAttachmentExtractor"/>.</param>
  56. public TranscodeManager(
  57. ILoggerFactory loggerFactory,
  58. IFileSystem fileSystem,
  59. IApplicationPaths appPaths,
  60. IServerConfigurationManager serverConfigurationManager,
  61. IUserManager userManager,
  62. ISessionManager sessionManager,
  63. EncodingHelper encodingHelper,
  64. IMediaEncoder mediaEncoder,
  65. IMediaSourceManager mediaSourceManager,
  66. IAttachmentExtractor attachmentExtractor)
  67. {
  68. _loggerFactory = loggerFactory;
  69. _fileSystem = fileSystem;
  70. _appPaths = appPaths;
  71. _serverConfigurationManager = serverConfigurationManager;
  72. _userManager = userManager;
  73. _sessionManager = sessionManager;
  74. _encodingHelper = encodingHelper;
  75. _mediaEncoder = mediaEncoder;
  76. _mediaSourceManager = mediaSourceManager;
  77. _attachmentExtractor = attachmentExtractor;
  78. _logger = loggerFactory.CreateLogger<TranscodeManager>();
  79. DeleteEncodedMediaCache();
  80. _sessionManager.PlaybackProgress += OnPlaybackProgress;
  81. _sessionManager.PlaybackStart += OnPlaybackProgress;
  82. }
  83. /// <inheritdoc />
  84. public TranscodingJob? GetTranscodingJob(string playSessionId)
  85. {
  86. lock (_activeTranscodingJobs)
  87. {
  88. return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
  89. }
  90. }
  91. /// <inheritdoc />
  92. public TranscodingJob? GetTranscodingJob(string path, TranscodingJobType type)
  93. {
  94. lock (_activeTranscodingJobs)
  95. {
  96. return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  97. }
  98. }
  99. /// <inheritdoc />
  100. public void PingTranscodingJob(string playSessionId, bool? isUserPaused)
  101. {
  102. ArgumentException.ThrowIfNullOrEmpty(playSessionId);
  103. _logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
  104. List<TranscodingJob> jobs;
  105. lock (_activeTranscodingJobs)
  106. {
  107. // This is really only needed for HLS.
  108. // Progressive streams can stop on their own reliably.
  109. jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
  110. }
  111. foreach (var job in jobs)
  112. {
  113. if (isUserPaused.HasValue)
  114. {
  115. _logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
  116. job.IsUserPaused = isUserPaused.Value;
  117. }
  118. PingTimer(job, true);
  119. }
  120. }
  121. private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
  122. {
  123. if (job.HasExited)
  124. {
  125. job.StopKillTimer();
  126. return;
  127. }
  128. var timerDuration = 10000;
  129. if (job.Type != TranscodingJobType.Progressive)
  130. {
  131. timerDuration = 60000;
  132. }
  133. job.PingTimeout = timerDuration;
  134. job.LastPingDate = DateTime.UtcNow;
  135. // Don't start the timer for playback checkins with progressive streaming
  136. if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
  137. {
  138. job.StartKillTimer(OnTranscodeKillTimerStopped);
  139. }
  140. else
  141. {
  142. job.ChangeKillTimerIfStarted();
  143. }
  144. }
  145. private async void OnTranscodeKillTimerStopped(object? state)
  146. {
  147. var job = state as TranscodingJob ?? throw new ArgumentException($"{nameof(state)} is not of type {nameof(TranscodingJob)}", nameof(state));
  148. if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
  149. {
  150. var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
  151. if (timeSinceLastPing < job.PingTimeout)
  152. {
  153. job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
  154. return;
  155. }
  156. }
  157. _logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  158. await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
  159. }
  160. /// <inheritdoc />
  161. public Task KillTranscodingJobs(string deviceId, string? playSessionId, Func<string, bool> deleteFiles)
  162. {
  163. var jobs = new List<TranscodingJob>();
  164. lock (_activeTranscodingJobs)
  165. {
  166. // This is really only needed for HLS.
  167. // Progressive streams can stop on their own reliably.
  168. jobs.AddRange(_activeTranscodingJobs.Where(j => string.IsNullOrWhiteSpace(playSessionId)
  169. ? string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase)
  170. : string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)));
  171. }
  172. return Task.WhenAll(GetKillJobs());
  173. IEnumerable<Task> GetKillJobs()
  174. {
  175. foreach (var job in jobs)
  176. {
  177. yield return KillTranscodingJob(job, false, deleteFiles);
  178. }
  179. }
  180. }
  181. private async Task KillTranscodingJob(TranscodingJob job, bool closeLiveStream, Func<string, bool> delete)
  182. {
  183. job.DisposeKillTimer();
  184. _logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
  185. lock (_activeTranscodingJobs)
  186. {
  187. _activeTranscodingJobs.Remove(job);
  188. if (job.CancellationTokenSource?.IsCancellationRequested == false)
  189. {
  190. #pragma warning disable CA1849 // Can't await in lock block
  191. job.CancellationTokenSource.Cancel();
  192. #pragma warning restore CA1849
  193. }
  194. }
  195. lock (_transcodingLocks)
  196. {
  197. _transcodingLocks.Remove(job.Path!);
  198. }
  199. job.Stop();
  200. if (delete(job.Path!))
  201. {
  202. await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
  203. if (job.MediaSource?.VideoType == VideoType.Dvd || job.MediaSource?.VideoType == VideoType.BluRay)
  204. {
  205. var concatFilePath = Path.Join(_serverConfigurationManager.GetTranscodePath(), job.MediaSource.Id + ".concat");
  206. if (File.Exists(concatFilePath))
  207. {
  208. _logger.LogInformation("Deleting ffmpeg concat configuration at {Path}", concatFilePath);
  209. File.Delete(concatFilePath);
  210. }
  211. }
  212. }
  213. if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
  214. {
  215. try
  216. {
  217. await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
  218. }
  219. catch (Exception ex)
  220. {
  221. _logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
  222. }
  223. }
  224. }
  225. private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
  226. {
  227. if (retryCount >= 10)
  228. {
  229. return;
  230. }
  231. _logger.LogInformation("Deleting partial stream file(s) {Path}", path);
  232. await Task.Delay(delayMs).ConfigureAwait(false);
  233. try
  234. {
  235. if (jobType == TranscodingJobType.Progressive)
  236. {
  237. DeleteProgressivePartialStreamFiles(path);
  238. }
  239. else
  240. {
  241. DeleteHlsPartialStreamFiles(path);
  242. }
  243. }
  244. catch (IOException ex)
  245. {
  246. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  247. await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
  248. }
  249. catch (Exception ex)
  250. {
  251. _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
  252. }
  253. }
  254. private void DeleteProgressivePartialStreamFiles(string outputFilePath)
  255. {
  256. if (File.Exists(outputFilePath))
  257. {
  258. _fileSystem.DeleteFile(outputFilePath);
  259. }
  260. }
  261. private void DeleteHlsPartialStreamFiles(string outputFilePath)
  262. {
  263. var directory = Path.GetDirectoryName(outputFilePath)
  264. ?? throw new ArgumentException("Path can't be a root directory.", nameof(outputFilePath));
  265. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  266. var filesToDelete = _fileSystem.GetFilePaths(directory)
  267. .Where(f => f.Contains(name, StringComparison.OrdinalIgnoreCase));
  268. List<Exception>? exs = null;
  269. foreach (var file in filesToDelete)
  270. {
  271. try
  272. {
  273. _logger.LogDebug("Deleting HLS file {0}", file);
  274. _fileSystem.DeleteFile(file);
  275. }
  276. catch (IOException ex)
  277. {
  278. (exs ??= new List<Exception>(4)).Add(ex);
  279. _logger.LogError(ex, "Error deleting HLS file {Path}", file);
  280. }
  281. }
  282. if (exs is not null)
  283. {
  284. throw new AggregateException("Error deleting HLS files", exs);
  285. }
  286. }
  287. /// <inheritdoc />
  288. public void ReportTranscodingProgress(
  289. TranscodingJob job,
  290. StreamState state,
  291. TimeSpan? transcodingPosition,
  292. float? framerate,
  293. double? percentComplete,
  294. long? bytesTranscoded,
  295. int? bitRate)
  296. {
  297. var ticks = transcodingPosition?.Ticks;
  298. if (job is not null)
  299. {
  300. job.Framerate = framerate;
  301. job.CompletionPercentage = percentComplete;
  302. job.TranscodingPositionTicks = ticks;
  303. job.BytesTranscoded = bytesTranscoded;
  304. job.BitRate = bitRate;
  305. }
  306. var deviceId = state.Request.DeviceId;
  307. if (!string.IsNullOrWhiteSpace(deviceId))
  308. {
  309. var audioCodec = state.ActualOutputAudioCodec;
  310. var videoCodec = state.ActualOutputVideoCodec;
  311. var hardwareAccelerationTypeString = _serverConfigurationManager.GetEncodingOptions().HardwareAccelerationType;
  312. HardwareEncodingType? hardwareAccelerationType = null;
  313. if (Enum.TryParse<HardwareEncodingType>(hardwareAccelerationTypeString, out var parsedHardwareAccelerationType))
  314. {
  315. hardwareAccelerationType = parsedHardwareAccelerationType;
  316. }
  317. _sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
  318. {
  319. Bitrate = bitRate ?? state.TotalOutputBitrate,
  320. AudioCodec = audioCodec,
  321. VideoCodec = videoCodec,
  322. Container = state.OutputContainer,
  323. Framerate = framerate,
  324. CompletionPercentage = percentComplete,
  325. Width = state.OutputWidth,
  326. Height = state.OutputHeight,
  327. AudioChannels = state.OutputAudioChannels,
  328. IsAudioDirect = EncodingHelper.IsCopyCodec(state.OutputAudioCodec),
  329. IsVideoDirect = EncodingHelper.IsCopyCodec(state.OutputVideoCodec),
  330. HardwareAccelerationType = hardwareAccelerationType,
  331. TranscodeReasons = state.TranscodeReasons
  332. });
  333. }
  334. }
  335. /// <inheritdoc />
  336. public async Task<TranscodingJob> StartFfMpeg(
  337. StreamState state,
  338. string outputPath,
  339. string commandLineArguments,
  340. Guid userId,
  341. TranscodingJobType transcodingJobType,
  342. CancellationTokenSource cancellationTokenSource,
  343. string? workingDirectory = null)
  344. {
  345. var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  346. Directory.CreateDirectory(directory);
  347. await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
  348. if (state.VideoRequest is not null && !EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  349. {
  350. var user = userId.Equals(default) ? null : _userManager.GetUserById(userId);
  351. if (user is not null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
  352. {
  353. this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
  354. throw new ArgumentException("User does not have access to video transcoding.");
  355. }
  356. }
  357. ArgumentException.ThrowIfNullOrEmpty(_mediaEncoder.EncoderPath);
  358. // If subtitles get burned in fonts may need to be extracted from the media file
  359. if (state.SubtitleStream is not null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  360. {
  361. var attachmentPath = Path.Combine(_appPaths.CachePath, "attachments", state.MediaSource.Id);
  362. if (state.VideoType != VideoType.Dvd)
  363. {
  364. await _attachmentExtractor.ExtractAllAttachments(state.MediaPath, state.MediaSource, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
  365. }
  366. if (state.SubtitleStream.IsExternal && Path.GetExtension(state.SubtitleStream.Path.AsSpan()).Equals(".mks", StringComparison.OrdinalIgnoreCase))
  367. {
  368. string subtitlePath = state.SubtitleStream.Path;
  369. string subtitlePathArgument = string.Format(CultureInfo.InvariantCulture, "file:\"{0}\"", subtitlePath.Replace("\"", "\\\"", StringComparison.Ordinal));
  370. string subtitleId = subtitlePath.GetMD5().ToString("N", CultureInfo.InvariantCulture);
  371. await _attachmentExtractor.ExtractAllAttachmentsExternal(subtitlePathArgument, subtitleId, attachmentPath, cancellationTokenSource.Token).ConfigureAwait(false);
  372. }
  373. }
  374. var process = new Process
  375. {
  376. StartInfo = new ProcessStartInfo
  377. {
  378. WindowStyle = ProcessWindowStyle.Hidden,
  379. CreateNoWindow = true,
  380. UseShellExecute = false,
  381. // Must consume both stdout and stderr or deadlocks may occur
  382. // RedirectStandardOutput = true,
  383. RedirectStandardError = true,
  384. RedirectStandardInput = true,
  385. FileName = _mediaEncoder.EncoderPath,
  386. Arguments = commandLineArguments,
  387. WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? string.Empty : workingDirectory,
  388. ErrorDialog = false
  389. },
  390. EnableRaisingEvents = true
  391. };
  392. var transcodingJob = this.OnTranscodeBeginning(
  393. outputPath,
  394. state.Request.PlaySessionId,
  395. state.MediaSource.LiveStreamId,
  396. Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture),
  397. transcodingJobType,
  398. process,
  399. state.Request.DeviceId,
  400. state,
  401. cancellationTokenSource);
  402. _logger.LogInformation("{Filename} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  403. var logFilePrefix = "FFmpeg.Transcode-";
  404. if (state.VideoRequest is not null
  405. && EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  406. {
  407. logFilePrefix = EncodingHelper.IsCopyCodec(state.OutputAudioCodec)
  408. ? "FFmpeg.Remux-"
  409. : "FFmpeg.DirectStream-";
  410. }
  411. var logFilePath = Path.Combine(
  412. _serverConfigurationManager.ApplicationPaths.LogDirectoryPath,
  413. $"{logFilePrefix}{DateTime.Now:yyyy-MM-dd_HH-mm-ss}_{state.Request.MediaSourceId}_{Guid.NewGuid().ToString()[..8]}.log");
  414. // FFmpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  415. Stream logStream = new FileStream(
  416. logFilePath,
  417. FileMode.Create,
  418. FileAccess.Write,
  419. FileShare.Read,
  420. IODefaults.FileStreamBufferSize,
  421. FileOptions.Asynchronous);
  422. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  423. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(
  424. JsonSerializer.Serialize(state.MediaSource)
  425. + Environment.NewLine
  426. + Environment.NewLine
  427. + commandLineLogMessage
  428. + Environment.NewLine
  429. + Environment.NewLine);
  430. await logStream.WriteAsync(commandLineLogMessageBytes, cancellationTokenSource.Token).ConfigureAwait(false);
  431. process.Exited += (_, _) => OnFfMpegProcessExited(process, transcodingJob, state);
  432. try
  433. {
  434. process.Start();
  435. }
  436. catch (Exception ex)
  437. {
  438. _logger.LogError(ex, "Error starting FFmpeg");
  439. this.OnTranscodeFailedToStart(outputPath, transcodingJobType, state);
  440. throw;
  441. }
  442. _logger.LogDebug("Launched FFmpeg process");
  443. state.TranscodingJob = transcodingJob;
  444. // Important - don't await the log task or we won't be able to kill FFmpeg when the user stops playback
  445. _ = new JobLogger(_logger).StartStreamingLog(state, process.StandardError, logStream);
  446. // Wait for the file to exist before proceeding
  447. var ffmpegTargetFile = state.WaitForPath ?? outputPath;
  448. _logger.LogDebug("Waiting for the creation of {0}", ffmpegTargetFile);
  449. while (!File.Exists(ffmpegTargetFile) && !transcodingJob.HasExited)
  450. {
  451. await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
  452. }
  453. _logger.LogDebug("File {0} created or transcoding has finished", ffmpegTargetFile);
  454. if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
  455. {
  456. await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
  457. if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
  458. {
  459. await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
  460. }
  461. }
  462. if (!transcodingJob.HasExited)
  463. {
  464. StartThrottler(state, transcodingJob);
  465. }
  466. else if (transcodingJob.ExitCode != 0)
  467. {
  468. throw new FfmpegException(string.Format(CultureInfo.InvariantCulture, "FFmpeg exited with code {0}", transcodingJob.ExitCode));
  469. }
  470. _logger.LogDebug("StartFfMpeg() finished successfully");
  471. return transcodingJob;
  472. }
  473. private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
  474. {
  475. if (EnableThrottling(state))
  476. {
  477. transcodingJob.TranscodingThrottler = new TranscodingThrottler(transcodingJob, _loggerFactory.CreateLogger<TranscodingThrottler>(), _serverConfigurationManager, _fileSystem, _mediaEncoder);
  478. transcodingJob.TranscodingThrottler.Start();
  479. }
  480. }
  481. private static bool EnableThrottling(StreamState state)
  482. => state.InputProtocol == MediaProtocol.File
  483. && state.RunTimeTicks.HasValue
  484. && state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks
  485. && state.IsInputVideo
  486. && state.VideoType == VideoType.VideoFile;
  487. private TranscodingJob OnTranscodeBeginning(
  488. string path,
  489. string? playSessionId,
  490. string? liveStreamId,
  491. string transcodingJobId,
  492. TranscodingJobType type,
  493. Process process,
  494. string? deviceId,
  495. StreamState state,
  496. CancellationTokenSource cancellationTokenSource)
  497. {
  498. lock (_activeTranscodingJobs)
  499. {
  500. var job = new TranscodingJob(_loggerFactory.CreateLogger<TranscodingJob>())
  501. {
  502. Type = type,
  503. Path = path,
  504. Process = process,
  505. ActiveRequestCount = 1,
  506. DeviceId = deviceId,
  507. CancellationTokenSource = cancellationTokenSource,
  508. Id = transcodingJobId,
  509. PlaySessionId = playSessionId,
  510. LiveStreamId = liveStreamId,
  511. MediaSource = state.MediaSource
  512. };
  513. _activeTranscodingJobs.Add(job);
  514. ReportTranscodingProgress(job, state, null, null, null, null, null);
  515. return job;
  516. }
  517. }
  518. /// <inheritdoc />
  519. public void OnTranscodeEndRequest(TranscodingJob job)
  520. {
  521. job.ActiveRequestCount--;
  522. _logger.LogDebug("OnTranscodeEndRequest job.ActiveRequestCount={ActiveRequestCount}", job.ActiveRequestCount);
  523. if (job.ActiveRequestCount <= 0)
  524. {
  525. PingTimer(job, false);
  526. }
  527. }
  528. private void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
  529. {
  530. lock (_activeTranscodingJobs)
  531. {
  532. var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  533. if (job is not null)
  534. {
  535. _activeTranscodingJobs.Remove(job);
  536. }
  537. }
  538. lock (_transcodingLocks)
  539. {
  540. _transcodingLocks.Remove(path);
  541. }
  542. if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
  543. {
  544. _sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
  545. }
  546. }
  547. private void OnFfMpegProcessExited(Process process, TranscodingJob job, StreamState state)
  548. {
  549. job.HasExited = true;
  550. job.ExitCode = process.ExitCode;
  551. ReportTranscodingProgress(job, state, null, null, null, null, null);
  552. _logger.LogDebug("Disposing stream resources");
  553. state.Dispose();
  554. if (process.ExitCode == 0)
  555. {
  556. _logger.LogInformation("FFmpeg exited with code 0");
  557. }
  558. else
  559. {
  560. _logger.LogError("FFmpeg exited with code {0}", process.ExitCode);
  561. }
  562. job.Dispose();
  563. }
  564. private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
  565. {
  566. if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
  567. {
  568. var liveStreamResponse = await _mediaSourceManager.OpenLiveStream(
  569. new LiveStreamRequest { OpenToken = state.MediaSource.OpenToken },
  570. cancellationTokenSource.Token)
  571. .ConfigureAwait(false);
  572. var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
  573. _encodingHelper.AttachMediaSourceInfo(state, encodingOptions, liveStreamResponse.MediaSource, state.RequestedUrl);
  574. if (state.VideoRequest is not null)
  575. {
  576. _encodingHelper.TryStreamCopy(state);
  577. }
  578. }
  579. if (state.MediaSource.BufferMs.HasValue)
  580. {
  581. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
  582. }
  583. }
  584. /// <inheritdoc />
  585. public TranscodingJob? OnTranscodeBeginRequest(string path, TranscodingJobType type)
  586. {
  587. lock (_activeTranscodingJobs)
  588. {
  589. var job = _activeTranscodingJobs
  590. .FirstOrDefault(j => j.Type == type && string.Equals(j.Path, path, StringComparison.OrdinalIgnoreCase));
  591. if (job is null)
  592. {
  593. return null;
  594. }
  595. job.ActiveRequestCount++;
  596. if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
  597. {
  598. job.StopKillTimer();
  599. }
  600. return job;
  601. }
  602. }
  603. /// <inheritdoc />
  604. public SemaphoreSlim GetTranscodingLock(string outputPath)
  605. {
  606. lock (_transcodingLocks)
  607. {
  608. if (!_transcodingLocks.TryGetValue(outputPath, out SemaphoreSlim? result))
  609. {
  610. result = new SemaphoreSlim(1, 1);
  611. _transcodingLocks[outputPath] = result;
  612. }
  613. return result;
  614. }
  615. }
  616. private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
  617. {
  618. if (!string.IsNullOrWhiteSpace(e.PlaySessionId))
  619. {
  620. PingTranscodingJob(e.PlaySessionId, e.IsPaused);
  621. }
  622. }
  623. private void DeleteEncodedMediaCache()
  624. {
  625. var path = _serverConfigurationManager.GetTranscodePath();
  626. if (!Directory.Exists(path))
  627. {
  628. return;
  629. }
  630. foreach (var file in _fileSystem.GetFilePaths(path, true))
  631. {
  632. _fileSystem.DeleteFile(file);
  633. }
  634. }
  635. /// <inheritdoc />
  636. public void Dispose()
  637. {
  638. _sessionManager.PlaybackProgress -= OnPlaybackProgress;
  639. _sessionManager.PlaybackStart -= OnPlaybackProgress;
  640. }
  641. }