AudioFileProber.cs 16 KB

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