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