AudioNormalizationTask.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. foreach (var library in _libraryManager.RootFolder.Children)
  71. {
  72. var libraryOptions = _libraryManager.GetLibraryOptions(library);
  73. if (!libraryOptions.EnableLUFSScan)
  74. {
  75. continue;
  76. }
  77. // Album gain
  78. var albums = _libraryManager.GetItemList(new InternalItemsQuery
  79. {
  80. IncludeItemTypes = [BaseItemKind.MusicAlbum],
  81. Parent = library,
  82. Recursive = true
  83. });
  84. foreach (var a in albums)
  85. {
  86. if (a.NormalizationGain.HasValue || a.LUFS.HasValue)
  87. {
  88. continue;
  89. }
  90. // Skip albums that don't have multiple tracks, album gain is useless here
  91. var albumTracks = ((MusicAlbum)a).Tracks.Where(x => x.IsFileProtocol).ToList();
  92. if (albumTracks.Count <= 1)
  93. {
  94. continue;
  95. }
  96. _logger.LogInformation("Calculating LUFS for album: {Album} with id: {Id}", a.Name, a.Id);
  97. var tempDir = _applicationPaths.TempDirectory;
  98. Directory.CreateDirectory(tempDir);
  99. var tempFile = Path.Join(tempDir, a.Id + ".concat");
  100. var inputLines = albumTracks.Select(x => string.Format(CultureInfo.InvariantCulture, "file '{0}'", x.Path.Replace("'", @"'\''", StringComparison.Ordinal)));
  101. await File.WriteAllLinesAsync(tempFile, inputLines, cancellationToken).ConfigureAwait(false);
  102. try
  103. {
  104. a.LUFS = await CalculateLUFSAsync(
  105. string.Format(CultureInfo.InvariantCulture, "-f concat -safe 0 -i \"{0}\"", tempFile),
  106. OperatingSystem.IsWindows(), // Wait for process to exit on Windows before we try deleting the concat file
  107. cancellationToken).ConfigureAwait(false);
  108. }
  109. finally
  110. {
  111. File.Delete(tempFile);
  112. }
  113. }
  114. _itemRepository.SaveItems(albums, cancellationToken);
  115. // Track gain
  116. var tracks = _libraryManager.GetItemList(new InternalItemsQuery
  117. {
  118. MediaTypes = [MediaType.Audio],
  119. IncludeItemTypes = [BaseItemKind.Audio],
  120. Parent = library,
  121. Recursive = true
  122. });
  123. foreach (var t in tracks)
  124. {
  125. if (t.NormalizationGain.HasValue || t.LUFS.HasValue || !t.IsFileProtocol)
  126. {
  127. continue;
  128. }
  129. t.LUFS = await CalculateLUFSAsync(
  130. string.Format(CultureInfo.InvariantCulture, "-i \"{0}\"", t.Path.Replace("\"", "\\\"", StringComparison.Ordinal)),
  131. false,
  132. cancellationToken).ConfigureAwait(false);
  133. }
  134. _itemRepository.SaveItems(tracks, cancellationToken);
  135. }
  136. }
  137. /// <inheritdoc />
  138. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  139. {
  140. yield return new TaskTriggerInfo
  141. {
  142. Type = TaskTriggerInfoType.IntervalTrigger,
  143. IntervalTicks = TimeSpan.FromHours(24).Ticks
  144. };
  145. }
  146. private async Task<float?> CalculateLUFSAsync(string inputArgs, bool waitForExit, CancellationToken cancellationToken)
  147. {
  148. var args = $"-hide_banner {inputArgs} -af ebur128=framelog=verbose -f null -";
  149. using (var process = new Process()
  150. {
  151. StartInfo = new ProcessStartInfo
  152. {
  153. FileName = _mediaEncoder.EncoderPath,
  154. Arguments = args,
  155. RedirectStandardOutput = false,
  156. RedirectStandardError = true
  157. },
  158. })
  159. {
  160. try
  161. {
  162. _logger.LogDebug("Starting ffmpeg with arguments: {Arguments}", args);
  163. process.Start();
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.LogError(ex, "Error starting ffmpeg with arguments: {Arguments}", args);
  168. return null;
  169. }
  170. using var reader = process.StandardError;
  171. float? lufs = null;
  172. await foreach (var line in reader.ReadAllLinesAsync(cancellationToken).ConfigureAwait(false))
  173. {
  174. Match match = LUFSRegex().Match(line);
  175. if (match.Success)
  176. {
  177. lufs = float.Parse(match.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  178. break;
  179. }
  180. }
  181. if (lufs is null)
  182. {
  183. _logger.LogError("Failed to find LUFS value in output");
  184. }
  185. if (waitForExit)
  186. {
  187. await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
  188. }
  189. return lufs;
  190. }
  191. }
  192. }