jellyfin/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs

431 lines
17 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Data.Enums;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Lyrics;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
2013-12-06 03:39:44 +00:00
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
2015-04-05 15:01:57 +00:00
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
2022-03-28 21:11:21 +00:00
using TagLib;
2013-02-21 01:33:05 +00:00
2013-06-09 16:47:28 +00:00
namespace MediaBrowser.Providers.MediaInfo
2013-02-21 01:33:05 +00:00
{
2022-03-31 14:17:37 +00:00
/// <summary>
/// Probes audio files for metadata.
/// </summary>
2023-05-22 20:48:09 +00:00
public partial class AudioFileProber
2013-02-21 01:33:05 +00:00
{
// Default LUFS value for use with the web interface, at -18db gain will be 1(no db gain).
private const float DefaultLUFSValue = -18;
private readonly ILogger<AudioFileProber> _logger;
private readonly IMediaEncoder _mediaEncoder;
2013-12-06 03:39:44 +00:00
private readonly IItemRepository _itemRepo;
2015-06-28 17:00:36 +00:00
private readonly ILibraryManager _libraryManager;
2018-09-12 17:26:21 +00:00
private readonly IMediaSourceManager _mediaSourceManager;
private readonly LyricResolver _lyricResolver;
private readonly ILyricManager _lyricManager;
2013-12-06 03:39:44 +00:00
2022-03-31 14:17:37 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="AudioFileProber"/> class.
/// </summary>
/// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
2022-03-31 14:17:37 +00:00
/// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
/// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
/// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
/// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
/// <param name="lyricResolver">Instance of the <see cref="LyricResolver"/> interface.</param>
/// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
2022-03-29 15:06:30 +00:00
public AudioFileProber(
ILogger<AudioFileProber> logger,
2020-08-07 17:26:28 +00:00
IMediaSourceManager mediaSourceManager,
IMediaEncoder mediaEncoder,
IItemRepository itemRepo,
ILibraryManager libraryManager,
LyricResolver lyricResolver,
ILyricManager lyricManager)
2013-03-02 17:59:15 +00:00
{
_logger = logger;
_mediaEncoder = mediaEncoder;
2013-12-06 03:39:44 +00:00
_itemRepo = itemRepo;
2015-06-28 17:00:36 +00:00
_libraryManager = libraryManager;
2018-09-12 17:26:21 +00:00
_mediaSourceManager = mediaSourceManager;
_lyricResolver = lyricResolver;
_lyricManager = lyricManager;
2013-03-02 17:59:15 +00:00
}
[GeneratedRegex(@"I:\s+(.*?)\s+LUFS")]
2023-05-22 20:48:09 +00:00
private static partial Regex LUFSRegex();
[GeneratedRegex(@"REPLAYGAIN_TRACK_GAIN:\s+-?([0-9.]+)\s+dB")]
private static partial Regex ReplayGainTagRegex();
2022-03-31 14:17:37 +00:00
/// <summary>
/// Probes the specified item for metadata.
/// </summary>
/// <param name="item">The item to probe.</param>
/// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <typeparam name="T">The type of item to resolve.</typeparam>
/// <returns>A <see cref="Task"/> probing the item for metadata.</returns>
2020-09-07 11:20:39 +00:00
public async Task<ItemUpdateType> Probe<T>(
T item,
MetadataRefreshOptions options,
2018-09-12 17:26:21 +00:00
CancellationToken cancellationToken)
where T : Audio
2013-06-18 19:16:27 +00:00
{
2018-09-12 17:26:21 +00:00
var path = item.Path;
var protocol = item.PathProtocol ?? MediaProtocol.File;
2013-06-18 19:16:27 +00:00
2018-09-12 17:26:21 +00:00
if (!item.IsShortcut || options.EnableRemoteContentProbe)
{
if (item.IsShortcut)
{
path = item.ShortcutPath;
protocol = _mediaSourceManager.GetPathProtocol(path);
}
2013-06-18 19:16:27 +00:00
2020-09-07 11:20:39 +00:00
var result = await _mediaEncoder.GetMediaInfo(
new MediaInfoRequest
2018-09-12 17:26:21 +00:00
{
2020-09-07 11:20:39 +00:00
MediaType = DlnaProfileType.Audio,
MediaSource = new MediaSourceInfo
{
Path = path,
Protocol = protocol
}
},
cancellationToken).ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
cancellationToken.ThrowIfCancellationRequested();
2014-02-09 21:11:11 +00:00
await FetchAsync(item, result, options, cancellationToken).ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
}
2014-02-09 21:11:11 +00:00
var libraryOptions = _libraryManager.GetLibraryOptions(item);
bool foundLUFSValue = false;
if (libraryOptions.UseReplayGainTags)
{
using (var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = _mediaEncoder.ProbePath,
Arguments = $"-hide_banner -i \"{path}\"",
RedirectStandardOutput = false,
RedirectStandardError = true
},
})
{
try
{
process.Start();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error starting ffmpeg");
throw;
}
using var reader = process.StandardError;
var output = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
Match split = ReplayGainTagRegex().Match(output);
if (split.Success)
{
item.LUFS = DefaultLUFSValue - float.Parse(split.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
foundLUFSValue = true;
}
else
{
item.LUFS = DefaultLUFSValue;
}
}
}
if (libraryOptions.EnableLUFSScan && !foundLUFSValue)
{
using (var process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = _mediaEncoder.EncoderPath,
Arguments = $"-hide_banner -i \"{path}\" -af ebur128=framelog=verbose -f null -",
RedirectStandardOutput = false,
RedirectStandardError = true
},
})
{
try
{
process.Start();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error starting ffmpeg");
throw;
}
using var reader = process.StandardError;
2023-10-07 21:56:07 +00:00
var output = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
2023-05-22 20:48:09 +00:00
MatchCollection split = LUFSRegex().Matches(output);
if (split.Count != 0)
{
item.LUFS = float.Parse(split[0].Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
}
else
{
item.LUFS = DefaultLUFSValue;
}
}
}
if (!libraryOptions.EnableLUFSScan && !libraryOptions.UseReplayGainTags)
{
item.LUFS = DefaultLUFSValue;
}
_logger.LogDebug("LUFS for {ItemName} is {LUFS}.", item.Name, item.LUFS);
2018-09-12 17:26:21 +00:00
return ItemUpdateType.MetadataImport;
2013-06-18 19:16:27 +00:00
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Fetches the specified audio.
/// </summary>
2022-03-31 14:17:37 +00:00
/// <param name="audio">The <see cref="Audio"/>.</param>
/// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
/// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
2022-03-31 14:17:37 +00:00
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task FetchAsync(
Audio audio,
Model.MediaInfo.MediaInfo mediaInfo,
MetadataRefreshOptions options,
CancellationToken cancellationToken)
2013-02-21 01:33:05 +00:00
{
2017-08-04 20:29:34 +00:00
audio.Container = mediaInfo.Container;
2015-04-04 19:35:29 +00:00
audio.TotalBitrate = mediaInfo.Bitrate;
2013-12-06 03:39:44 +00:00
2015-04-04 19:35:29 +00:00
audio.RunTimeTicks = mediaInfo.RunTimeTicks;
audio.Size = mediaInfo.Size;
audio.PremiereDate = mediaInfo.PremiereDate;
if (!audio.IsLocked)
{
await FetchDataFromTags(audio, options).ConfigureAwait(false);
}
2013-12-06 03:39:44 +00:00
var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
AddExternalLyrics(audio, mediaStreams, options);
audio.HasLyrics = mediaStreams.Any(s => s.Type == MediaStreamType.Lyric);
_itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
2013-02-21 01:33:05 +00:00
}
/// <summary>
2022-03-31 14:17:37 +00:00
/// Fetches data from the tags.
2013-02-21 01:33:05 +00:00
/// </summary>
2022-03-31 14:17:37 +00:00
/// <param name="audio">The <see cref="Audio"/>.</param>
/// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
private async Task FetchDataFromTags(Audio audio, MetadataRefreshOptions options)
2013-02-21 01:33:05 +00:00
{
using var file = TagLib.File.Create(audio.Path);
2022-03-28 21:11:21 +00:00
var tagTypes = file.TagTypesOnDisk;
2022-10-07 12:40:10 +00:00
Tag? tags = null;
2022-03-28 21:11:21 +00:00
if (tagTypes.HasFlag(TagTypes.Id3v2))
2013-02-21 01:33:05 +00:00
{
2022-03-28 21:11:21 +00:00
tags = file.GetTag(TagTypes.Id3v2);
2013-02-21 01:33:05 +00:00
}
2022-03-28 21:11:21 +00:00
else if (tagTypes.HasFlag(TagTypes.Ape))
{
2022-03-28 21:11:21 +00:00
tags = file.GetTag(TagTypes.Ape);
}
2022-03-28 21:11:21 +00:00
else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
2013-02-21 01:33:05 +00:00
{
2022-03-28 21:11:21 +00:00
tags = file.GetTag(TagTypes.FlacMetadata);
}
2022-10-03 11:05:57 +00:00
else if (tagTypes.HasFlag(TagTypes.Apple))
{
tags = file.GetTag(TagTypes.Apple);
}
2022-10-03 11:16:13 +00:00
else if (tagTypes.HasFlag(TagTypes.Xiph))
{
tags = file.GetTag(TagTypes.Xiph);
}
else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
{
tags = file.GetTag(TagTypes.AudibleMetadata);
}
2022-03-28 21:11:21 +00:00
else if (tagTypes.HasFlag(TagTypes.Id3v1))
{
tags = file.GetTag(TagTypes.Id3v1);
}
2013-08-29 21:00:27 +00:00
2022-12-05 14:01:13 +00:00
if (tags is not null)
2022-03-28 21:11:21 +00:00
{
if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
2013-08-04 00:59:23 +00:00
{
2022-03-28 21:11:21 +00:00
var people = new List<PersonInfo>();
var albumArtists = tags.AlbumArtists;
foreach (var albumArtist in albumArtists)
2013-02-21 01:33:05 +00:00
{
if (!string.IsNullOrEmpty(albumArtist))
2022-03-28 21:11:21 +00:00
{
PeopleHelper.AddPerson(people, new PersonInfo
{
Name = albumArtist,
Type = PersonKind.AlbumArtist
});
}
2022-03-28 21:11:21 +00:00
}
2014-06-23 16:05:19 +00:00
2022-03-28 21:11:21 +00:00
var performers = tags.Performers;
foreach (var performer in performers)
{
if (!string.IsNullOrEmpty(performer))
2022-03-28 21:11:21 +00:00
{
PeopleHelper.AddPerson(people, new PersonInfo
{
Name = performer,
Type = PersonKind.Artist
});
}
2022-03-28 21:11:21 +00:00
}
2013-02-21 01:33:05 +00:00
2022-03-28 21:11:21 +00:00
foreach (var composer in tags.Composers)
{
if (!string.IsNullOrEmpty(composer))
2022-03-28 21:11:21 +00:00
{
PeopleHelper.AddPerson(people, new PersonInfo
{
Name = composer,
Type = PersonKind.Composer
});
}
2022-03-28 21:11:21 +00:00
}
_libraryManager.UpdatePeople(audio, people);
2024-02-29 00:34:06 +00:00
2024-02-29 00:18:52 +00:00
if (options.ReplaceAllMetadata && performers.Length != 0)
{
audio.Artists = performers;
}
else if (!options.ReplaceAllMetadata
&& (audio.Artists is null || audio.Artists.Count == 0))
{
audio.Artists = performers;
}
if (options.ReplaceAllMetadata && albumArtists.Length != 0)
{
audio.AlbumArtists = albumArtists;
}
else if (!options.ReplaceAllMetadata
&& (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0))
{
audio.AlbumArtists = albumArtists;
}
2022-03-28 21:11:21 +00:00
}
2013-02-21 01:33:05 +00:00
if (!audio.LockedFields.Contains(MetadataField.Name))
{
audio.Name = options.ReplaceAllMetadata || string.IsNullOrEmpty(audio.Name) ? tags.Title : audio.Name;
}
if (options.ReplaceAllMetadata)
{
audio.Album = tags.Album;
audio.IndexNumber = Convert.ToInt32(tags.Track);
audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
}
else
{
audio.Album ??= tags.Album;
audio.IndexNumber ??= Convert.ToInt32(tags.Track);
audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
}
2022-03-29 15:06:30 +00:00
if (tags.Year != 0)
2022-03-28 21:11:21 +00:00
{
var year = Convert.ToInt32(tags.Year);
audio.ProductionYear = year;
}
2022-03-28 21:11:21 +00:00
if (!audio.LockedFields.Contains(MetadataField.Genres))
{
audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
: audio.Genres;
}
2013-02-21 01:33:05 +00:00
2024-02-29 00:12:05 +00:00
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
{
audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
}
2024-02-29 00:12:05 +00:00
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
{
audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
}
2024-02-29 00:12:05 +00:00
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
{
audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
}
2024-02-29 00:12:05 +00:00
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
{
audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
}
2024-02-29 00:12:05 +00:00
if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
{
audio.SetProviderId(MetadataProvider.MusicBrainzTrack, tags.MusicBrainzTrackId);
}
// Save extracted lyrics if they exist,
// and if we are replacing all metadata or the audio doesn't yet have lyrics.
if (!string.IsNullOrWhiteSpace(tags.Lyrics)
&& (options.ReplaceAllMetadata || audio.GetMediaStreams().All(s => s.Type != MediaStreamType.Lyric)))
{
await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
}
2013-02-21 01:33:05 +00:00
}
}
private void AddExternalLyrics(
Audio audio,
List<MediaStream> currentStreams,
MetadataRefreshOptions options)
{
var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, false);
audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray();
currentStreams.AddRange(externalLyricFiles);
}
}
2013-02-21 01:33:05 +00:00
}