TranscodeManager.cs 27 KB

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