Adds the ID3 music metadata plugin and its unit and integration test suites

This commit is contained in:
BinaryAlley committed 2026-09-30 12:00:00 +03:00
1 parent 80af18170a
commit 1ffa14cec4
27 files changed
+4842

No files matched your search

@@ -0,0 +1,38 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Core;
using Lumina.Plugins.ID3.Core.Tags;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
#endregion
namespace Lumina.Plugins.ID3.Common.DependencyInjection;
/// <summary>
/// Utility class for registering the services of the ID3 metadata provider into the Dependency Injection container.
/// </summary>
internal static class Id3Services
{
/// <summary>
/// Registers the services of the ID3 metadata providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddId3MetadataProviders(this IServiceCollection services, Guid pluginId)
{
ArgumentNullException.ThrowIfNull(services);
// The reader is scoped, so that the tags of a single file are read only once across the artist, album and track providers of the same enrichment scope.
services.TryAddScoped<Id3TagReader>();
// Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations.
// A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair.
services.AddKeyedTransient<IMetadataProvider, Id3ArtistMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, Id3AlbumMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, Id3TrackMetadataProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,258 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.ID3.Common.Models.DTO.Tags;
/// <summary>
/// Snapshot of the metadata read from the embedded tags of a single audio file.
/// Every audio property that the tags do not carry is left empty, so that the local values already extracted from the file are never overwritten with blanks.
/// </summary>
internal sealed class Id3TagDto
{
/// <summary>
/// Gets or initializes the title of the track.
/// </summary>
public string? Title { get; init; }
/// <summary>
/// Gets or initializes the title of the album the track belongs to.
/// </summary>
public string? Album { get; init; }
/// <summary>
/// Gets or initializes the artists credited on the track.
/// </summary>
public List<string> TrackArtists { get; init; } = [];
/// <summary>
/// Gets or initializes the artists credited on the album.
/// </summary>
public List<string> AlbumArtists { get; init; } = [];
/// <summary>
/// Gets or initializes the sort name of the album artist.
/// </summary>
public string? AlbumArtistSortName { get; init; }
/// <summary>
/// Gets or initializes the sort name of the track artist.
/// </summary>
public string? TrackArtistSortName { get; init; }
/// <summary>
/// Gets or initializes the number of the track on its disc.
/// </summary>
public uint TrackNumber { get; init; }
/// <summary>
/// Gets or initializes the number of tracks on the disc, as reported by the tags.
/// </summary>
public uint TrackCount { get; init; }
/// <summary>
/// Gets or initializes the number of the disc the track belongs to.
/// </summary>
public uint DiscNumber { get; init; }
/// <summary>
/// Gets or initializes the number of discs of the release, as reported by the tags.
/// </summary>
public uint DiscCount { get; init; }
/// <summary>
/// Gets or initializes the year the track was released.
/// </summary>
public int? Year { get; init; }
/// <summary>
/// Gets or initializes the original release date of the track.
/// </summary>
public DateOnly? OriginalReleaseDate { get; init; }
/// <summary>
/// Gets or initializes the original release year of the track.
/// </summary>
public int? OriginalReleaseYear { get; init; }
/// <summary>
/// Gets or initializes the genres the tags associate with the track.
/// </summary>
public List<string> Genres { get; init; } = [];
/// <summary>
/// Gets or initializes the composers credited on the track.
/// </summary>
public List<string> Composers { get; init; } = [];
/// <summary>
/// Gets or initializes the lyricists credited on the track.
/// </summary>
public List<string> Lyricists { get; init; } = [];
/// <summary>
/// Gets or initializes the conductors credited on the track.
/// </summary>
public List<string> Conductors { get; init; } = [];
/// <summary>
/// Gets or initializes the remixers credited on the track.
/// </summary>
public List<string> Remixers { get; init; } = [];
/// <summary>
/// Gets or initializes the people credited on the track, each with the free-form role read from the tags.
/// </summary>
public List<(string Role, string Name)> InvolvedPeople { get; init; } = [];
/// <summary>
/// Gets or initializes the language of the track.
/// </summary>
public string? Language { get; init; }
/// <summary>
/// Gets or initializes the script used by the language of the track.
/// </summary>
public string? Script { get; init; }
/// <summary>
/// Gets or initializes the label that issued the album.
/// </summary>
public string? Label { get; init; }
/// <summary>
/// Gets or initializes the catalog numbers of the album.
/// </summary>
public List<string> CatalogNumbers { get; init; } = [];
/// <summary>
/// Gets or initializes the barcode of the album.
/// </summary>
public string? Barcode { get; init; }
/// <summary>
/// Gets or initializes the types of the release, as read from the tags.
/// </summary>
public List<string> ReleaseTypes { get; init; } = [];
/// <summary>
/// Gets or initializes the status of the release.
/// </summary>
public string? ReleaseStatus { get; init; }
/// <summary>
/// Gets or initializes the country the release was issued in.
/// </summary>
public string? ReleaseCountry { get; init; }
/// <summary>
/// Gets or initializes the physical or digital medium of the release.
/// </summary>
public string? MediaFormat { get; init; }
/// <summary>
/// Gets or initializes the outermost packaging of the release.
/// </summary>
public string? Packaging { get; init; }
/// <summary>
/// Gets or initializes the ASIN of the album.
/// </summary>
public string? Asin { get; init; }
/// <summary>
/// Gets or initializes the ISRCs of the track.
/// </summary>
public List<string> Isrcs { get; init; } = [];
/// <summary>
/// Gets or initializes the moods of the track.
/// </summary>
public List<string> Moods { get; init; } = [];
/// <summary>
/// Gets or initializes the title of the work the track is a recording of.
/// </summary>
public string? WorkTitle { get; init; }
/// <summary>
/// Gets or initializes the musical key of the track.
/// </summary>
public string? MusicKey { get; init; }
/// <summary>
/// Gets or initializes the tempo of the track in beats per minute.
/// </summary>
public int? Bpm { get; init; }
/// <summary>
/// Gets or initializes the duration of the audio of the track in seconds.
/// </summary>
public int? DurationInSeconds { get; init; }
/// <summary>
/// Gets or initializes the sample rate of the audio of the track in Hz.
/// </summary>
public int? SampleRate { get; init; }
/// <summary>
/// Gets or initializes the number of audio channels of the track.
/// </summary>
public int? Channels { get; init; }
/// <summary>
/// Gets or initializes the bit depth of the audio of the track.
/// </summary>
public int? BitDepth { get; init; }
/// <summary>
/// Gets or initializes the bitrate of the audio of the track in kbps.
/// </summary>
public int? Bitrate { get; init; }
/// <summary>
/// Gets or initializes the description of the audio codec of the track.
/// </summary>
public string? AudioCodec { get; init; }
/// <summary>
/// Gets or initializes the official website associated with the artist.
/// </summary>
public string? Website { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the artist.
/// </summary>
public string? MusicBrainzArtistId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the release artist.
/// </summary>
public string? MusicBrainzReleaseArtistId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the release group.
/// </summary>
public string? MusicBrainzReleaseGroupId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the release.
/// </summary>
public string? MusicBrainzReleaseId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the recording of the track.
/// </summary>
public string? MusicBrainzRecordingId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the track on its release.
/// </summary>
public string? MusicBrainzReleaseTrackId { get; init; }
/// <summary>
/// Gets or initializes the MusicBrainz identifier of the work the track is a recording of.
/// </summary>
public string? MusicBrainzWorkId { get; init; }
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using Lumina.Plugins.ID3.Core.Mapping;
using Lumina.Plugins.ID3.Core.Tags;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Provides album metadata from the embedded tags of one of its audio files, by resolving lookups into album metadata DTOs.
/// </summary>
internal sealed class Id3AlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
{
private readonly Id3TagReader _tagReader;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "ID3";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="Id3AlbumMetadataProvider"/> class.
/// </summary>
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
public Id3AlbumMetadataProvider(Id3TagReader tagReader)
{
_tagReader = tagReader;
}
/// <summary>
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of album metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
AlbumMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false);
IReadOnlyList<AlbumMetadataDto> results = metadata is null ? [] : [metadata];
return results;
}
/// <summary>
/// Gets the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when the file carries none.</returns>
public Task<AlbumMetadataDto?> GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return ReadMetadataAsync(lookup.Path, cancellationToken);
}
/// <summary>
/// Reads the metadata of the album from the embedded tags of the track stored at <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of a track of the album.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when the tags carry no album title.</returns>
private Task<AlbumMetadataDto?> ReadMetadataAsync(string path, CancellationToken cancellationToken)
{
// The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file.
return Task.Run(() =>
{
Id3TagDto? data = _tagReader.Read(path);
if (data is null || string.IsNullOrWhiteSpace(data.Album))
return null;
return Id3TagMapper.MapAlbum(data);
}, cancellationToken);
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using Lumina.Plugins.ID3.Core.Mapping;
using Lumina.Plugins.ID3.Core.Tags;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Provides music artist metadata from the embedded tags of one of its audio files, by resolving lookups into artist metadata DTOs.
/// </summary>
internal sealed class Id3ArtistMetadataProvider : IMetadataProvider<ArtistMetadataLookupDto, ArtistMetadataDto>
{
private readonly Id3TagReader _tagReader;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "ID3";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="Id3ArtistMetadataProvider"/> class.
/// </summary>
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
public Id3ArtistMetadataProvider(Id3TagReader tagReader)
{
_tagReader = tagReader;
}
/// <summary>
/// Searches for the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of artist metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
public async Task<IReadOnlyList<ArtistMetadataDto>> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
ArtistMetadataDto? metadata = await ReadMetadataAsync(lookup, cancellationToken).ConfigureAwait(false);
IReadOnlyList<ArtistMetadataDto> results = metadata is null ? [] : [metadata];
return results;
}
/// <summary>
/// Gets the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when the file carries none.</returns>
public Task<ArtistMetadataDto?> GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return ReadMetadataAsync(lookup, cancellationToken);
}
/// <summary>
/// Reads the metadata of the artist described by <paramref name="lookup"/> from the embedded tags of the track stored at its path.
/// </summary>
/// <param name="lookup">The lookup describing the artist.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when the tags carry no artist name.</returns>
private Task<ArtistMetadataDto?> ReadMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file.
return Task.Run(() =>
{
Id3TagDto? data = _tagReader.Read(lookup.Path);
if (data is null || (data.AlbumArtists.Count == 0 && data.TrackArtists.Count == 0))
return null;
return Id3TagMapper.MapArtist(data, lookup.Name);
}, cancellationToken);
}
}
@@ -0,0 +1,64 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.ID3.Common.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Plugin that populates music metadata exclusively from the embedded tags of the audio files, without accessing the web.
/// </summary>
public sealed class Id3Plugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("a3f1c8d2-6b47-4e9a-8c15-2d7f9e4b6a03");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "ID3 Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Populates artist, album and track metadata from the embedded tags of the audio files, without accessing the web.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return [];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddId3MetadataProviders(pluginId: Id);
}
}
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using Lumina.Plugins.ID3.Core.Mapping;
using Lumina.Plugins.ID3.Core.Tags;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.ID3.Core;
/// <summary>
/// Provides track metadata from the embedded tags of the audio file, by resolving lookups into audio metadata DTOs.
/// </summary>
internal sealed class Id3TrackMetadataProvider : IMetadataProvider<TrackMetadataLookupDto, AudioMetadataDto>
{
private readonly Id3TagReader _tagReader;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "ID3";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => false;
/// <summary>
/// Initializes a new instance of the <see cref="Id3TrackMetadataProvider"/> class.
/// </summary>
/// <param name="tagReader">The reader of the embedded tags of the audio files.</param>
public Id3TrackMetadataProvider(Id3TagReader tagReader)
{
_tagReader = tagReader;
}
/// <summary>
/// Searches for the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of track metadata candidates found, which for embedded tags is at most the file of the lookup.</returns>
public async Task<IReadOnlyList<AudioMetadataDto>> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
AudioMetadataDto? metadata = await ReadMetadataAsync(lookup.Path, cancellationToken).ConfigureAwait(false);
IReadOnlyList<AudioMetadataDto> results = metadata is null ? [] : [metadata];
return results;
}
/// <summary>
/// Gets the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when the file carries none.</returns>
public Task<AudioMetadataDto?> GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
return ReadMetadataAsync(lookup.Path, cancellationToken);
}
/// <summary>
/// Reads the metadata of the track stored at <paramref name="path"/> from its embedded tags.
/// </summary>
/// <param name="path">The file system path of the track.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when the tags carry no title.</returns>
private Task<AudioMetadataDto?> ReadMetadataAsync(string path, CancellationToken cancellationToken)
{
// The tagging library exposes no asynchronous API, so the blocking read of the file is offloaded so that a scan does not block on the tags of each file.
return Task.Run(() =>
{
Id3TagDto? data = _tagReader.Read(path);
if (data is null || string.IsNullOrWhiteSpace(data.Title))
return null;
return Id3TagMapper.MapTrack(data);
}, cancellationToken);
}
}
@@ -0,0 +1,644 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
#endregion
namespace Lumina.Plugins.ID3.Core.Mapping;
/// <summary>
/// Maps the metadata read from the embedded tags of an audio file into the application's media metadata DTOs.
/// </summary>
internal static class Id3TagMapper
{
/// <summary>
/// The neutral cultures of the application, keyed by both their two letter and three letter language codes, so that a language code is resolved without enumerating the cultures of the system for every mapped file.
/// </summary>
private static readonly Dictionary<string, CultureInfo> s_culturesByLanguageCode = BuildCulturesByLanguageCode();
/// <summary>
/// Builds the map of the neutral cultures of the application, keyed by their language codes.
/// </summary>
/// <returns>The cultures, keyed by both their two letter and three letter language codes.</returns>
private static Dictionary<string, CultureInfo> BuildCulturesByLanguageCode()
{
Dictionary<string, CultureInfo> cultures = new(StringComparer.OrdinalIgnoreCase);
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
if (culture.ThreeLetterISOLanguageName.Length == 3 && !cultures.ContainsKey(culture.ThreeLetterISOLanguageName))
cultures[culture.ThreeLetterISOLanguageName] = culture;
if (culture.TwoLetterISOLanguageName.Length == 2 && !cultures.ContainsKey(culture.TwoLetterISOLanguageName))
cultures[culture.TwoLetterISOLanguageName] = culture;
}
return cultures;
}
/// <summary>
/// Maps the tags of an audio file into artist metadata.
/// </summary>
/// <param name="data">The tags of a track of the artist.</param>
/// <param name="artistName">The name of the artist the metadata is mapped for, when known, used to select the matching credited artist.</param>
/// <returns>The mapped artist metadata.</returns>
public static ArtistMetadataDto MapArtist(Id3TagDto data, string? artistName)
{
bool doesMatchTrackArtist = !string.IsNullOrWhiteSpace(artistName) && data.TrackArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase));
bool doesMatchAlbumArtist = !string.IsNullOrWhiteSpace(artistName) && data.AlbumArtists.Any(artist => string.Equals(artist, artistName, StringComparison.OrdinalIgnoreCase));
string? mappedName;
string? mappedSortName;
Guid? musicBrainzArtistId;
if (doesMatchTrackArtist)
{
mappedName = NullIfWhiteSpace(artistName);
mappedSortName = data.TrackArtistSortName ?? data.AlbumArtistSortName;
musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId);
}
else if (doesMatchAlbumArtist)
{
mappedName = NullIfWhiteSpace(artistName);
mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName;
musicBrainzArtistId = ParseGuid(data.MusicBrainzReleaseArtistId) ?? ParseGuid(data.MusicBrainzArtistId);
}
else
{
mappedName = NullIfWhiteSpace(data.AlbumArtists.FirstOrDefault()) ?? NullIfWhiteSpace(data.TrackArtists.FirstOrDefault());
mappedSortName = data.AlbumArtistSortName ?? data.TrackArtistSortName;
musicBrainzArtistId = ParseGuid(data.MusicBrainzArtistId) ?? ParseGuid(data.MusicBrainzReleaseArtistId);
}
return new ArtistMetadataDto(
Name: mappedName,
SortName: mappedSortName,
Disambiguation: null,
Type: null,
Gender: null,
Country: null,
Area: null,
BeginArea: null,
EndArea: null,
LifeSpanBegin: null,
LifeSpanEnd: null,
IsEnded: false,
Website: data.Website,
MusicBrainzArtistId: musicBrainzArtistId,
Ipis: null,
Isnis: null,
Aliases: null,
Genres: null,
Tags: null,
Ratings: null,
Contributors: null);
}
/// <summary>
/// Maps the tags of an audio file into album metadata.
/// </summary>
/// <param name="data">The tags of a track of the album.</param>
/// <returns>The mapped album metadata.</returns>
public static AlbumMetadataDto MapAlbum(Id3TagDto data)
{
return new AlbumMetadataDto(
Title: NullIfWhiteSpace(data.Album),
OriginalTitle: null,
Description: null,
Disambiguation: null,
ReleaseInfo: BuildReleaseInfo(data),
Language: MapLanguage(data.Language),
OriginalLanguage: null,
Tags: null,
Genres: MapGenres(data.Genres),
Script: NullIfWhiteSpace(data.Script),
ReleaseTypes: MapReleaseTypes(data.ReleaseTypes),
ReleaseStatus: MapReleaseStatus(data.ReleaseStatus),
MediaFormat: MapMediaFormat(data.MediaFormat),
Packaging: MapPackaging(data.Packaging),
TotalDiscs: data.DiscCount > 0 ? (int)data.DiscCount : null,
TotalTracks: data.TrackCount > 0 ? (int)data.TrackCount : null,
Barcode: NullIfWhiteSpace(data.Barcode),
CatalogNumbers: data.CatalogNumbers.Count > 0 ? [.. data.CatalogNumbers] : null,
Label: NullIfWhiteSpace(data.Label),
ASIN: NullIfWhiteSpace(data.Asin),
MusicBrainzReleaseId: ParseGuid(data.MusicBrainzReleaseId),
MusicBrainzReleaseGroupId: ParseGuid(data.MusicBrainzReleaseGroupId),
MusicBrainzReleaseArtistId: ParseGuid(data.MusicBrainzReleaseArtistId),
Contributors: MapAlbumContributors(data),
Ratings: null,
ReleaseTitle: null);
}
/// <summary>
/// Maps the tags of an audio file into track metadata.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The mapped track metadata.</returns>
public static AudioMetadataDto MapTrack(Id3TagDto data)
{
return new AudioMetadataDto(
Title: NullIfWhiteSpace(data.Title),
OriginalTitle: null,
Description: null,
Disambiguation: null,
ReleaseInfo: BuildReleaseInfo(data),
Language: MapLanguage(data.Language),
OriginalLanguage: null,
Tags: null,
Genres: MapGenres(data.Genres),
Script: NullIfWhiteSpace(data.Script),
Key: MapKey(data.MusicKey),
Bpm: data.Bpm,
IsVideo: false,
Work: MapWork(data),
Isrcs: MapIsrcs(data.Isrcs),
Moods: MapMoods(data.Moods),
DurationInSeconds: data.DurationInSeconds,
SampleRate: data.SampleRate,
Channels: data.Channels,
BitDepth: data.BitDepth,
AudioCodec: NullIfWhiteSpace(data.AudioCodec),
Bitrate: data.Bitrate,
MusicBrainzRecordingId: ParseGuid(data.MusicBrainzRecordingId),
MusicBrainzTrackId: ParseGuid(data.MusicBrainzReleaseTrackId),
Contributors: MapTrackContributors(data),
Ratings: null);
}
/// <summary>
/// Builds the release information of the metadata from the tags, or <see langword="null"/> when the tags carry none of it.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The release information, or <see langword="null"/> when the tags carry no release field.</returns>
private static ReleaseInfoDto? BuildReleaseInfo(Id3TagDto data)
{
ReleaseCountry? releaseCountry = MapReleaseCountry(data.ReleaseCountry);
if (data.OriginalReleaseDate is null && data.OriginalReleaseYear is null && releaseCountry is null)
return null;
return new ReleaseInfoDto(
OriginalReleaseDate: data.OriginalReleaseDate,
OriginalReleaseYear: data.OriginalReleaseYear,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: releaseCountry,
ReleaseVersion: null);
}
/// <summary>
/// Maps the work of the track, or <see langword="null"/> when the tags carry none.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The mapped work, or <see langword="null"/>.</returns>
private static MusicWorkDto? MapWork(Id3TagDto data)
{
Guid? workId = ParseFirstGuid(data.MusicBrainzWorkId);
string? workTitle = FirstValue(data.WorkTitle);
// The work is only mapped when both its identifier and its title are known, because the domain requires both and would otherwise reject the whole track.
if (workId is null || string.IsNullOrWhiteSpace(workTitle))
return null;
return new MusicWorkDto(
MusicBrainzWorkId: workId,
Title: workTitle,
Type: null,
Languages: null,
Iswcs: null);
}
/// <summary>
/// Maps the contributors credited on the track, each with its canonical role.
/// </summary>
/// <param name="data">The tags of the track.</param>
/// <returns>The mapped contributors, or <see langword="null"/> when the tags credit none.</returns>
private static List<MediaContributorDto>? MapTrackContributors(Id3TagDto data)
{
List<MediaContributorDto> contributors = [];
foreach (string artist in data.TrackArtists)
AddContributor(contributors, artist, MediaContributorRole.Performer);
foreach (string composer in data.Composers)
AddContributor(contributors, composer, MediaContributorRole.Composer);
foreach (string lyricist in data.Lyricists)
AddContributor(contributors, lyricist, MediaContributorRole.Lyricist);
foreach (string conductor in data.Conductors)
AddContributor(contributors, conductor, MediaContributorRole.Conductor);
foreach (string remixer in data.Remixers)
AddContributor(contributors, remixer, MediaContributorRole.Remixer);
foreach ((string role, string name) in data.InvolvedPeople)
AddContributor(contributors, name, MapRole(role));
return contributors.Count > 0 ? contributors : null;
}
/// <summary>
/// Maps the contributors credited on the album, which the tags only expose as the album artists.
/// </summary>
/// <param name="data">The tags of a track of the album.</param>
/// <returns>The mapped contributors, or <see langword="null"/> when the tags credit none.</returns>
private static List<MediaContributorDto>? MapAlbumContributors(Id3TagDto data)
{
List<string> artists = data.AlbumArtists.Count > 0 ? data.AlbumArtists : data.TrackArtists;
List<MediaContributorDto> contributors = [];
foreach (string artist in artists)
AddContributor(contributors, artist, MediaContributorRole.Performer);
return contributors.Count > 0 ? contributors : null;
}
/// <summary>
/// Maps the genres of the metadata, without duplicates.
/// </summary>
/// <param name="genres">The genre names read from the tags.</param>
/// <returns>The mapped genres, or <see langword="null"/> when there are none.</returns>
private static List<GenreDto>? MapGenres(List<string> genres)
{
List<GenreDto> result = [.. genres
.Where(genre => !string.IsNullOrWhiteSpace(genre))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(genre => new GenreDto(genre))];
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps the moods of the metadata, without duplicates.
/// </summary>
/// <param name="moods">The mood names read from the tags.</param>
/// <returns>The mapped moods, or <see langword="null"/> when there are none.</returns>
private static List<MoodDto>? MapMoods(List<string> moods)
{
List<MoodDto> result = [.. moods
.Where(mood => !string.IsNullOrWhiteSpace(mood))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(mood => new MoodDto(mood))];
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps the ISRCs of the track, without duplicates.
/// </summary>
/// <param name="isrcs">The ISRC values read from the tags.</param>
/// <returns>The mapped ISRCs, or <see langword="null"/> when there are none.</returns>
private static List<IsrcDto>? MapIsrcs(List<string> isrcs)
{
List<IsrcDto> result = [.. isrcs
.Where(isrc => !string.IsNullOrWhiteSpace(isrc))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Select(isrc => new IsrcDto(isrc))];
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps the types of the release into the application enum, without duplicates.
/// </summary>
/// <param name="releaseTypes">The free-form release types read from the tags.</param>
/// <returns>The mapped release types, or <see langword="null"/> when there are none.</returns>
private static List<MusicReleaseType>? MapReleaseTypes(List<string> releaseTypes)
{
List<MusicReleaseType> result = [];
foreach (string releaseType in releaseTypes)
{
MusicReleaseType? mapped = MapReleaseType(releaseType);
if (mapped is not null && !result.Contains(mapped.Value))
result.Add(mapped.Value);
}
return result.Count > 0 ? result : null;
}
/// <summary>
/// Maps a single free-form release type into the application enum.
/// </summary>
/// <param name="releaseType">The release type to map.</param>
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicReleaseType? MapReleaseType(string? releaseType)
{
if (string.IsNullOrWhiteSpace(releaseType))
return null;
return releaseType.Trim().ToLowerInvariant() switch
{
"album" => MusicReleaseType.Album,
"single" => MusicReleaseType.Single,
"ep" => MusicReleaseType.Ep,
"broadcast" => MusicReleaseType.Broadcast,
"other" => MusicReleaseType.Other,
"compilation" => MusicReleaseType.Compilation,
"live" => MusicReleaseType.Live,
"soundtrack" => MusicReleaseType.Soundtrack,
"spokenword" => MusicReleaseType.SpokenWord,
"audio drama" => MusicReleaseType.AudioDrama,
"audiobook" => MusicReleaseType.AudioBook,
"demo" => MusicReleaseType.Demo,
"dj-mix" => MusicReleaseType.DjMix,
"field recording" => MusicReleaseType.FieldRecording,
"interview" => MusicReleaseType.Interview,
"mixtape/street" => MusicReleaseType.Mixtape,
"remix" => MusicReleaseType.Remix,
_ => null
};
}
/// <summary>
/// Maps a free-form release status into the application enum.
/// </summary>
/// <param name="releaseStatus">The release status to map.</param>
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
private static MusicReleaseStatus? MapReleaseStatus(string? releaseStatus)
{
if (string.IsNullOrWhiteSpace(releaseStatus))
return null;
return releaseStatus.Trim().ToLowerInvariant() switch
{
"official" => MusicReleaseStatus.Official,
"promotion" => MusicReleaseStatus.Promotion,
"bootleg" => MusicReleaseStatus.Bootleg,
"pseudo-release" => MusicReleaseStatus.PseudoRelease,
"withdrawn" => MusicReleaseStatus.Withdrawn,
"cancelled" => MusicReleaseStatus.Cancelled,
"expunged" => MusicReleaseStatus.Expunged,
_ => null
};
}
/// <summary>
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
/// </summary>
/// <param name="country">The country code to map.</param>
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
private static ReleaseCountry? MapReleaseCountry(string? country)
{
if (string.IsNullOrWhiteSpace(country))
return null;
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
}
/// <summary>
/// Maps a free-form media format into the application enum.
/// </summary>
/// <param name="mediaFormat">The media format to map.</param>
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
private static MusicMediaFormat? MapMediaFormat(string? mediaFormat)
{
if (string.IsNullOrWhiteSpace(mediaFormat))
return null;
string value = mediaFormat.Trim().ToLowerInvariant();
MusicMediaFormat? mapped = value switch
{
"12\" vinyl" => MusicMediaFormat.Inch12Vinyl,
"10\" vinyl" => MusicMediaFormat.Inch10Vinyl,
"7\" vinyl" => MusicMediaFormat.Inch7Vinyl,
"3\" vinyl" => MusicMediaFormat.Inch3Vinyl,
"vinyl" => MusicMediaFormat.Vinyl,
"cd" => MusicMediaFormat.CD,
"sacd" => MusicMediaFormat.SACD,
"hybrid sacd" => MusicMediaFormat.HybridSACD,
"digital media" => MusicMediaFormat.DigitalMedia,
"cassette" => MusicMediaFormat.Cassette,
"dvd" => MusicMediaFormat.DVD,
"dvd-video" => MusicMediaFormat.DVDVideo,
"dvd-audio" => MusicMediaFormat.DVDAudio,
"blu-ray" => MusicMediaFormat.BluRay,
"minidisc" => MusicMediaFormat.MiniDisc,
"8cm cd" => MusicMediaFormat.Cm8CD,
"dat" => MusicMediaFormat.DAT,
"vinyl disc" => MusicMediaFormat.VinylDisc,
"other" => MusicMediaFormat.Other,
_ => null
};
if (mapped is not null)
return mapped;
// Fall back to a direct parse for the values whose free-form name already matches an enum member, ignoring the separators.
string normalized = value.Replace("\"", string.Empty, StringComparison.Ordinal).Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal);
return Enum.TryParse(normalized, ignoreCase: true, out MusicMediaFormat parsed) ? parsed : null;
}
/// <summary>
/// Maps a free-form packaging into the application enum.
/// </summary>
/// <param name="packaging">The packaging to map.</param>
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
private static MusicReleasePackaging? MapPackaging(string? packaging)
{
if (string.IsNullOrWhiteSpace(packaging))
return null;
string value = packaging.Trim().ToLowerInvariant().Replace(" ", string.Empty, StringComparison.Ordinal).Replace("-", string.Empty, StringComparison.Ordinal).Replace("/", string.Empty, StringComparison.Ordinal);
return Enum.TryParse(value, ignoreCase: true, out MusicReleasePackaging parsed) ? parsed : null;
}
/// <summary>
/// Maps a free-form musical key into the application enum.
/// </summary>
/// <param name="musicKey">The musical key to map.</param>
/// <returns>The mapped musical key, or <see langword="null"/> when the key is unknown.</returns>
private static MusicKey? MapKey(string? musicKey)
{
if (string.IsNullOrWhiteSpace(musicKey))
return null;
string value = musicKey.Trim();
bool isMinor = false;
if (value.EndsWith("minor", StringComparison.OrdinalIgnoreCase))
{
isMinor = true;
value = value[..^5];
}
else if (value.EndsWith("major", StringComparison.OrdinalIgnoreCase))
value = value[..^5];
else if (value.EndsWith("min", StringComparison.OrdinalIgnoreCase))
{
isMinor = true;
value = value[..^3];
}
else if (value.EndsWith("maj", StringComparison.OrdinalIgnoreCase))
value = value[..^3];
else if (value.EndsWith("m", StringComparison.OrdinalIgnoreCase))
{
isMinor = true;
value = value[..^1];
}
value = value.Trim().ToUpperInvariant().Replace("\u266f", "#", StringComparison.Ordinal).Replace("\u266d", "B", StringComparison.Ordinal);
return value switch
{
"C" => isMinor ? MusicKey.CMinor : MusicKey.CMajor,
"C#" or "DB" => isMinor ? MusicKey.CSharpMinor : MusicKey.CSharpMajor,
"D" => isMinor ? MusicKey.DMinor : MusicKey.DMajor,
"D#" or "EB" => isMinor ? MusicKey.DSharpMinor : MusicKey.DSharpMajor,
"E" => isMinor ? MusicKey.EMinor : MusicKey.EMajor,
"F" => isMinor ? MusicKey.FMinor : MusicKey.FMajor,
"F#" or "GB" => isMinor ? MusicKey.FSharpMinor : MusicKey.FSharpMajor,
"G" => isMinor ? MusicKey.GMinor : MusicKey.GMajor,
"G#" or "AB" => isMinor ? MusicKey.GSharpMinor : MusicKey.GSharpMajor,
"A" => isMinor ? MusicKey.AMinor : MusicKey.AMajor,
"A#" or "BB" => isMinor ? MusicKey.ASharpMinor : MusicKey.ASharpMajor,
"B" => isMinor ? MusicKey.BMinor : MusicKey.BMajor,
_ => null
};
}
/// <summary>
/// Maps a free-form ISO 639 language code into language information.
/// </summary>
/// <param name="rawCode">The code to map.</param>
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
// A language code can list several languages, such as "eng/ara"; the first one is the language of the release.
string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code;
switch (primaryCode)
{
case "zxx":
return new LanguageInfoDto(primaryCode, "No linguistic content", null);
case "mul":
return new LanguageInfoDto(primaryCode, "Multiple languages", null);
case "und":
return new LanguageInfoDto(primaryCode, "Undetermined", null);
}
if (s_culturesByLanguageCode.TryGetValue(primaryCode, out CultureInfo? culture))
return new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName);
return new LanguageInfoDto(primaryCode, primaryCode, null);
}
/// <summary>
/// Maps a free-form contributor role into a canonical media contributor role.
/// </summary>
/// <param name="role">The role to map.</param>
/// <returns>The mapped contributor role.</returns>
private static MediaContributorRole MapRole(string? role)
{
if (string.IsNullOrWhiteSpace(role))
return MediaContributorRole.Other;
string value = role.Trim().ToLowerInvariant();
// An instrument is more specific than a generic role, so the instruments are matched first.
if (value.Contains("backing vocal", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (value.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (value.Contains("bass guitar", StringComparison.Ordinal) || value.Contains("electric bass", StringComparison.Ordinal) || string.Equals(value, "bass", StringComparison.Ordinal))
return MediaContributorRole.BassGuitar;
if (value.Contains("guitar", StringComparison.Ordinal))
return MediaContributorRole.Guitar;
if (value.Contains("drum", StringComparison.Ordinal) || value.Contains("membranophone", StringComparison.Ordinal))
return MediaContributorRole.Drums;
if (value.Contains("percussion", StringComparison.Ordinal) || value.Contains("tambourine", StringComparison.Ordinal) || value.Contains("handclap", StringComparison.Ordinal) || value.Contains("stomp", StringComparison.Ordinal))
return MediaContributorRole.Percussion;
if (value.Contains("keyboard", StringComparison.Ordinal))
return MediaContributorRole.Keyboards;
if (value.Contains("piano", StringComparison.Ordinal))
return MediaContributorRole.Piano;
if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal) || value.Contains("sampler", StringComparison.Ordinal))
return MediaContributorRole.Synthesizer;
if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal))
return MediaContributorRole.Strings;
if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal))
return MediaContributorRole.Brass;
if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal))
return MediaContributorRole.Woodwinds;
if (value.Contains("executive producer", StringComparison.Ordinal))
return MediaContributorRole.ExecutiveProducer;
if (value.Contains("producer", StringComparison.Ordinal))
return MediaContributorRole.Producer;
if (value.Contains("remix", StringComparison.Ordinal))
return MediaContributorRole.Remixer;
if (value.Contains("engineer", StringComparison.Ordinal) || value.Contains("mastering", StringComparison.Ordinal))
return MediaContributorRole.Engineer;
if (value.Contains("mix", StringComparison.Ordinal))
return MediaContributorRole.Mixer;
if (value.Contains("arranger", StringComparison.Ordinal))
return MediaContributorRole.Arranger;
if (value.Contains("conductor", StringComparison.Ordinal))
return MediaContributorRole.Conductor;
if (value.Contains("orchestrator", StringComparison.Ordinal))
return MediaContributorRole.Orchestrator;
if (value.Contains("composer", StringComparison.Ordinal))
return MediaContributorRole.Composer;
if (value.Contains("lyricist", StringComparison.Ordinal) || value.Contains("librettist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (value.Contains("writer", StringComparison.Ordinal) || value.Contains("author", StringComparison.Ordinal))
return MediaContributorRole.Author;
if (value.Contains("choir", StringComparison.Ordinal) || value.Contains("chorus", StringComparison.Ordinal))
return MediaContributorRole.Choir;
if (value.Contains("performer", StringComparison.Ordinal) || value.Contains("member of band", StringComparison.Ordinal) || value.Contains("orchestra", StringComparison.Ordinal))
return MediaContributorRole.Performer;
return MediaContributorRole.Other;
}
/// <summary>
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="displayName">The display name of the contributor.</param>
/// <param name="role">The role the contributor played.</param>
private static void AddContributor(List<MediaContributorDto> contributors, string displayName, MediaContributorRole role)
{
if (string.IsNullOrWhiteSpace(displayName))
return;
if (contributors.Any(contributor =>
string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) &&
contributor.Role == role))
return;
contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName.Trim(), null), role));
}
/// <summary>
/// Parses the provided value as a globally unique identifier.
/// </summary>
/// <param name="value">The value to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is missing or malformed.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
}
/// <summary>
/// Parses the first globally unique identifier of a value that may hold several slash-separated identifiers.
/// </summary>
/// <param name="value">The value to parse.</param>
/// <returns>The first parsed identifier, or <see langword="null"/> when the value holds none.</returns>
private static Guid? ParseFirstGuid(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
foreach (string candidate in value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
if (Guid.TryParse(candidate, out Guid parsed))
return parsed;
return null;
}
/// <summary>
/// Gets the first value of a tag that may hold several slash-separated values.
/// </summary>
/// <param name="value">The value to read.</param>
/// <returns>The first non-empty value, or <see langword="null"/> when the value is empty.</returns>
private static string? FirstValue(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return null;
return NullIfWhiteSpace(value.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).FirstOrDefault());
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,434 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.ID3.Common.Models.DTO.Tags;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
#endregion
namespace Lumina.Plugins.ID3.Core.Tags;
/// <summary>
/// Reads the embedded tags of an audio file into a snapshot, caching the snapshot per path so that the tags of a single file are read only once.
/// </summary>
internal sealed class Id3TagReader
{
/// <summary>
/// The container tag types whose extended tags are searched, in the order they are tried.
/// </summary>
private static readonly TagLib.TagTypes[] s_extendedTagContainerTypes = [TagLib.TagTypes.Xiph, TagLib.TagTypes.Id3v2, TagLib.TagTypes.Apple, TagLib.TagTypes.Ape];
/// <summary>
/// The keys of the free-form Apple tags that carry the involved people of a track, paired with the role each of them describes.
/// </summary>
private static readonly (string Role, string Key)[] s_appleInvolvedPeopleKeys =
[
("performer", "performer"),
("producer", "PRODUCER"),
("engineer", "ENGINEER"),
("mixer", "MIXER"),
("arranger", "arranger"),
("writer", "writer")
];
/// <summary>
/// Matches a four digit year.
/// </summary>
private static readonly Regex s_yearPattern = new(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b", RegexOptions.Compiled);
/// <summary>
/// The maximum number of tag snapshots the cache retains, so that reading a large library does not retain the tags of every file it visits.
/// </summary>
private const int MAX_CACHED_SNAPSHOTS = 512;
private readonly Dictionary<string, Id3TagDto> _cache = new(StringComparer.Ordinal);
private readonly Queue<string> _cacheOrder = new();
private readonly Lock _cacheLock = new();
/// <summary>
/// Reads the embedded tags of the audio file stored at <paramref name="path"/>.
/// </summary>
/// <param name="path">The file system path of the audio file whose tags are read.</param>
/// <returns>The snapshot of the tags, or <see langword="null"/> when the file does not exist or its tags cannot be read.</returns>
public Id3TagDto? Read(string path)
{
if (string.IsNullOrWhiteSpace(path))
return null;
lock (_cacheLock)
{
if (_cache.TryGetValue(path, out Id3TagDto? cached))
return cached;
}
Id3TagDto? data = ReadTagData(path);
// A file whose tags cannot be read is not cached, so that a transient failure does not skip the file for the rest of the scan.
if (data is null)
return null;
lock (_cacheLock)
{
if (!_cache.ContainsKey(path))
{
if (_cache.Count >= MAX_CACHED_SNAPSHOTS)
EvictOldestSnapshot();
_cache[path] = data;
_cacheOrder.Enqueue(path);
}
}
return data;
}
/// <summary>
/// Removes the snapshot that was cached first, keeping the cache within its maximum size.
/// </summary>
private void EvictOldestSnapshot()
{
if (_cacheOrder.Count == 0)
return;
string oldestPath = _cacheOrder.Dequeue();
_cache.Remove(oldestPath);
}
/// <summary>
/// Reads the embedded tags of the audio file stored at <paramref name="path"/> into a snapshot.
/// </summary>
/// <param name="path">The file system path of the audio file whose tags are read.</param>
/// <returns>The snapshot of the tags, or <see langword="null"/> when the file does not exist or its tags cannot be read.</returns>
private static Id3TagDto? ReadTagData(string path)
{
// A file whose path cannot be represented by the operating system, or that is not an audio container, yields no metadata rather than an error.
if (!File.Exists(path))
return null;
try
{
// A link inside a library root must not cause the tags of a file outside the library to be read.
if (File.GetAttributes(path).HasFlag(FileAttributes.ReparsePoint))
return null;
using (TagLib.File tagFile = TagLib.File.Create(path))
{
TagLib.Tag tag = tagFile.Tag;
TagLib.Properties audioProperties = tagFile.Properties;
List<Func<string, List<string>>> extendedFields = BuildExtendedFieldSources(tagFile);
(DateOnly? releaseDate, int? releaseYear) = ParseDate(GetExtendedField(extendedFields, "TDRC", "DATE"));
(DateOnly? originalDate, int? originalYear) = ParseDate(GetExtendedField(extendedFields, "TDOR", "originaldate", "ORIGINALDATE", "originalyear"));
int? year = releaseYear ?? (tag.Year > 0 ? (int)tag.Year : null);
// The original release date and year must describe the same point in time, so the explicit original date is preferred and the year of the chosen date is used whenever a date is known, rather than the year of the release described by the tags.
DateOnly? originalReleaseDate = originalDate ?? releaseDate;
int? originalReleaseYear = originalReleaseDate?.Year ?? originalYear ?? year;
return new Id3TagDto
{
Title = NullIfWhiteSpace(tag.Title),
Album = NullIfWhiteSpace(tag.Album),
TrackArtists = Filter(tag.Performers),
AlbumArtists = Filter(tag.AlbumArtists),
AlbumArtistSortName = NullIfWhiteSpace(tag.AlbumArtistsSort?.FirstOrDefault()),
TrackArtistSortName = NullIfWhiteSpace(tag.PerformersSort?.FirstOrDefault()),
TrackNumber = tag.Track,
TrackCount = tag.TrackCount,
DiscNumber = tag.Disc,
DiscCount = tag.DiscCount,
Year = year,
OriginalReleaseDate = originalReleaseDate,
OriginalReleaseYear = originalReleaseYear,
Genres = SplitValues(Filter(tag.Genres)),
Composers = SplitValues(Filter(tag.Composers)),
Lyricists = SplitValues(GetExtendedFields(extendedFields, "LYRICIST", "lyricist", "TEXT")),
Conductors = Filter([tag.Conductor]),
Remixers = Filter([tag.RemixedBy]),
InvolvedPeople = ReadInvolvedPeople(extendedFields),
Language = NullIfWhiteSpace(GetExtendedField(extendedFields, "LANGUAGE", "TLAN")),
Script = NullIfWhiteSpace(GetExtendedField(extendedFields, "SCRIPT")),
Label = NullIfWhiteSpace(tag.Publisher) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "LABEL")),
CatalogNumbers = SplitValuesOnSemicolons(GetExtendedFields(extendedFields, "CATALOGNUMBER")),
Barcode = NullIfWhiteSpace(GetExtendedField(extendedFields, "BARCODE", "barcode")),
ReleaseTypes = SplitValuesOnSemicolons([tag.MusicBrainzReleaseType]),
ReleaseStatus = NullIfWhiteSpace(tag.MusicBrainzReleaseStatus),
ReleaseCountry = NullIfWhiteSpace(tag.MusicBrainzReleaseCountry),
MediaFormat = NullIfWhiteSpace(GetExtendedField(extendedFields, "MEDIA", "TMED")),
Packaging = NullIfWhiteSpace(GetExtendedField(extendedFields, "PACKAGING")),
Asin = NullIfWhiteSpace(tag.AmazonId) ?? NullIfWhiteSpace(GetExtendedField(extendedFields, "ASIN")),
Isrcs = ReadIsrcs(extendedFields, tag),
Moods = SplitValues(GetExtendedFields(extendedFields, "mood", "MOOD", "MOODS")),
WorkTitle = NullIfWhiteSpace(GetExtendedField(extendedFields, "WORK", "MUSICBRAINZ_WORK")),
MusicKey = NullIfWhiteSpace(tag.InitialKey),
Bpm = tag.BeatsPerMinute > 0 ? (int)tag.BeatsPerMinute : null,
DurationInSeconds = audioProperties.Duration > TimeSpan.Zero ? (int)audioProperties.Duration.TotalSeconds : null,
SampleRate = audioProperties.AudioSampleRate > 0 ? audioProperties.AudioSampleRate : null,
Channels = audioProperties.AudioChannels > 0 ? audioProperties.AudioChannels : null,
BitDepth = audioProperties.BitsPerSample > 0 ? audioProperties.BitsPerSample : null,
Bitrate = audioProperties.AudioBitrate > 0 ? audioProperties.AudioBitrate : null,
AudioCodec = NullIfWhiteSpace(audioProperties.Description),
Website = NullIfWhiteSpace(GetExtendedField(extendedFields, "WOAR", "website")),
MusicBrainzArtistId = NullIfWhiteSpace(tag.MusicBrainzArtistId),
MusicBrainzReleaseArtistId = NullIfWhiteSpace(tag.MusicBrainzReleaseArtistId),
MusicBrainzReleaseGroupId = NullIfWhiteSpace(tag.MusicBrainzReleaseGroupId),
MusicBrainzReleaseId = NullIfWhiteSpace(tag.MusicBrainzReleaseId),
MusicBrainzRecordingId = NullIfWhiteSpace(tag.MusicBrainzTrackId),
MusicBrainzReleaseTrackId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Release Track Id", "MUSICBRAINZ_RELEASETRACKID")),
MusicBrainzWorkId = NullIfWhiteSpace(GetExtendedField(extendedFields, "MusicBrainz Work Id", "MUSICBRAINZ_WORKID"))
};
}
}
catch (Exception exception) when (exception is TagLib.CorruptFileException or TagLib.UnsupportedFormatException or IOException or UnauthorizedAccessException)
{
// A file whose tags cannot be read still contributes the metadata derived from its path, so the failure is not propagated.
return null;
}
}
/// <summary>
/// Reads the people credited on the track, together with the free-form role each of them is credited for.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <returns>The people credited on the track, as role and name pairs.</returns>
private static List<(string Role, string Name)> ReadInvolvedPeople(List<Func<string, List<string>>> extendedFields)
{
List<(string Role, string Name)> people = [];
// The ID3v2.3 involved people list (IPLS) and the ID3v2.4 equivalent (TIPL) store roles and names as a single flat sequence of alternating values.
List<string> id3People = GetExtendedFields(extendedFields, "IPLS", "TIPL", "TMCL");
for (int index = 0; index + 1 < id3People.Count; index += 2)
people.Add((id3People[index], id3People[index + 1]));
// The Apple containers store each role as its own free-form tag, carrying one or more names.
foreach ((string role, string key) in s_appleInvolvedPeopleKeys)
foreach (string name in GetExtendedFields(extendedFields, key))
if (!string.IsNullOrWhiteSpace(name))
people.Add((role, name));
return people;
}
/// <summary>
/// Reads the ISRCs of the track, from both the dedicated tag and the extended tags, without duplicates.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <param name="tag">The combined tag of the file.</param>
/// <returns>The ISRCs of the track.</returns>
private static List<string> ReadIsrcs(List<Func<string, List<string>>> extendedFields, TagLib.Tag tag)
{
List<string> values = SplitValues(GetExtendedFields(extendedFields, "ISRC", "TSRC"));
if (!string.IsNullOrWhiteSpace(tag.ISRC))
values.AddRange(SplitValues([tag.ISRC]));
return [.. values.Distinct(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Builds the ordered accessors that resolve an extended tag value from whichever container tag of the file carries it.
/// </summary>
/// <param name="tagFile">The file whose extended tags are read.</param>
/// <returns>The accessors, in the order the containers are searched.</returns>
private static List<Func<string, List<string>>> BuildExtendedFieldSources(TagLib.File tagFile)
{
List<Func<string, List<string>>> sources = [];
foreach (TagLib.TagTypes tagType in s_extendedTagContainerTypes)
{
TagLib.Tag? tag = tagFile.GetTag(tagType);
if (tag is TagLib.Ogg.XiphComment xiphComment)
sources.Add(key => [.. (xiphComment.GetField(key) ?? [])]);
else if (tag is TagLib.Id3v2.Tag id3v2Tag)
{
Dictionary<string, List<string>> id3Fields = BuildId3v2Fields(id3v2Tag);
sources.Add(key => id3Fields.TryGetValue(key, out List<string>? values) ? values : []);
}
else if (tag is TagLib.Mpeg4.AppleTag appleTag)
sources.Add(key => GetAppleFields(appleTag, key));
else if (tag is TagLib.Ape.Tag apeTag)
sources.Add(key => GetApeFields(apeTag, key));
}
return sources;
}
/// <summary>
/// Builds the map of the ID3v2 frames of the file, keyed by the name each frame is looked up with, so that the frames are enumerated only once per file.
/// </summary>
/// <param name="id3v2Tag">The ID3v2 tag whose frames are indexed.</param>
/// <returns>The values of every frame, keyed by the frame identifier or the description of a user defined frame.</returns>
private static Dictionary<string, List<string>> BuildId3v2Fields(TagLib.Id3v2.Tag id3v2Tag)
{
Dictionary<string, List<string>> fields = new(StringComparer.OrdinalIgnoreCase);
foreach (TagLib.Id3v2.Frame frame in id3v2Tag.GetFrames())
{
string key;
List<string> values;
if (frame is TagLib.Id3v2.UserTextInformationFrame userTextViewFrame)
{
key = userTextViewFrame.Description;
values = [.. userTextViewFrame.Text];
}
else if (frame is TagLib.Id3v2.UrlLinkFrame urlFrame)
{
key = urlFrame.FrameId.ToString();
values = [.. urlFrame.Text];
}
else if (frame is TagLib.Id3v2.TextInformationFrame textFrame)
{
key = textFrame.FrameId.ToString();
values = [.. textFrame.Text];
}
else
continue;
// A user defined frame without a description carries no lookup key, so it is not indexed.
if (string.IsNullOrEmpty(key))
continue;
if (fields.TryGetValue(key, out List<string>? existing))
existing.AddRange(values);
else
fields[key] = values;
}
return fields;
}
/// <summary>
/// Reads the values of a free-form Apple tag with the provided <paramref name="key"/>.
/// </summary>
/// <param name="appleTag">The Apple tag whose values are read.</param>
/// <param name="key">The name of the free-form tag to read.</param>
/// <returns>Every value of the tag.</returns>
private static List<string> GetAppleFields(TagLib.Mpeg4.AppleTag appleTag, string key)
{
List<string> values = [];
foreach (string appleValue in appleTag.GetDashBoxes("com.apple.iTunes", key) ?? [])
values.AddRange(appleValue.Split('\0', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
return values;
}
/// <summary>
/// Reads the values of an APE tag with the provided <paramref name="key"/>.
/// </summary>
/// <param name="apeTag">The APE tag whose values are read.</param>
/// <param name="key">The name of the tag to read.</param>
/// <returns>Every value of the tag.</returns>
private static List<string> GetApeFields(TagLib.Ape.Tag apeTag, string key)
{
if (apeTag.HasItem(key) && apeTag.GetItem(key) is TagLib.Ape.Item apeItem)
return [.. apeItem.ToStringArray()];
return [];
}
/// <summary>
/// Reads the first non-empty value of an extended tag, from whichever container tag of the file carries it.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
/// <returns>The first non-empty value found, or <see langword="null"/> when the file carries none of the provided tags.</returns>
private static string? GetExtendedField(List<Func<string, List<string>>> extendedFields, params string[] keys)
{
foreach (Func<string, List<string>> extendedField in extendedFields)
{
foreach (string key in keys)
{
List<string> values = extendedField(key);
string? value = values.FirstOrDefault(candidate => !string.IsNullOrWhiteSpace(candidate));
if (!string.IsNullOrWhiteSpace(value))
return value;
}
}
return null;
}
/// <summary>
/// Reads every value of an extended tag, from whichever container tag of the file carries it.
/// </summary>
/// <param name="extendedFields">The extended fields of the file, in the order their containers are searched.</param>
/// <param name="keys">The candidate names of the extended tag to read, in the order they are tried.</param>
/// <returns>Every non-empty value found, or an empty list when the file carries none of the provided tags.</returns>
private static List<string> GetExtendedFields(List<Func<string, List<string>>> extendedFields, params string[] keys)
{
List<string> values = [];
foreach (Func<string, List<string>> extendedField in extendedFields)
foreach (string key in keys)
// A container whose keys are matched case insensitively resolves several case variant aliases to the same entry, so the values already read are not added again.
foreach (string value in extendedField(key))
if (!string.IsNullOrWhiteSpace(value) && !values.Contains(value, StringComparer.Ordinal))
values.Add(value);
return values;
}
/// <summary>
/// Keeps only the non-empty values of the provided collection, trimmed.
/// </summary>
/// <param name="values">The values to filter.</param>
/// <returns>The non-empty, trimmed values.</returns>
private static List<string> Filter(IEnumerable<string>? values)
{
return [.. (values ?? []).Where(value => !string.IsNullOrWhiteSpace(value)).Select(value => value.Trim())];
}
/// <summary>
/// Splits every provided value on the separators used to pack several values into a single tag, and keeps the non-empty results.
/// </summary>
/// <param name="values">The values to split.</param>
/// <returns>The individual values found.</returns>
private static List<string> SplitValues(IEnumerable<string> values)
{
return SplitValues(values, ['/', ';']);
}
/// <summary>
/// Splits every provided value on semicolons only, for the tags whose own values may contain a slash.
/// </summary>
/// <param name="values">The values to split.</param>
/// <returns>The individual values found.</returns>
private static List<string> SplitValuesOnSemicolons(IEnumerable<string> values)
{
return SplitValues(values, [';']);
}
/// <summary>
/// Splits every provided value on the provided separators, and keeps the non-empty results.
/// </summary>
/// <param name="values">The values to split.</param>
/// <param name="separators">The separators to split the values on.</param>
/// <returns>The individual values found.</returns>
private static List<string> SplitValues(IEnumerable<string> values, char[] separators)
{
List<string> result = [];
foreach (string value in values)
{
if (string.IsNullOrWhiteSpace(value))
continue;
foreach (string part in value.Split(separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
if (!string.IsNullOrWhiteSpace(part))
result.Add(part);
}
return result;
}
/// <summary>
/// Parses a date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
private static (DateOnly? Date, int? Year) ParseDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return (null, null);
if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact))
return (exact, exact.Year);
Match yearMatch = s_yearPattern.Match(value);
return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="TagLibSharp" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.IntegrationTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.ID3.Fixtures")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]