| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using ATL; |
| | | 8 | | using Jellyfin.Data.Enums; |
| | | 9 | | using Jellyfin.Extensions; |
| | | 10 | | using MediaBrowser.Controller.Entities; |
| | | 11 | | using MediaBrowser.Controller.Entities.Audio; |
| | | 12 | | using MediaBrowser.Controller.Library; |
| | | 13 | | using MediaBrowser.Controller.Lyrics; |
| | | 14 | | using MediaBrowser.Controller.MediaEncoding; |
| | | 15 | | using MediaBrowser.Controller.Persistence; |
| | | 16 | | using MediaBrowser.Controller.Providers; |
| | | 17 | | using MediaBrowser.Model.Dlna; |
| | | 18 | | using MediaBrowser.Model.Dto; |
| | | 19 | | using MediaBrowser.Model.Entities; |
| | | 20 | | using MediaBrowser.Model.Extensions; |
| | | 21 | | using MediaBrowser.Model.MediaInfo; |
| | | 22 | | using Microsoft.Extensions.Logging; |
| | | 23 | | using static Jellyfin.Extensions.StringExtensions; |
| | | 24 | | |
| | | 25 | | namespace MediaBrowser.Providers.MediaInfo |
| | | 26 | | { |
| | | 27 | | /// <summary> |
| | | 28 | | /// Probes audio files for metadata. |
| | | 29 | | /// </summary> |
| | | 30 | | public class AudioFileProber |
| | | 31 | | { |
| | | 32 | | private const char InternalValueSeparator = '\u001F'; |
| | | 33 | | |
| | | 34 | | private readonly IMediaEncoder _mediaEncoder; |
| | | 35 | | private readonly ILibraryManager _libraryManager; |
| | | 36 | | private readonly ILogger<AudioFileProber> _logger; |
| | | 37 | | private readonly IMediaSourceManager _mediaSourceManager; |
| | | 38 | | private readonly LyricResolver _lyricResolver; |
| | | 39 | | private readonly ILyricManager _lyricManager; |
| | | 40 | | private readonly IMediaStreamRepository _mediaStreamRepository; |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Initializes a new instance of the <see cref="AudioFileProber"/> class. |
| | | 44 | | /// </summary> |
| | | 45 | | /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param> |
| | | 46 | | /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param> |
| | | 47 | | /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param> |
| | | 48 | | /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> |
| | | 49 | | /// <param name="lyricResolver">Instance of the <see cref="LyricResolver"/> interface.</param> |
| | | 50 | | /// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param> |
| | | 51 | | /// <param name="mediaStreamRepository">Instance of the <see cref="IMediaStreamRepository"/>.</param> |
| | | 52 | | public AudioFileProber( |
| | | 53 | | ILogger<AudioFileProber> logger, |
| | | 54 | | IMediaSourceManager mediaSourceManager, |
| | | 55 | | IMediaEncoder mediaEncoder, |
| | | 56 | | ILibraryManager libraryManager, |
| | | 57 | | LyricResolver lyricResolver, |
| | | 58 | | ILyricManager lyricManager, |
| | | 59 | | IMediaStreamRepository mediaStreamRepository) |
| | | 60 | | { |
| | 21 | 61 | | _mediaEncoder = mediaEncoder; |
| | 21 | 62 | | _libraryManager = libraryManager; |
| | 21 | 63 | | _logger = logger; |
| | 21 | 64 | | _mediaSourceManager = mediaSourceManager; |
| | 21 | 65 | | _lyricResolver = lyricResolver; |
| | 21 | 66 | | _lyricManager = lyricManager; |
| | 21 | 67 | | _mediaStreamRepository = mediaStreamRepository; |
| | 21 | 68 | | ATL.Settings.DisplayValueSeparator = InternalValueSeparator; |
| | 21 | 69 | | ATL.Settings.UseFileNameWhenNoTitle = false; |
| | 21 | 70 | | ATL.Settings.ID3v2_separatev2v3Values = false; |
| | 21 | 71 | | } |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Probes the specified item for metadata. |
| | | 75 | | /// </summary> |
| | | 76 | | /// <param name="item">The item to probe.</param> |
| | | 77 | | /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param> |
| | | 78 | | /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> |
| | | 79 | | /// <typeparam name="T">The type of item to resolve.</typeparam> |
| | | 80 | | /// <returns>A <see cref="Task"/> probing the item for metadata.</returns> |
| | | 81 | | public async Task<ItemUpdateType> Probe<T>( |
| | | 82 | | T item, |
| | | 83 | | MetadataRefreshOptions options, |
| | | 84 | | CancellationToken cancellationToken) |
| | | 85 | | where T : Audio |
| | | 86 | | { |
| | | 87 | | var path = item.Path; |
| | | 88 | | var protocol = item.PathProtocol ?? MediaProtocol.File; |
| | | 89 | | |
| | | 90 | | if (!item.IsShortcut || options.EnableRemoteContentProbe) |
| | | 91 | | { |
| | | 92 | | if (item.IsShortcut) |
| | | 93 | | { |
| | | 94 | | path = item.ShortcutPath; |
| | | 95 | | protocol = _mediaSourceManager.GetPathProtocol(path); |
| | | 96 | | } |
| | | 97 | | |
| | | 98 | | var result = await _mediaEncoder.GetMediaInfo( |
| | | 99 | | new MediaInfoRequest |
| | | 100 | | { |
| | | 101 | | MediaType = DlnaProfileType.Audio, |
| | | 102 | | MediaSource = new MediaSourceInfo |
| | | 103 | | { |
| | | 104 | | Path = path, |
| | | 105 | | Protocol = protocol |
| | | 106 | | } |
| | | 107 | | }, |
| | | 108 | | cancellationToken).ConfigureAwait(false); |
| | | 109 | | |
| | | 110 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 111 | | |
| | | 112 | | await FetchAsync(item, result, options, cancellationToken).ConfigureAwait(false); |
| | | 113 | | } |
| | | 114 | | |
| | | 115 | | return ItemUpdateType.MetadataImport; |
| | | 116 | | } |
| | | 117 | | |
| | | 118 | | /// <summary> |
| | | 119 | | /// Fetches the specified audio. |
| | | 120 | | /// </summary> |
| | | 121 | | /// <param name="audio">The <see cref="Audio"/>.</param> |
| | | 122 | | /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param> |
| | | 123 | | /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param> |
| | | 124 | | /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param> |
| | | 125 | | /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> |
| | | 126 | | private async Task FetchAsync( |
| | | 127 | | Audio audio, |
| | | 128 | | Model.MediaInfo.MediaInfo mediaInfo, |
| | | 129 | | MetadataRefreshOptions options, |
| | | 130 | | CancellationToken cancellationToken) |
| | | 131 | | { |
| | | 132 | | audio.Container = mediaInfo.Container; |
| | | 133 | | audio.TotalBitrate = mediaInfo.Bitrate; |
| | | 134 | | |
| | | 135 | | audio.RunTimeTicks = mediaInfo.RunTimeTicks; |
| | | 136 | | |
| | | 137 | | // Add external lyrics first to prevent the lrc file get overwritten on first scan |
| | | 138 | | var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams); |
| | | 139 | | AddExternalLyrics(audio, mediaStreams, options); |
| | | 140 | | var tryExtractEmbeddedLyrics = mediaStreams.All(s => s.Type != MediaStreamType.Lyric); |
| | | 141 | | |
| | | 142 | | if (!audio.IsLocked) |
| | | 143 | | { |
| | | 144 | | await FetchDataFromTags(audio, mediaInfo, options, tryExtractEmbeddedLyrics).ConfigureAwait(false); |
| | | 145 | | if (tryExtractEmbeddedLyrics) |
| | | 146 | | { |
| | | 147 | | AddExternalLyrics(audio, mediaStreams, options); |
| | | 148 | | } |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | audio.HasLyrics = mediaStreams.Any(s => s.Type == MediaStreamType.Lyric); |
| | | 152 | | |
| | | 153 | | _mediaStreamRepository.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken); |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Fetches data from the tags. |
| | | 158 | | /// </summary> |
| | | 159 | | /// <param name="audio">The <see cref="Audio"/>.</param> |
| | | 160 | | /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param> |
| | | 161 | | /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param> |
| | | 162 | | /// <param name="tryExtractEmbeddedLyrics">Whether to extract embedded lyrics to lrc file. </param> |
| | | 163 | | private async Task FetchDataFromTags(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, MetadataRefreshOptions op |
| | | 164 | | { |
| | | 165 | | var libraryOptions = _libraryManager.GetLibraryOptions(audio); |
| | | 166 | | Track track = new Track(audio.Path); |
| | | 167 | | |
| | | 168 | | if (track.MetadataFormats |
| | | 169 | | .All(mf => string.Equals(mf.ShortName, "ID3v1", StringComparison.OrdinalIgnoreCase))) |
| | | 170 | | { |
| | | 171 | | _logger.LogWarning("File {File} only has ID3v1 tags, some fields may be truncated", audio.Path); |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | // We should never use the property setter of the ATL.Track class. |
| | | 175 | | // That setter is meant for its own tag parser and external editor usage and will have unwanted side effects |
| | | 176 | | // For example, setting the Year property will also set the Date property, which is not what we want here. |
| | | 177 | | // To properly handle fallback values, we make a clone of those fields when valid. |
| | | 178 | | var trackTitle = (string.IsNullOrEmpty(track.Title) ? mediaInfo.Name : track.Title)?.Trim(); |
| | | 179 | | var trackAlbum = (string.IsNullOrEmpty(track.Album) ? mediaInfo.Album : track.Album)?.Trim(); |
| | | 180 | | var trackYear = track.Year is null or 0 ? mediaInfo.ProductionYear : track.Year; |
| | | 181 | | var trackTrackNumber = track.TrackNumber is null or 0 ? mediaInfo.IndexNumber : track.TrackNumber; |
| | | 182 | | var trackDiscNumber = track.DiscNumber is null or 0 ? mediaInfo.ParentIndexNumber : track.DiscNumber; |
| | | 183 | | |
| | | 184 | | // Some users may use a misbehaved tag editor that writes a null character in the tag when not allowed by th |
| | | 185 | | trackTitle = GetSanitizedStringTag(trackTitle, audio.Path); |
| | | 186 | | trackAlbum = GetSanitizedStringTag(trackAlbum, audio.Path); |
| | | 187 | | var trackAlbumArtist = GetSanitizedStringTag(track.AlbumArtist, audio.Path); |
| | | 188 | | var trackArist = GetSanitizedStringTag(track.Artist, audio.Path); |
| | | 189 | | var trackComposer = GetSanitizedStringTag(track.Composer, audio.Path); |
| | | 190 | | var trackGenre = GetSanitizedStringTag(track.Genre, audio.Path); |
| | | 191 | | |
| | | 192 | | if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast)) |
| | | 193 | | { |
| | | 194 | | var people = new List<PersonInfo>(); |
| | | 195 | | string[]? albumArtists = null; |
| | | 196 | | if (libraryOptions.PreferNonstandardArtistsTag) |
| | | 197 | | { |
| | | 198 | | TryGetSanitizedAdditionalFields(track, "ALBUMARTISTS", out var albumArtistsTagString); |
| | | 199 | | if (albumArtistsTagString is not null) |
| | | 200 | | { |
| | | 201 | | albumArtists = albumArtistsTagString.Split(InternalValueSeparator); |
| | | 202 | | } |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | if (albumArtists is null || albumArtists.Length == 0) |
| | | 206 | | { |
| | | 207 | | albumArtists = string.IsNullOrEmpty(trackAlbumArtist) ? [] : trackAlbumArtist.Split(InternalValueSep |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | if (libraryOptions.UseCustomTagDelimiters) |
| | | 211 | | { |
| | | 212 | | albumArtists = albumArtists.SelectMany(a => SplitWithCustomDelimiter(a, libraryOptions.GetCustomTagD |
| | | 213 | | } |
| | | 214 | | |
| | | 215 | | foreach (var albumArtist in albumArtists) |
| | | 216 | | { |
| | | 217 | | if (!string.IsNullOrWhiteSpace(albumArtist)) |
| | | 218 | | { |
| | | 219 | | PeopleHelper.AddPerson(people, new PersonInfo |
| | | 220 | | { |
| | | 221 | | Name = albumArtist, |
| | | 222 | | Type = PersonKind.AlbumArtist |
| | | 223 | | }); |
| | | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | string[]? performers = null; |
| | | 228 | | if (libraryOptions.PreferNonstandardArtistsTag) |
| | | 229 | | { |
| | | 230 | | TryGetSanitizedAdditionalFields(track, "ARTISTS", out var artistsTagString); |
| | | 231 | | if (artistsTagString is not null) |
| | | 232 | | { |
| | | 233 | | performers = artistsTagString.Split(InternalValueSeparator); |
| | | 234 | | } |
| | | 235 | | } |
| | | 236 | | |
| | | 237 | | if (performers is null || performers.Length == 0) |
| | | 238 | | { |
| | | 239 | | performers = string.IsNullOrEmpty(trackArist) ? [] : trackArist.Split(InternalValueSeparator); |
| | | 240 | | } |
| | | 241 | | |
| | | 242 | | if (libraryOptions.UseCustomTagDelimiters) |
| | | 243 | | { |
| | | 244 | | performers = performers.SelectMany(p => SplitWithCustomDelimiter(p, libraryOptions.GetCustomTagDelim |
| | | 245 | | } |
| | | 246 | | |
| | | 247 | | foreach (var performer in performers) |
| | | 248 | | { |
| | | 249 | | if (!string.IsNullOrWhiteSpace(performer)) |
| | | 250 | | { |
| | | 251 | | PeopleHelper.AddPerson(people, new PersonInfo |
| | | 252 | | { |
| | | 253 | | Name = performer, |
| | | 254 | | Type = PersonKind.Artist |
| | | 255 | | }); |
| | | 256 | | } |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | if (!string.IsNullOrWhiteSpace(trackComposer)) |
| | | 260 | | { |
| | | 261 | | foreach (var composer in trackComposer.Split(InternalValueSeparator)) |
| | | 262 | | { |
| | | 263 | | if (!string.IsNullOrWhiteSpace(composer)) |
| | | 264 | | { |
| | | 265 | | PeopleHelper.AddPerson(people, new PersonInfo |
| | | 266 | | { |
| | | 267 | | Name = composer, |
| | | 268 | | Type = PersonKind.Composer |
| | | 269 | | }); |
| | | 270 | | } |
| | | 271 | | } |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | _libraryManager.UpdatePeople(audio, people); |
| | | 275 | | |
| | | 276 | | if (options.ReplaceAllMetadata && performers.Length != 0) |
| | | 277 | | { |
| | | 278 | | audio.Artists = performers; |
| | | 279 | | } |
| | | 280 | | else if (!options.ReplaceAllMetadata |
| | | 281 | | && (audio.Artists is null || audio.Artists.Count == 0)) |
| | | 282 | | { |
| | | 283 | | audio.Artists = performers; |
| | | 284 | | } |
| | | 285 | | |
| | | 286 | | if (albumArtists.Length == 0) |
| | | 287 | | { |
| | | 288 | | // Album artists not provided, fall back to performers (artists). |
| | | 289 | | albumArtists = performers; |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | if (options.ReplaceAllMetadata && albumArtists.Length != 0) |
| | | 293 | | { |
| | | 294 | | audio.AlbumArtists = albumArtists; |
| | | 295 | | } |
| | | 296 | | else if (!options.ReplaceAllMetadata |
| | | 297 | | && (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0)) |
| | | 298 | | { |
| | | 299 | | audio.AlbumArtists = albumArtists; |
| | | 300 | | } |
| | | 301 | | } |
| | | 302 | | |
| | | 303 | | if (!audio.LockedFields.Contains(MetadataField.Name) && !string.IsNullOrEmpty(trackTitle)) |
| | | 304 | | { |
| | | 305 | | audio.Name = trackTitle; |
| | | 306 | | } |
| | | 307 | | |
| | | 308 | | if (options.ReplaceAllMetadata) |
| | | 309 | | { |
| | | 310 | | audio.Album = trackAlbum; |
| | | 311 | | audio.IndexNumber = trackTrackNumber; |
| | | 312 | | audio.ParentIndexNumber = trackDiscNumber; |
| | | 313 | | } |
| | | 314 | | else |
| | | 315 | | { |
| | | 316 | | audio.Album ??= trackAlbum; |
| | | 317 | | audio.IndexNumber ??= trackTrackNumber; |
| | | 318 | | audio.ParentIndexNumber ??= trackDiscNumber; |
| | | 319 | | } |
| | | 320 | | |
| | | 321 | | if (track.Date.HasValue) |
| | | 322 | | { |
| | | 323 | | audio.PremiereDate = track.Date; |
| | | 324 | | } |
| | | 325 | | |
| | | 326 | | if (trackYear.HasValue) |
| | | 327 | | { |
| | | 328 | | var year = trackYear.Value; |
| | | 329 | | audio.ProductionYear = year; |
| | | 330 | | |
| | | 331 | | // ATL library handles such fallback this with its own internal logic, but we also need to handle it her |
| | | 332 | | if (!audio.PremiereDate.HasValue) |
| | | 333 | | { |
| | | 334 | | try |
| | | 335 | | { |
| | | 336 | | audio.PremiereDate = new DateTime(year, 01, 01); |
| | | 337 | | } |
| | | 338 | | catch (ArgumentOutOfRangeException ex) |
| | | 339 | | { |
| | | 340 | | _logger.LogError(ex, "Error parsing YEAR tag in {File}. '{TagValue}' is an invalid year", audio. |
| | | 341 | | } |
| | | 342 | | } |
| | | 343 | | } |
| | | 344 | | |
| | | 345 | | if (!audio.LockedFields.Contains(MetadataField.Genres)) |
| | | 346 | | { |
| | | 347 | | var genres = string.IsNullOrEmpty(trackGenre) ? [] : trackGenre.Split(InternalValueSeparator).Distinct(S |
| | | 348 | | |
| | | 349 | | if (libraryOptions.UseCustomTagDelimiters) |
| | | 350 | | { |
| | | 351 | | genres = genres.SelectMany(g => SplitWithCustomDelimiter(g, libraryOptions.GetCustomTagDelimiters(), |
| | | 352 | | } |
| | | 353 | | |
| | | 354 | | genres = genres.Trimmed().Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); |
| | | 355 | | |
| | | 356 | | if (options.ReplaceAllMetadata || audio.Genres is null || audio.Genres.Length == 0 || audio.Genres.All(s |
| | | 357 | | { |
| | | 358 | | audio.Genres = genres; |
| | | 359 | | } |
| | | 360 | | } |
| | | 361 | | |
| | | 362 | | TryGetSanitizedAdditionalFields(track, "REPLAYGAIN_TRACK_GAIN", out var trackGainTag); |
| | | 363 | | |
| | | 364 | | if (trackGainTag is not null) |
| | | 365 | | { |
| | | 366 | | if (trackGainTag.EndsWith("db", StringComparison.OrdinalIgnoreCase)) |
| | | 367 | | { |
| | | 368 | | trackGainTag = trackGainTag[..^2].Trim(); |
| | | 369 | | } |
| | | 370 | | |
| | | 371 | | if (float.TryParse(trackGainTag, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && flo |
| | | 372 | | { |
| | | 373 | | audio.NormalizationGain = value; |
| | | 374 | | } |
| | | 375 | | } |
| | | 376 | | |
| | | 377 | | if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _)) |
| | | 378 | | { |
| | | 379 | | if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_ARTISTID", out var musicBrainzArtistTag) |
| | | 380 | | || TryGetSanitizedAdditionalFields(track, "MusicBrainz Artist Id", out musicBrainzArtistTag)) |
| | | 381 | | && !string.IsNullOrEmpty(musicBrainzArtistTag)) |
| | | 382 | | { |
| | | 383 | | var id = GetFirstMusicBrainzId(musicBrainzArtistTag, libraryOptions.UseCustomTagDelimiters, libraryO |
| | | 384 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzArtist, id); |
| | | 385 | | } |
| | | 386 | | } |
| | | 387 | | |
| | | 388 | | if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _)) |
| | | 389 | | { |
| | | 390 | | if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_ALBUMARTISTID", out var musicBrainzReleaseArtis |
| | | 391 | | || TryGetSanitizedAdditionalFields(track, "MusicBrainz Album Artist Id", out musicBrainzReleaseArti |
| | | 392 | | && !string.IsNullOrEmpty(musicBrainzReleaseArtistIdTag)) |
| | | 393 | | { |
| | | 394 | | var id = GetFirstMusicBrainzId(musicBrainzReleaseArtistIdTag, libraryOptions.UseCustomTagDelimiters, |
| | | 395 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbumArtist, id); |
| | | 396 | | } |
| | | 397 | | } |
| | | 398 | | |
| | | 399 | | if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _)) |
| | | 400 | | { |
| | | 401 | | if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_ALBUMID", out var musicBrainzReleaseIdTag) |
| | | 402 | | || TryGetSanitizedAdditionalFields(track, "MusicBrainz Album Id", out musicBrainzReleaseIdTag)) |
| | | 403 | | && !string.IsNullOrEmpty(musicBrainzReleaseIdTag)) |
| | | 404 | | { |
| | | 405 | | var id = GetFirstMusicBrainzId(musicBrainzReleaseIdTag, libraryOptions.UseCustomTagDelimiters, libra |
| | | 406 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzAlbum, id); |
| | | 407 | | } |
| | | 408 | | } |
| | | 409 | | |
| | | 410 | | if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _)) |
| | | 411 | | { |
| | | 412 | | if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_RELEASEGROUPID", out var musicBrainzReleaseGrou |
| | | 413 | | || TryGetSanitizedAdditionalFields(track, "MusicBrainz Release Group Id", out musicBrainzReleaseGro |
| | | 414 | | && !string.IsNullOrEmpty(musicBrainzReleaseGroupIdTag)) |
| | | 415 | | { |
| | | 416 | | var id = GetFirstMusicBrainzId(musicBrainzReleaseGroupIdTag, libraryOptions.UseCustomTagDelimiters, |
| | | 417 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzReleaseGroup, id); |
| | | 418 | | } |
| | | 419 | | } |
| | | 420 | | |
| | | 421 | | if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _)) |
| | | 422 | | { |
| | | 423 | | if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_RELEASETRACKID", out var trackMbId) |
| | | 424 | | || TryGetSanitizedAdditionalFields(track, "MusicBrainz Release Track Id", out trackMbId)) |
| | | 425 | | && !string.IsNullOrEmpty(trackMbId)) |
| | | 426 | | { |
| | | 427 | | var id = GetFirstMusicBrainzId(trackMbId, libraryOptions.UseCustomTagDelimiters, libraryOptions.GetC |
| | | 428 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzTrack, id); |
| | | 429 | | } |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzRecording, out _)) |
| | | 433 | | { |
| | | 434 | | if ((TryGetSanitizedAdditionalFields(track, "MUSICBRAINZ_TRACKID", out var recordingMbId) |
| | | 435 | | || TryGetSanitizedAdditionalFields(track, "MusicBrainz Track Id", out recordingMbId)) |
| | | 436 | | && !string.IsNullOrEmpty(recordingMbId)) |
| | | 437 | | { |
| | | 438 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzRecording, recordingMbId); |
| | | 439 | | } |
| | | 440 | | else if (TryGetSanitizedUFIDFields(track, out var owner, out var identifier) && !string.IsNullOrEmpty(ow |
| | | 441 | | { |
| | | 442 | | // If tagged with MB Picard, the format is 'http://musicbrainz.org\0<recording MBID>' |
| | | 443 | | if (owner.Contains("musicbrainz.org", StringComparison.OrdinalIgnoreCase)) |
| | | 444 | | { |
| | | 445 | | audio.TrySetProviderId(MetadataProvider.MusicBrainzRecording, identifier); |
| | | 446 | | } |
| | | 447 | | } |
| | | 448 | | } |
| | | 449 | | |
| | | 450 | | // Save extracted lyrics if they exist, |
| | | 451 | | // and if the audio doesn't yet have lyrics. |
| | | 452 | | // ATL supports both SRT and LRC formats as synchronized lyrics, but we only want to save LRC format. |
| | | 453 | | var supportedLyrics = track.Lyrics.Where(l => l.Format != LyricsInfo.LyricsFormat.SRT).ToList(); |
| | | 454 | | var candidateSynchronizedLyric = supportedLyrics.FirstOrDefault(l => l.Format is not LyricsInfo.LyricsFormat |
| | | 455 | | var candidateUnsynchronizedLyric = supportedLyrics.FirstOrDefault(l => l.Format is LyricsInfo.LyricsFormat.U |
| | | 456 | | var lyrics = candidateSynchronizedLyric is not null ? candidateSynchronizedLyric.FormatSynch() : candidateUn |
| | | 457 | | if (!string.IsNullOrWhiteSpace(lyrics) |
| | | 458 | | && tryExtractEmbeddedLyrics) |
| | | 459 | | { |
| | | 460 | | await _lyricManager.SaveLyricAsync(audio, "lrc", lyrics).ConfigureAwait(false); |
| | | 461 | | } |
| | | 462 | | } |
| | | 463 | | |
| | | 464 | | private void AddExternalLyrics( |
| | | 465 | | Audio audio, |
| | | 466 | | List<MediaStream> currentStreams, |
| | | 467 | | MetadataRefreshOptions options) |
| | | 468 | | { |
| | 0 | 469 | | var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1); |
| | 0 | 470 | | var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, fals |
| | | 471 | | |
| | 0 | 472 | | audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray(); |
| | 0 | 473 | | if (externalLyricFiles.Count > 0) |
| | | 474 | | { |
| | 0 | 475 | | currentStreams.Add(externalLyricFiles[0]); |
| | | 476 | | } |
| | 0 | 477 | | } |
| | | 478 | | |
| | | 479 | | private List<string> SplitWithCustomDelimiter(string val, char[] tagDelimiters, string[] whitelist) |
| | | 480 | | { |
| | 0 | 481 | | var items = new List<string>(); |
| | 0 | 482 | | var temp = val; |
| | 0 | 483 | | foreach (var whitelistItem in whitelist) |
| | | 484 | | { |
| | 0 | 485 | | if (string.IsNullOrWhiteSpace(whitelistItem)) |
| | | 486 | | { |
| | | 487 | | continue; |
| | | 488 | | } |
| | | 489 | | |
| | 0 | 490 | | var originalTemp = temp; |
| | 0 | 491 | | temp = temp.Replace(whitelistItem, string.Empty, StringComparison.OrdinalIgnoreCase); |
| | | 492 | | |
| | 0 | 493 | | if (!string.Equals(temp, originalTemp, StringComparison.OrdinalIgnoreCase)) |
| | | 494 | | { |
| | 0 | 495 | | items.Add(whitelistItem); |
| | | 496 | | } |
| | | 497 | | } |
| | | 498 | | |
| | 0 | 499 | | var items2 = temp.Split(tagDelimiters, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntrie |
| | 0 | 500 | | items.AddRange(items2); |
| | | 501 | | |
| | 0 | 502 | | return items; |
| | | 503 | | } |
| | | 504 | | |
| | | 505 | | // MusicBrainz IDs are multi-value tags, so we need to split them |
| | | 506 | | // However, our current provider can only have one single ID, which means we need to pick the first one |
| | | 507 | | private string? GetFirstMusicBrainzId(string tag, bool useCustomTagDelimiters, char[] tagDelimiters, string[] wh |
| | | 508 | | { |
| | 0 | 509 | | var val = tag.Split(InternalValueSeparator).FirstOrDefault(); |
| | 0 | 510 | | if (val is not null && useCustomTagDelimiters) |
| | | 511 | | { |
| | 0 | 512 | | val = SplitWithCustomDelimiter(val, tagDelimiters, whitelist).FirstOrDefault(); |
| | | 513 | | } |
| | | 514 | | |
| | 0 | 515 | | return val; |
| | | 516 | | } |
| | | 517 | | |
| | | 518 | | private string? GetSanitizedStringTag(string? tag, string filePath) |
| | | 519 | | { |
| | 0 | 520 | | if (string.IsNullOrEmpty(tag)) |
| | | 521 | | { |
| | 0 | 522 | | return null; |
| | | 523 | | } |
| | | 524 | | |
| | 0 | 525 | | var result = tag.TruncateAtNull(); |
| | 0 | 526 | | if (result.Length != tag.Length) |
| | | 527 | | { |
| | 0 | 528 | | _logger.LogWarning("Audio file {File} contains a null character in its tag, but this is not allowed by i |
| | | 529 | | } |
| | | 530 | | |
| | 0 | 531 | | return result; |
| | | 532 | | } |
| | | 533 | | |
| | | 534 | | private bool TryGetSanitizedAdditionalFields(Track track, string field, out string? value) |
| | | 535 | | { |
| | 0 | 536 | | var hasField = TryGetAdditionalFieldWithFallback(track, field, out value); |
| | 0 | 537 | | value = GetSanitizedStringTag(value, track.Path); |
| | 0 | 538 | | return hasField; |
| | | 539 | | } |
| | | 540 | | |
| | | 541 | | private bool TryGetSanitizedUFIDFields(Track track, out string? owner, out string? identifier) |
| | | 542 | | { |
| | 0 | 543 | | var hasField = TryGetAdditionalFieldWithFallback(track, "UFID", out string? value); |
| | 0 | 544 | | if (hasField && !string.IsNullOrEmpty(value)) |
| | | 545 | | { |
| | 0 | 546 | | string[] parts = value.Split('\0'); |
| | 0 | 547 | | if (parts.Length == 2) |
| | | 548 | | { |
| | 0 | 549 | | owner = GetSanitizedStringTag(parts[0], track.Path); |
| | 0 | 550 | | identifier = GetSanitizedStringTag(parts[1], track.Path); |
| | 0 | 551 | | return true; |
| | | 552 | | } |
| | | 553 | | } |
| | | 554 | | |
| | 0 | 555 | | owner = null; |
| | 0 | 556 | | identifier = null; |
| | 0 | 557 | | return false; |
| | | 558 | | } |
| | | 559 | | |
| | | 560 | | // Build the explicit mka-style fallback key (e.g., ARTISTS -> track.artists, "MusicBrainz Artist Id" -> track.m |
| | | 561 | | private static string GetMkaFallbackKey(string key) |
| | | 562 | | { |
| | 0 | 563 | | if (string.IsNullOrWhiteSpace(key)) |
| | | 564 | | { |
| | 0 | 565 | | return key; |
| | | 566 | | } |
| | | 567 | | |
| | 0 | 568 | | var normalized = key.Trim().Replace(' ', '_').ToLowerInvariant(); |
| | 0 | 569 | | return "track." + normalized; |
| | | 570 | | } |
| | | 571 | | |
| | | 572 | | // First try the normal key exactly; if missing, try the mka-style fallback key. |
| | | 573 | | private bool TryGetAdditionalFieldWithFallback(Track track, string key, out string? value) |
| | | 574 | | { |
| | | 575 | | // Prefer the normal key (as-is, case-sensitive) |
| | 0 | 576 | | if (track.AdditionalFields.TryGetValue(key, out value)) |
| | | 577 | | { |
| | 0 | 578 | | return true; |
| | | 579 | | } |
| | | 580 | | |
| | | 581 | | // Fallback to mka-style: "track." + lower-case(original key) |
| | 0 | 582 | | var fallbackKey = GetMkaFallbackKey(key); |
| | 0 | 583 | | if (track.AdditionalFields.TryGetValue(fallbackKey, out value)) |
| | | 584 | | { |
| | 0 | 585 | | return true; |
| | | 586 | | } |
| | | 587 | | |
| | 0 | 588 | | value = null; |
| | 0 | 589 | | return false; |
| | | 590 | | } |
| | | 591 | | } |
| | | 592 | | } |