AudioFileProber.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. tags ??= new TagLib.Id3v2.Tag();
  179. tags.AlbumArtists ??= mediaInfo.AlbumArtists;
  180. tags.Album ??= mediaInfo.Album;
  181. tags.Title ??= mediaInfo.Name;
  182. tags.Year = tags.Year == 0U ? Convert.ToUInt32(mediaInfo.ProductionYear, CultureInfo.InvariantCulture) : tags.Year;
  183. tags.Performers ??= mediaInfo.Artists;
  184. tags.Genres ??= mediaInfo.Genres;
  185. tags.Track = tags.Track == 0U ? Convert.ToUInt32(mediaInfo.IndexNumber, CultureInfo.InvariantCulture) : tags.Track;
  186. tags.Disc = tags.Disc == 0U ? Convert.ToUInt32(mediaInfo.ParentIndexNumber, CultureInfo.InvariantCulture) : tags.Disc;
  187. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  188. {
  189. var people = new List<PersonInfo>();
  190. var albumArtists = tags.AlbumArtists;
  191. foreach (var albumArtist in albumArtists)
  192. {
  193. if (!string.IsNullOrEmpty(albumArtist))
  194. {
  195. PeopleHelper.AddPerson(people, new PersonInfo
  196. {
  197. Name = albumArtist,
  198. Type = PersonKind.AlbumArtist
  199. });
  200. }
  201. }
  202. var performers = tags.Performers;
  203. foreach (var performer in performers)
  204. {
  205. if (!string.IsNullOrEmpty(performer))
  206. {
  207. PeopleHelper.AddPerson(people, new PersonInfo
  208. {
  209. Name = performer,
  210. Type = PersonKind.Artist
  211. });
  212. }
  213. }
  214. foreach (var composer in tags.Composers)
  215. {
  216. if (!string.IsNullOrEmpty(composer))
  217. {
  218. PeopleHelper.AddPerson(people, new PersonInfo
  219. {
  220. Name = composer,
  221. Type = PersonKind.Composer
  222. });
  223. }
  224. }
  225. _libraryManager.UpdatePeople(audio, people);
  226. if (options.ReplaceAllMetadata && performers.Length != 0)
  227. {
  228. audio.Artists = performers;
  229. }
  230. else if (!options.ReplaceAllMetadata
  231. && (audio.Artists is null || audio.Artists.Count == 0))
  232. {
  233. audio.Artists = performers;
  234. }
  235. if (albumArtists.Length == 0)
  236. {
  237. // Album artists not provided, fall back to performers (artists).
  238. albumArtists = performers;
  239. }
  240. if (options.ReplaceAllMetadata && albumArtists.Length != 0)
  241. {
  242. audio.AlbumArtists = albumArtists;
  243. }
  244. else if (!options.ReplaceAllMetadata
  245. && (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0))
  246. {
  247. audio.AlbumArtists = albumArtists;
  248. }
  249. }
  250. if (!audio.LockedFields.Contains(MetadataField.Name) && !string.IsNullOrEmpty(tags.Title))
  251. {
  252. audio.Name = tags.Title;
  253. }
  254. if (options.ReplaceAllMetadata)
  255. {
  256. audio.Album = tags.Album;
  257. audio.IndexNumber = Convert.ToInt32(tags.Track);
  258. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  259. }
  260. else
  261. {
  262. audio.Album ??= tags.Album;
  263. audio.IndexNumber ??= Convert.ToInt32(tags.Track);
  264. audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
  265. }
  266. if (tags.Year != 0)
  267. {
  268. var year = Convert.ToInt32(tags.Year);
  269. audio.ProductionYear = year;
  270. if (!audio.PremiereDate.HasValue)
  271. {
  272. try
  273. {
  274. audio.PremiereDate = new DateTime(year, 01, 01);
  275. }
  276. catch (ArgumentOutOfRangeException ex)
  277. {
  278. _logger.LogError(ex, "Error parsing YEAR tag in {File}. '{TagValue}' is an invalid year", audio.Path, tags.Year);
  279. }
  280. }
  281. }
  282. if (!audio.LockedFields.Contains(MetadataField.Genres))
  283. {
  284. audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
  285. ? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
  286. : audio.Genres;
  287. }
  288. if (!double.IsNaN(tags.ReplayGainTrackGain))
  289. {
  290. audio.NormalizationGain = (float)tags.ReplayGainTrackGain;
  291. }
  292. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
  293. {
  294. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  295. }
  296. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
  297. {
  298. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  299. }
  300. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
  301. {
  302. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  303. }
  304. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
  305. {
  306. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  307. }
  308. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
  309. {
  310. // Fallback to ffprobe as TagLib incorrectly provides recording MBID in `tags.MusicBrainzTrackId`.
  311. // See https://github.com/mono/taglib-sharp/issues/304
  312. var trackMbId = mediaInfo.GetProviderId(MetadataProvider.MusicBrainzTrack);
  313. if (trackMbId is not null)
  314. {
  315. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, trackMbId);
  316. }
  317. }
  318. // Save extracted lyrics if they exist,
  319. // and if the audio doesn't yet have lyrics.
  320. if (!string.IsNullOrWhiteSpace(tags.Lyrics)
  321. && tryExtractEmbeddedLyrics)
  322. {
  323. await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
  324. }
  325. }
  326. private void AddExternalLyrics(
  327. Audio audio,
  328. List<MediaStream> currentStreams,
  329. MetadataRefreshOptions options)
  330. {
  331. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  332. var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, false);
  333. audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray();
  334. currentStreams.AddRange(externalLyricFiles);
  335. }
  336. }
  337. }