< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.ScheduledTasks.Tasks.AudioNormalizationTask
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs
Line coverage
66%
Covered lines: 8
Uncovered lines: 4
Coverable lines: 12
Total lines: 287
Line coverage: 66.6%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
.ctor(...)100%11100%
get_Name()100%11100%
get_Description()100%210%
get_Category()100%210%
get_Key()100%210%

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/ScheduledTasks/Tasks/AudioNormalizationTask.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.Globalization;
 5using System.IO;
 6using System.Linq;
 7using System.Text.RegularExpressions;
 8using System.Threading;
 9using System.Threading.Tasks;
 10using Jellyfin.Data.Enums;
 11using Jellyfin.Extensions;
 12using MediaBrowser.Common.Configuration;
 13using MediaBrowser.Controller.Entities;
 14using MediaBrowser.Controller.Entities.Audio;
 15using MediaBrowser.Controller.Library;
 16using MediaBrowser.Controller.MediaEncoding;
 17using MediaBrowser.Controller.Persistence;
 18using MediaBrowser.Model.Globalization;
 19using MediaBrowser.Model.Tasks;
 20using Microsoft.Extensions.Logging;
 21
 22namespace Emby.Server.Implementations.ScheduledTasks.Tasks;
 23
 24/// <summary>
 25/// The audio normalization task.
 26/// </summary>
 27public 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
 036    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    {
 2155        _itemRepository = itemRepository;
 2156        _libraryManager = libraryManager;
 2157        _mediaEncoder = mediaEncoder;
 2158        _applicationPaths = applicationPaths;
 2159        _localization = localizationManager;
 2160        _logger = logger;
 2161    }
 62
 63    /// <inheritdoc />
 2164    public string Name => _localization.GetLocalizedString("TaskAudioNormalization");
 65
 66    /// <inheritdoc />
 067    public string Description => _localization.GetLocalizedString("TaskAudioNormalizationDescription");
 68
 69    /// <inheritdoc />
 070    public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
 71
 72    /// <inheritdoc />
 073    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            await foreach (var line in reader.ReadAllLinesAsync(cancellationToken).ConfigureAwait(false))
 265            {
 266                Match match = LUFSRegex().Match(line);
 267                if (match.Success)
 268                {
 269                    lufs = float.Parse(match.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
 270                    break;
 271                }
 272            }
 273
 274            if (lufs is null)
 275            {
 276                _logger.LogError("Failed to find LUFS value in output");
 277            }
 278
 279            if (waitForExit)
 280            {
 281                await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
 282            }
 283
 284            return lufs;
 285        }
 286    }
 287}