AudioFileProber.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. if (!audio.IsLocked)
  115. {
  116. await FetchDataFromTags(audio, mediaInfo, options).ConfigureAwait(false);
  117. }
  118. var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
  119. AddExternalLyrics(audio, mediaStreams, options);
  120. audio.HasLyrics = mediaStreams.Any(s => s.Type == MediaStreamType.Lyric);
  121. _itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
  122. }
  123. /// <summary>
  124. /// Fetches data from the tags.
  125. /// </summary>
  126. /// <param name="audio">The <see cref="Audio"/>.</param>
  127. /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
  128. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  129. private async Task FetchDataFromTags(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, MetadataRefreshOptions options)
  130. {
  131. using var file = TagLib.File.Create(audio.Path);
  132. var tagTypes = file.TagTypesOnDisk;
  133. Tag? tags = null;
  134. if (tagTypes.HasFlag(TagTypes.Id3v2))
  135. {
  136. tags = file.GetTag(TagTypes.Id3v2);
  137. }
  138. else if (tagTypes.HasFlag(TagTypes.Ape))
  139. {
  140. tags = file.GetTag(TagTypes.Ape);
  141. }
  142. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  143. {
  144. tags = file.GetTag(TagTypes.FlacMetadata);
  145. }
  146. else if (tagTypes.HasFlag(TagTypes.Apple))
  147. {
  148. tags = file.GetTag(TagTypes.Apple);
  149. }
  150. else if (tagTypes.HasFlag(TagTypes.Xiph))
  151. {
  152. tags = file.GetTag(TagTypes.Xiph);
  153. }
  154. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  155. {
  156. tags = file.GetTag(TagTypes.AudibleMetadata);
  157. }
  158. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  159. {
  160. tags = file.GetTag(TagTypes.Id3v1);
  161. }
  162. if (tags is not null)
  163. {
  164. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  165. {
  166. var people = new List<PersonInfo>();
  167. var albumArtists = tags.AlbumArtists;
  168. foreach (var albumArtist in albumArtists)
  169. {
  170. if (!string.IsNullOrEmpty(albumArtist))
  171. {
  172. PeopleHelper.AddPerson(people, new PersonInfo
  173. {
  174. Name = albumArtist,
  175. Type = PersonKind.AlbumArtist
  176. });
  177. }
  178. }
  179. var performers = tags.Performers;
  180. foreach (var performer in performers)
  181. {
  182. if (!string.IsNullOrEmpty(performer))
  183. {
  184. PeopleHelper.AddPerson(people, new PersonInfo
  185. {
  186. Name = performer,
  187. Type = PersonKind.Artist
  188. });
  189. }
  190. }
  191. foreach (var composer in tags.Composers)
  192. {
  193. if (!string.IsNullOrEmpty(composer))
  194. {
  195. PeopleHelper.AddPerson(people, new PersonInfo
  196. {
  197. Name = composer,
  198. Type = PersonKind.Composer
  199. });
  200. }
  201. }
  202. _libraryManager.UpdatePeople(audio, people);
  203. if (options.ReplaceAllMetadata && performers.Length != 0)
  204. {
  205. audio.Artists = performers;
  206. }
  207. else if (!options.ReplaceAllMetadata
  208. && (audio.Artists is null || audio.Artists.Count == 0))
  209. {
  210. audio.Artists = performers;
  211. }
  212. if (albumArtists.Length == 0)
  213. {
  214. // Album artists not provided, fall back to performers (artists).
  215. albumArtists = performers;
  216. }
  217. if (options.ReplaceAllMetadata && albumArtists.Length != 0)
  218. {
  219. audio.AlbumArtists = albumArtists;
  220. }
  221. else if (!options.ReplaceAllMetadata
  222. && (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0))
  223. {
  224. audio.AlbumArtists = albumArtists;
  225. }
  226. }
  227. if (!audio.LockedFields.Contains(MetadataField.Name) && !string.IsNullOrEmpty(tags.Title))
  228. {
  229. audio.Name = tags.Title;
  230. }
  231. if (options.ReplaceAllMetadata)
  232. {
  233. audio.Album = tags.Album;
  234. audio.IndexNumber = Convert.ToInt32(tags.Track);
  235. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  236. }
  237. else
  238. {
  239. audio.Album ??= tags.Album;
  240. audio.IndexNumber ??= Convert.ToInt32(tags.Track);
  241. audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
  242. }
  243. if (tags.Year != 0)
  244. {
  245. var year = Convert.ToInt32(tags.Year);
  246. audio.ProductionYear = year;
  247. if (!audio.PremiereDate.HasValue)
  248. {
  249. audio.PremiereDate = new DateTime(year, 01, 01);
  250. }
  251. }
  252. if (!audio.LockedFields.Contains(MetadataField.Genres))
  253. {
  254. audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
  255. ? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
  256. : audio.Genres;
  257. }
  258. if (!double.IsNaN(tags.ReplayGainTrackGain))
  259. {
  260. audio.NormalizationGain = (float)tags.ReplayGainTrackGain;
  261. }
  262. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
  263. {
  264. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  265. }
  266. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
  267. {
  268. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  269. }
  270. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
  271. {
  272. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  273. }
  274. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
  275. {
  276. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  277. }
  278. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
  279. {
  280. // Fallback to ffprobe as TagLib incorrectly provides recording MBID in `tags.MusicBrainzTrackId`.
  281. // See https://github.com/mono/taglib-sharp/issues/304
  282. var trackMbId = mediaInfo.GetProviderId(MetadataProvider.MusicBrainzTrack);
  283. if (trackMbId is not null)
  284. {
  285. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, trackMbId);
  286. }
  287. }
  288. // Save extracted lyrics if they exist,
  289. // and if we are replacing all metadata or the audio doesn't yet have lyrics.
  290. if (!string.IsNullOrWhiteSpace(tags.Lyrics)
  291. && (options.ReplaceAllMetadata || audio.GetMediaStreams().All(s => s.Type != MediaStreamType.Lyric)))
  292. {
  293. await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
  294. }
  295. }
  296. }
  297. private void AddExternalLyrics(
  298. Audio audio,
  299. List<MediaStream> currentStreams,
  300. MetadataRefreshOptions options)
  301. {
  302. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  303. var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, false);
  304. audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray();
  305. currentStreams.AddRange(externalLyricFiles);
  306. }
  307. }
  308. }