AudioNormalizationTask.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. /// <summary>
  34. /// Initializes a new instance of the <see cref="AudioNormalizationTask"/> class.
  35. /// </summary>
  36. /// <param name="itemRepository">Instance of the <see cref="IItemRepository"/> interface.</param>
  37. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  38. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  39. /// <param name="applicationPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  40. /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  41. /// <param name="logger">Instance of the <see cref="ILogger{AudioNormalizationTask}"/> interface.</param>
  42. public AudioNormalizationTask(
  43. IItemRepository itemRepository,
  44. ILibraryManager libraryManager,
  45. IMediaEncoder mediaEncoder,
  46. IApplicationPaths applicationPaths,
  47. ILocalizationManager localizationManager,
  48. ILogger<AudioNormalizationTask> logger)
  49. {
  50. _itemRepository = itemRepository;
  51. _libraryManager = libraryManager;
  52. _mediaEncoder = mediaEncoder;
  53. _applicationPaths = applicationPaths;
  54. _localization = localizationManager;
  55. _logger = logger;
  56. }
  57. /// <inheritdoc />
  58. public string Name => _localization.GetLocalizedString("TaskAudioNormalization");
  59. /// <inheritdoc />
  60. public string Description => _localization.GetLocalizedString("TaskAudioNormalizationDescription");
  61. /// <inheritdoc />
  62. public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
  63. /// <inheritdoc />
  64. public string Key => "AudioNormalization";
  65. [GeneratedRegex(@"^\s+I:\s+(.*?)\s+LUFS")]
  66. private static partial Regex LUFSRegex();
  67. /// <inheritdoc />
  68. public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
  69. {
  70. var numComplete = 0;
  71. var libraries = _libraryManager.RootFolder.Children.Where(library => _libraryManager.GetLibraryOptions(library).EnableLUFSScan).ToArray();
  72. double percent = 0;
  73. foreach (var library in libraries)
  74. {
  75. var albums = _libraryManager.GetItemList(new InternalItemsQuery { IncludeItemTypes = [BaseItemKind.MusicAlbum], Parent = library, Recursive = true });
  76. double nextPercent = numComplete + 1;
  77. nextPercent /= libraries.Length;
  78. nextPercent -= percent;
  79. // Split the progress for this single library into two halves: album gain and track gain.
  80. // The first half will be for album gain, the second half for track gain.
  81. nextPercent /= 2;
  82. var albumComplete = 0;
  83. foreach (var a in albums)
  84. {
  85. if (!a.NormalizationGain.HasValue && !a.LUFS.HasValue)
  86. {
  87. // Album gain
  88. var albumTracks = ((MusicAlbum)a).Tracks.Where(x => x.IsFileProtocol).ToList();
  89. // Skip albums that don't have multiple tracks, album gain is useless here
  90. if (albumTracks.Count > 1)
  91. {
  92. _logger.LogInformation("Calculating LUFS for album: {Album} with id: {Id}", a.Name, a.Id);
  93. var tempDir = _applicationPaths.TempDirectory;
  94. Directory.CreateDirectory(tempDir);
  95. var tempFile = Path.Join(tempDir, a.Id + ".concat");
  96. var inputLines = albumTracks.Select(x => string.Format(CultureInfo.InvariantCulture, "file '{0}'", x.Path.Replace("'", @"'\''", StringComparison.Ordinal)));
  97. await File.WriteAllLinesAsync(tempFile, inputLines, cancellationToken).ConfigureAwait(false);
  98. try
  99. {
  100. a.LUFS = await CalculateLUFSAsync(
  101. string.Format(CultureInfo.InvariantCulture, "-f concat -safe 0 -i \"{0}\"", tempFile),
  102. OperatingSystem.IsWindows(), // Wait for process to exit on Windows before we try deleting the concat file
  103. cancellationToken).ConfigureAwait(false);
  104. }
  105. finally
  106. {
  107. File.Delete(tempFile);
  108. }
  109. }
  110. }
  111. // Update sub-progress for album gain
  112. albumComplete++;
  113. double albumPercent = albumComplete;
  114. albumPercent /= albums.Count;
  115. progress.Report(100 * (percent + (albumPercent * nextPercent)));
  116. }
  117. // Update progress to start at the track gain percent calculation
  118. percent += nextPercent;
  119. _itemRepository.SaveItems(albums, cancellationToken);
  120. // Track gain
  121. var tracks = _libraryManager.GetItemList(new InternalItemsQuery { MediaTypes = [MediaType.Audio], IncludeItemTypes = [BaseItemKind.Audio], Parent = library, Recursive = true });
  122. var tracksComplete = 0;
  123. foreach (var t in tracks)
  124. {
  125. if (!t.NormalizationGain.HasValue && !t.LUFS.HasValue && t.IsFileProtocol)
  126. {
  127. t.LUFS = await CalculateLUFSAsync(
  128. string.Format(CultureInfo.InvariantCulture, "-i \"{0}\"", t.Path.Replace("\"", "\\\"", StringComparison.Ordinal)),
  129. false,
  130. cancellationToken).ConfigureAwait(false);
  131. }
  132. // Update sub-progress for track gain
  133. tracksComplete++;
  134. double trackPercent = tracksComplete;
  135. trackPercent /= tracks.Count;
  136. progress.Report(100 * (percent + (trackPercent * nextPercent)));
  137. }
  138. _itemRepository.SaveItems(tracks, cancellationToken);
  139. // Update progress
  140. numComplete++;
  141. percent = numComplete;
  142. percent /= libraries.Length;
  143. progress.Report(100 * percent);
  144. }
  145. progress.Report(100.0);
  146. }
  147. /// <inheritdoc />
  148. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  149. {
  150. yield return new TaskTriggerInfo
  151. {
  152. Type = TaskTriggerInfoType.IntervalTrigger,
  153. IntervalTicks = TimeSpan.FromHours(24).Ticks
  154. };
  155. }
  156. private async Task<float?> CalculateLUFSAsync(string inputArgs, bool waitForExit, CancellationToken cancellationToken)
  157. {
  158. var args = $"-hide_banner {inputArgs} -af ebur128=framelog=verbose -f null -";
  159. using (var process = new Process()
  160. {
  161. StartInfo = new ProcessStartInfo
  162. {
  163. FileName = _mediaEncoder.EncoderPath,
  164. Arguments = args,
  165. RedirectStandardOutput = false,
  166. RedirectStandardError = true
  167. },
  168. })
  169. {
  170. try
  171. {
  172. _logger.LogDebug("Starting ffmpeg with arguments: {Arguments}", args);
  173. process.Start();
  174. }
  175. catch (Exception ex)
  176. {
  177. _logger.LogError(ex, "Error starting ffmpeg with arguments: {Arguments}", args);
  178. return null;
  179. }
  180. using var reader = process.StandardError;
  181. float? lufs = null;
  182. await foreach (var line in reader.ReadAllLinesAsync(cancellationToken).ConfigureAwait(false))
  183. {
  184. Match match = LUFSRegex().Match(line);
  185. if (match.Success)
  186. {
  187. lufs = float.Parse(match.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  188. break;
  189. }
  190. }
  191. if (lufs is null)
  192. {
  193. _logger.LogError("Failed to find LUFS value in output");
  194. }
  195. if (waitForExit)
  196. {
  197. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  198. }
  199. return lufs;
  200. }
  201. }
  202. }