AudioFileProber.cs 15 KB

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