AudioFileProber.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 Jellyfin.Data.Enums;
  8. using Jellyfin.Extensions;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Entities.Audio;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Lyrics;
  13. using MediaBrowser.Controller.MediaEncoding;
  14. using MediaBrowser.Controller.Persistence;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Dlna;
  17. using MediaBrowser.Model.Dto;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.MediaInfo;
  20. using Microsoft.Extensions.Logging;
  21. using TagLib;
  22. namespace MediaBrowser.Providers.MediaInfo
  23. {
  24. /// <summary>
  25. /// Probes audio files for metadata.
  26. /// </summary>
  27. public class AudioFileProber
  28. {
  29. private readonly IMediaEncoder _mediaEncoder;
  30. private readonly IItemRepository _itemRepo;
  31. private readonly ILibraryManager _libraryManager;
  32. private readonly ILogger<AudioFileProber> _logger;
  33. private readonly IMediaSourceManager _mediaSourceManager;
  34. private readonly LyricResolver _lyricResolver;
  35. private readonly ILyricManager _lyricManager;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="AudioFileProber"/> class.
  38. /// </summary>
  39. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  40. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  41. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  42. /// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
  43. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  44. /// <param name="lyricResolver">Instance of the <see cref="LyricResolver"/> interface.</param>
  45. /// <param name="lyricManager">Instance of the <see cref="ILyricManager"/> interface.</param>
  46. public AudioFileProber(
  47. ILogger<AudioFileProber> logger,
  48. IMediaSourceManager mediaSourceManager,
  49. IMediaEncoder mediaEncoder,
  50. IItemRepository itemRepo,
  51. ILibraryManager libraryManager,
  52. LyricResolver lyricResolver,
  53. ILyricManager lyricManager)
  54. {
  55. _mediaEncoder = mediaEncoder;
  56. _itemRepo = itemRepo;
  57. _libraryManager = libraryManager;
  58. _logger = logger;
  59. _mediaSourceManager = mediaSourceManager;
  60. _lyricResolver = lyricResolver;
  61. _lyricManager = lyricManager;
  62. }
  63. /// <summary>
  64. /// Probes the specified item for metadata.
  65. /// </summary>
  66. /// <param name="item">The item to probe.</param>
  67. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  68. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  69. /// <typeparam name="T">The type of item to resolve.</typeparam>
  70. /// <returns>A <see cref="Task"/> probing the item for metadata.</returns>
  71. public async Task<ItemUpdateType> Probe<T>(
  72. T item,
  73. MetadataRefreshOptions options,
  74. CancellationToken cancellationToken)
  75. where T : Audio
  76. {
  77. var path = item.Path;
  78. var protocol = item.PathProtocol ?? MediaProtocol.File;
  79. if (!item.IsShortcut || options.EnableRemoteContentProbe)
  80. {
  81. if (item.IsShortcut)
  82. {
  83. path = item.ShortcutPath;
  84. protocol = _mediaSourceManager.GetPathProtocol(path);
  85. }
  86. var result = await _mediaEncoder.GetMediaInfo(
  87. new MediaInfoRequest
  88. {
  89. MediaType = DlnaProfileType.Audio,
  90. MediaSource = new MediaSourceInfo
  91. {
  92. Path = path,
  93. Protocol = protocol
  94. }
  95. },
  96. cancellationToken).ConfigureAwait(false);
  97. cancellationToken.ThrowIfCancellationRequested();
  98. await FetchAsync(item, result, options, cancellationToken).ConfigureAwait(false);
  99. }
  100. return ItemUpdateType.MetadataImport;
  101. }
  102. /// <summary>
  103. /// Fetches the specified audio.
  104. /// </summary>
  105. /// <param name="audio">The <see cref="Audio"/>.</param>
  106. /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
  107. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  108. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  109. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  110. private async Task FetchAsync(
  111. Audio audio,
  112. Model.MediaInfo.MediaInfo mediaInfo,
  113. MetadataRefreshOptions options,
  114. CancellationToken cancellationToken)
  115. {
  116. audio.Container = mediaInfo.Container;
  117. audio.TotalBitrate = mediaInfo.Bitrate;
  118. audio.RunTimeTicks = mediaInfo.RunTimeTicks;
  119. audio.Size = mediaInfo.Size;
  120. audio.PremiereDate = mediaInfo.PremiereDate;
  121. // Add external lyrics first to prevent the lrc file get overwritten on first scan
  122. var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
  123. AddExternalLyrics(audio, mediaStreams, options);
  124. var tryExtractEmbeddedLyrics = mediaStreams.All(s => s.Type != MediaStreamType.Lyric);
  125. if (!audio.IsLocked)
  126. {
  127. await FetchDataFromTags(audio, mediaInfo, options, tryExtractEmbeddedLyrics).ConfigureAwait(false);
  128. if (tryExtractEmbeddedLyrics)
  129. {
  130. AddExternalLyrics(audio, mediaStreams, options);
  131. }
  132. }
  133. audio.HasLyrics = mediaStreams.Any(s => s.Type == MediaStreamType.Lyric);
  134. _itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
  135. }
  136. /// <summary>
  137. /// Fetches data from the tags.
  138. /// </summary>
  139. /// <param name="audio">The <see cref="Audio"/>.</param>
  140. /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
  141. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  142. /// <param name="tryExtractEmbeddedLyrics">Whether to extract embedded lyrics to lrc file. </param>
  143. private async Task FetchDataFromTags(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, MetadataRefreshOptions options, bool tryExtractEmbeddedLyrics)
  144. {
  145. Tag? tags = null;
  146. try
  147. {
  148. using var file = TagLib.File.Create(audio.Path);
  149. var tagTypes = file.TagTypesOnDisk;
  150. if (tagTypes.HasFlag(TagTypes.Id3v2))
  151. {
  152. tags = file.GetTag(TagTypes.Id3v2);
  153. }
  154. else if (tagTypes.HasFlag(TagTypes.Ape))
  155. {
  156. tags = file.GetTag(TagTypes.Ape);
  157. }
  158. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  159. {
  160. tags = file.GetTag(TagTypes.FlacMetadata);
  161. }
  162. else if (tagTypes.HasFlag(TagTypes.Apple))
  163. {
  164. tags = file.GetTag(TagTypes.Apple);
  165. }
  166. else if (tagTypes.HasFlag(TagTypes.Xiph))
  167. {
  168. tags = file.GetTag(TagTypes.Xiph);
  169. }
  170. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  171. {
  172. tags = file.GetTag(TagTypes.AudibleMetadata);
  173. }
  174. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  175. {
  176. tags = file.GetTag(TagTypes.Id3v1);
  177. }
  178. }
  179. catch (Exception e)
  180. {
  181. _logger.LogWarning(e, "TagLib-Sharp does not support this audio");
  182. }
  183. tags ??= new TagLib.Id3v2.Tag();
  184. tags.AlbumArtists = tags.AlbumArtists.Length == 0 ? mediaInfo.AlbumArtists : tags.AlbumArtists;
  185. tags.Album ??= mediaInfo.Album;
  186. tags.Title ??= mediaInfo.Name;
  187. tags.Year = tags.Year == 0U ? Convert.ToUInt32(mediaInfo.ProductionYear, CultureInfo.InvariantCulture) : tags.Year;
  188. tags.Performers = tags.Performers.Length == 0 ? mediaInfo.Artists : tags.Performers;
  189. tags.Genres ??= mediaInfo.Genres;
  190. tags.Track = tags.Track == 0U ? Convert.ToUInt32(mediaInfo.IndexNumber, CultureInfo.InvariantCulture) : tags.Track;
  191. tags.Disc = tags.Disc == 0U ? Convert.ToUInt32(mediaInfo.ParentIndexNumber, CultureInfo.InvariantCulture) : tags.Disc;
  192. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  193. {
  194. var people = new List<PersonInfo>();
  195. var albumArtists = tags.AlbumArtists;
  196. foreach (var albumArtist in albumArtists)
  197. {
  198. if (!string.IsNullOrEmpty(albumArtist))
  199. {
  200. PeopleHelper.AddPerson(people, new PersonInfo
  201. {
  202. Name = albumArtist,
  203. Type = PersonKind.AlbumArtist
  204. });
  205. }
  206. }
  207. var performers = tags.Performers;
  208. foreach (var performer in performers)
  209. {
  210. if (!string.IsNullOrEmpty(performer))
  211. {
  212. PeopleHelper.AddPerson(people, new PersonInfo
  213. {
  214. Name = performer,
  215. Type = PersonKind.Artist
  216. });
  217. }
  218. }
  219. foreach (var composer in tags.Composers)
  220. {
  221. if (!string.IsNullOrEmpty(composer))
  222. {
  223. PeopleHelper.AddPerson(people, new PersonInfo
  224. {
  225. Name = composer,
  226. Type = PersonKind.Composer
  227. });
  228. }
  229. }
  230. _libraryManager.UpdatePeople(audio, people);
  231. if (options.ReplaceAllMetadata && performers.Length != 0)
  232. {
  233. audio.Artists = performers;
  234. }
  235. else if (!options.ReplaceAllMetadata
  236. && (audio.Artists is null || audio.Artists.Count == 0))
  237. {
  238. audio.Artists = performers;
  239. }
  240. if (albumArtists.Length == 0)
  241. {
  242. // Album artists not provided, fall back to performers (artists).
  243. albumArtists = performers;
  244. }
  245. if (options.ReplaceAllMetadata && albumArtists.Length != 0)
  246. {
  247. audio.AlbumArtists = albumArtists;
  248. }
  249. else if (!options.ReplaceAllMetadata
  250. && (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0))
  251. {
  252. audio.AlbumArtists = albumArtists;
  253. }
  254. }
  255. if (!audio.LockedFields.Contains(MetadataField.Name) && !string.IsNullOrEmpty(tags.Title))
  256. {
  257. audio.Name = tags.Title;
  258. }
  259. if (options.ReplaceAllMetadata)
  260. {
  261. audio.Album = tags.Album;
  262. audio.IndexNumber = Convert.ToInt32(tags.Track);
  263. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  264. }
  265. else
  266. {
  267. audio.Album ??= tags.Album;
  268. audio.IndexNumber ??= Convert.ToInt32(tags.Track);
  269. audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
  270. }
  271. if (tags.Year != 0)
  272. {
  273. var year = Convert.ToInt32(tags.Year);
  274. audio.ProductionYear = year;
  275. if (!audio.PremiereDate.HasValue)
  276. {
  277. try
  278. {
  279. audio.PremiereDate = new DateTime(year, 01, 01);
  280. }
  281. catch (ArgumentOutOfRangeException ex)
  282. {
  283. _logger.LogError(ex, "Error parsing YEAR tag in {File}. '{TagValue}' is an invalid year", audio.Path, tags.Year);
  284. }
  285. }
  286. }
  287. if (!audio.LockedFields.Contains(MetadataField.Genres))
  288. {
  289. audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
  290. ? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
  291. : audio.Genres;
  292. }
  293. if (!double.IsNaN(tags.ReplayGainTrackGain))
  294. {
  295. audio.NormalizationGain = (float)tags.ReplayGainTrackGain;
  296. }
  297. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
  298. {
  299. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  300. }
  301. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
  302. {
  303. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  304. }
  305. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
  306. {
  307. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  308. }
  309. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
  310. {
  311. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  312. }
  313. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
  314. {
  315. // Fallback to ffprobe as TagLib incorrectly provides recording MBID in `tags.MusicBrainzTrackId`.
  316. // See https://github.com/mono/taglib-sharp/issues/304
  317. var trackMbId = mediaInfo.GetProviderId(MetadataProvider.MusicBrainzTrack);
  318. if (trackMbId is not null)
  319. {
  320. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, trackMbId);
  321. }
  322. }
  323. // Save extracted lyrics if they exist,
  324. // and if the audio doesn't yet have lyrics.
  325. if (!string.IsNullOrWhiteSpace(tags.Lyrics)
  326. && tryExtractEmbeddedLyrics)
  327. {
  328. await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
  329. }
  330. }
  331. private void AddExternalLyrics(
  332. Audio audio,
  333. List<MediaStream> currentStreams,
  334. MetadataRefreshOptions options)
  335. {
  336. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  337. var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, false);
  338. audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray();
  339. if (externalLyricFiles.Count > 0)
  340. {
  341. currentStreams.Add(externalLyricFiles[0]);
  342. }
  343. }
  344. }
  345. }