AudioNormalizationTask.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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.RegularExpressions;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Data.Enums;
  11. using Jellyfin.Extensions;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Entities.Audio;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.MediaEncoding;
  17. using MediaBrowser.Controller.Persistence;
  18. using MediaBrowser.Model.Globalization;
  19. using MediaBrowser.Model.Tasks;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
  22. /// <summary>
  23. /// The audio normalization task.
  24. /// </summary>
  25. public partial class AudioNormalizationTask : IScheduledTask
  26. {
  27. private readonly IItemRepository _itemRepository;
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly IMediaEncoder _mediaEncoder;
  30. private readonly IApplicationPaths _applicationPaths;
  31. private readonly ILocalizationManager _localization;
  32. private readonly ILogger<AudioNormalizationTask> _logger;
  33. private static readonly TimeSpan _dbSaveInterval = TimeSpan.FromMinutes(5);
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="AudioNormalizationTask"/> class.
  36. /// </summary>
  37. /// <param name="itemRepository">Instance of the <see cref="IItemRepository"/> interface.</param>
  38. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  39. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  40. /// <param name="applicationPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  41. /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  42. /// <param name="logger">Instance of the <see cref="ILogger{AudioNormalizationTask}"/> interface.</param>
  43. public AudioNormalizationTask(
  44. IItemRepository itemRepository,
  45. ILibraryManager libraryManager,
  46. IMediaEncoder mediaEncoder,
  47. IApplicationPaths applicationPaths,
  48. ILocalizationManager localizationManager,
  49. ILogger<AudioNormalizationTask> logger)
  50. {
  51. _itemRepository = itemRepository;
  52. _libraryManager = libraryManager;
  53. _mediaEncoder = mediaEncoder;
  54. _applicationPaths = applicationPaths;
  55. _localization = localizationManager;
  56. _logger = logger;
  57. }
  58. /// <inheritdoc />
  59. public string Name => _localization.GetLocalizedString("TaskAudioNormalization");
  60. /// <inheritdoc />
  61. public string Description => _localization.GetLocalizedString("TaskAudioNormalizationDescription");
  62. /// <inheritdoc />
  63. public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
  64. /// <inheritdoc />
  65. public string Key => "AudioNormalization";
  66. [GeneratedRegex(@"^\s+I:\s+(.*?)\s+LUFS")]
  67. private static partial Regex LUFSRegex();
  68. /// <inheritdoc />
  69. public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
  70. {
  71. var numComplete = 0;
  72. var libraries = _libraryManager.RootFolder.Children.Where(library => _libraryManager.GetLibraryOptions(library).EnableLUFSScan).ToArray();
  73. double percent = 0;
  74. foreach (var library in libraries)
  75. {
  76. var startDbSaveInterval = Stopwatch.GetTimestamp();
  77. var albums = _libraryManager.GetItemList(new InternalItemsQuery { IncludeItemTypes = [BaseItemKind.MusicAlbum], Parent = library, Recursive = true });
  78. var toSaveDbItems = new List<BaseItem>();
  79. double nextPercent = numComplete + 1;
  80. nextPercent /= libraries.Length;
  81. nextPercent -= percent;
  82. // Split the progress for this single library into two halves: album gain and track gain.
  83. // The first half will be for album gain, the second half for track gain.
  84. nextPercent /= 2;
  85. var albumComplete = 0;
  86. foreach (var a in albums)
  87. {
  88. if (!a.NormalizationGain.HasValue && !a.LUFS.HasValue)
  89. {
  90. // Album gain
  91. var albumTracks = ((MusicAlbum)a).Tracks.Where(x => x.IsFileProtocol).ToList();
  92. // Skip albums that don't have multiple tracks, album gain is useless here
  93. if (albumTracks.Count > 1)
  94. {
  95. _logger.LogInformation("Calculating LUFS for album: {Album} with id: {Id}", a.Name, a.Id);
  96. var tempDir = _applicationPaths.TempDirectory;
  97. Directory.CreateDirectory(tempDir);
  98. var tempFile = Path.Join(tempDir, a.Id + ".concat");
  99. var inputLines = albumTracks.Select(x => string.Format(CultureInfo.InvariantCulture, "file '{0}'", x.Path.Replace("'", @"'\''", StringComparison.Ordinal)));
  100. await File.WriteAllLinesAsync(tempFile, inputLines, cancellationToken).ConfigureAwait(false);
  101. try
  102. {
  103. a.LUFS = await CalculateLUFSAsync(
  104. string.Format(CultureInfo.InvariantCulture, "-f concat -safe 0 -i \"{0}\"", tempFile),
  105. OperatingSystem.IsWindows(), // Wait for process to exit on Windows before we try deleting the concat file
  106. cancellationToken).ConfigureAwait(false);
  107. toSaveDbItems.Add(a);
  108. }
  109. finally
  110. {
  111. try
  112. {
  113. File.Delete(tempFile);
  114. }
  115. catch (Exception ex)
  116. {
  117. _logger.LogError(ex, "Failed to delete concat file: {FileName}.", tempFile);
  118. }
  119. }
  120. }
  121. }
  122. if (Stopwatch.GetElapsedTime(startDbSaveInterval) > _dbSaveInterval)
  123. {
  124. if (toSaveDbItems.Count > 1)
  125. {
  126. _itemRepository.SaveItems(toSaveDbItems, cancellationToken);
  127. toSaveDbItems.Clear();
  128. }
  129. startDbSaveInterval = Stopwatch.GetTimestamp();
  130. }
  131. // Update sub-progress for album gain
  132. albumComplete++;
  133. double albumPercent = albumComplete;
  134. albumPercent /= albums.Count;
  135. progress.Report(100 * (percent + (albumPercent * nextPercent)));
  136. }
  137. // Update progress to start at the track gain percent calculation
  138. percent += nextPercent;
  139. if (toSaveDbItems.Count > 1)
  140. {
  141. _itemRepository.SaveItems(toSaveDbItems, cancellationToken);
  142. toSaveDbItems.Clear();
  143. }
  144. startDbSaveInterval = Stopwatch.GetTimestamp();
  145. // Track gain
  146. var tracks = _libraryManager.GetItemList(new InternalItemsQuery { MediaTypes = [MediaType.Audio], IncludeItemTypes = [BaseItemKind.Audio], Parent = library, Recursive = true });
  147. var tracksComplete = 0;
  148. foreach (var t in tracks)
  149. {
  150. if (!t.NormalizationGain.HasValue && !t.LUFS.HasValue && t.IsFileProtocol)
  151. {
  152. t.LUFS = await CalculateLUFSAsync(
  153. string.Format(CultureInfo.InvariantCulture, "-i \"{0}\"", t.Path.Replace("\"", "\\\"", StringComparison.Ordinal)),
  154. false,
  155. cancellationToken).ConfigureAwait(false);
  156. toSaveDbItems.Add(t);
  157. }
  158. if (Stopwatch.GetElapsedTime(startDbSaveInterval) > _dbSaveInterval)
  159. {
  160. if (toSaveDbItems.Count > 1)
  161. {
  162. _itemRepository.SaveItems(toSaveDbItems, cancellationToken);
  163. toSaveDbItems.Clear();
  164. }
  165. startDbSaveInterval = Stopwatch.GetTimestamp();
  166. }
  167. // Update sub-progress for track gain
  168. tracksComplete++;
  169. double trackPercent = tracksComplete;
  170. trackPercent /= tracks.Count;
  171. progress.Report(100 * (percent + (trackPercent * nextPercent)));
  172. }
  173. if (toSaveDbItems.Count > 1)
  174. {
  175. _itemRepository.SaveItems(toSaveDbItems, cancellationToken);
  176. }
  177. // Update progress
  178. numComplete++;
  179. percent = numComplete;
  180. percent /= libraries.Length;
  181. progress.Report(100 * percent);
  182. }
  183. progress.Report(100.0);
  184. }
  185. /// <inheritdoc />
  186. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  187. {
  188. yield return new TaskTriggerInfo
  189. {
  190. Type = TaskTriggerInfoType.IntervalTrigger,
  191. IntervalTicks = TimeSpan.FromHours(24).Ticks
  192. };
  193. }
  194. private async Task<float?> CalculateLUFSAsync(string inputArgs, bool waitForExit, CancellationToken cancellationToken)
  195. {
  196. var args = $"-hide_banner {inputArgs} -af ebur128=framelog=verbose -f null -";
  197. using (var process = new Process()
  198. {
  199. StartInfo = new ProcessStartInfo
  200. {
  201. FileName = _mediaEncoder.EncoderPath,
  202. Arguments = args,
  203. RedirectStandardOutput = false,
  204. RedirectStandardError = true
  205. },
  206. })
  207. {
  208. _logger.LogDebug("Starting ffmpeg with arguments: {Arguments}", args);
  209. try
  210. {
  211. process.Start();
  212. }
  213. catch (Exception ex)
  214. {
  215. _logger.LogError(ex, "Error starting ffmpeg with arguments: {Arguments}", args);
  216. return null;
  217. }
  218. try
  219. {
  220. process.PriorityClass = ProcessPriorityClass.BelowNormal;
  221. }
  222. catch (Exception ex)
  223. {
  224. _logger.LogWarning(ex, "Error setting ffmpeg process priority");
  225. }
  226. using var reader = process.StandardError;
  227. float? lufs = null;
  228. await foreach (var line in reader.ReadAllLinesAsync(cancellationToken).ConfigureAwait(false))
  229. {
  230. Match match = LUFSRegex().Match(line);
  231. if (match.Success)
  232. {
  233. lufs = float.Parse(match.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  234. break;
  235. }
  236. }
  237. if (lufs is null)
  238. {
  239. _logger.LogError("Failed to find LUFS value in output");
  240. }
  241. if (waitForExit)
  242. {
  243. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  244. }
  245. return lufs;
  246. }
  247. }
  248. }