< 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
84%
Covered lines: 16
Uncovered lines: 3
Coverable lines: 19
Total lines: 220
Line coverage: 84.2%
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
.ctor(...)100%11100%
get_Name()100%11100%
get_Description()100%210%
get_Category()100%210%
get_Key()100%210%
GetDefaultTriggers()100%11100%

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
 36    /// <summary>
 37    /// Initializes a new instance of the <see cref="AudioNormalizationTask"/> class.
 38    /// </summary>
 39    /// <param name="itemRepository">Instance of the <see cref="IItemRepository"/> interface.</param>
 40    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 41    /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
 42    /// <param name="applicationPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
 43    /// <param name="localizationManager">Instance of the <see cref="ILocalizationManager"/> interface.</param>
 44    /// <param name="logger">Instance of the <see cref="ILogger{AudioNormalizationTask}"/> interface.</param>
 45    public AudioNormalizationTask(
 46        IItemRepository itemRepository,
 47        ILibraryManager libraryManager,
 48        IMediaEncoder mediaEncoder,
 49        IApplicationPaths applicationPaths,
 50        ILocalizationManager localizationManager,
 51        ILogger<AudioNormalizationTask> logger)
 52    {
 2153        _itemRepository = itemRepository;
 2154        _libraryManager = libraryManager;
 2155        _mediaEncoder = mediaEncoder;
 2156        _applicationPaths = applicationPaths;
 2157        _localization = localizationManager;
 2158        _logger = logger;
 2159    }
 60
 61    /// <inheritdoc />
 2162    public string Name => _localization.GetLocalizedString("TaskAudioNormalization");
 63
 64    /// <inheritdoc />
 065    public string Description => _localization.GetLocalizedString("TaskAudioNormalizationDescription");
 66
 67    /// <inheritdoc />
 068    public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
 69
 70    /// <inheritdoc />
 071    public string Key => "AudioNormalization";
 72
 73    [GeneratedRegex(@"^\s+I:\s+(.*?)\s+LUFS")]
 74    private static partial Regex LUFSRegex();
 75
 76    /// <inheritdoc />
 77    public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
 78    {
 79        foreach (var library in _libraryManager.RootFolder.Children)
 80        {
 81            var libraryOptions = _libraryManager.GetLibraryOptions(library);
 82            if (!libraryOptions.EnableLUFSScan)
 83            {
 84                continue;
 85            }
 86
 87            // Album gain
 88            var albums = _libraryManager.GetItemList(new InternalItemsQuery
 89            {
 90                IncludeItemTypes = [BaseItemKind.MusicAlbum],
 91                Parent = library,
 92                Recursive = true
 93            });
 94
 95            foreach (var a in albums)
 96            {
 97                if (a.NormalizationGain.HasValue || a.LUFS.HasValue)
 98                {
 99                    continue;
 100                }
 101
 102                // Skip albums that don't have multiple tracks, album gain is useless here
 103                var albumTracks = ((MusicAlbum)a).Tracks.Where(x => x.IsFileProtocol).ToList();
 104                if (albumTracks.Count <= 1)
 105                {
 106                    continue;
 107                }
 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}'", x.Pat
 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 deleting the c
 120                        cancellationToken).ConfigureAwait(false);
 121                }
 122                finally
 123                {
 124                    File.Delete(tempFile);
 125                }
 126            }
 127
 128            _itemRepository.SaveItems(albums, cancellationToken);
 129
 130            // Track gain
 131            var tracks = _libraryManager.GetItemList(new InternalItemsQuery
 132            {
 133                MediaTypes = [MediaType.Audio],
 134                IncludeItemTypes = [BaseItemKind.Audio],
 135                Parent = library,
 136                Recursive = true
 137            });
 138
 139            foreach (var t in tracks)
 140            {
 141                if (t.NormalizationGain.HasValue || t.LUFS.HasValue || !t.IsFileProtocol)
 142                {
 143                    continue;
 144                }
 145
 146                t.LUFS = await CalculateLUFSAsync(
 147                    string.Format(CultureInfo.InvariantCulture, "-i \"{0}\"", t.Path.Replace("\"", "\\\"", StringCompari
 148                    false,
 149                    cancellationToken).ConfigureAwait(false);
 150            }
 151
 152            _itemRepository.SaveItems(tracks, cancellationToken);
 153        }
 154    }
 155
 156    /// <inheritdoc />
 157    public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
 158    {
 21159        return
 21160        [
 21161            new TaskTriggerInfo
 21162            {
 21163                Type = TaskTriggerInfoType.IntervalTrigger,
 21164                IntervalTicks = TimeSpan.FromHours(24).Ticks
 21165            }
 21166        ];
 167    }
 168
 169    private async Task<float?> CalculateLUFSAsync(string inputArgs, bool waitForExit, CancellationToken cancellationToke
 170    {
 171        var args = $"-hide_banner {inputArgs} -af ebur128=framelog=verbose -f null -";
 172
 173        using (var process = new Process()
 174        {
 175            StartInfo = new ProcessStartInfo
 176            {
 177                FileName = _mediaEncoder.EncoderPath,
 178                Arguments = args,
 179                RedirectStandardOutput = false,
 180                RedirectStandardError = true
 181            },
 182        })
 183        {
 184            try
 185            {
 186                _logger.LogDebug("Starting ffmpeg with arguments: {Arguments}", args);
 187                process.Start();
 188            }
 189            catch (Exception ex)
 190            {
 191                _logger.LogError(ex, "Error starting ffmpeg with arguments: {Arguments}", args);
 192                return null;
 193            }
 194
 195            using var reader = process.StandardError;
 196            float? lufs = null;
 197            await foreach (var line in reader.ReadAllLinesAsync(cancellationToken))
 198            {
 199                Match match = LUFSRegex().Match(line);
 200                if (match.Success)
 201                {
 202                    lufs = float.Parse(match.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
 203                    break;
 204                }
 205            }
 206
 207            if (lufs is null)
 208            {
 209                _logger.LogError("Failed to find LUFS value in output");
 210            }
 211
 212            if (waitForExit)
 213            {
 214                await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
 215            }
 216
 217            return lufs;
 218        }
 219    }
 220}