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