AudioFileProber.cs 14 KB

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