AudioFileProber.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. [GeneratedRegex(@"REPLAYGAIN_TRACK_GAIN:\s+-?([0-9.]+)\s+dB")]
  69. private static partial Regex ReplayGainTagRegex();
  70. /// <summary>
  71. /// Probes the specified item for metadata.
  72. /// </summary>
  73. /// <param name="item">The item to probe.</param>
  74. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  75. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  76. /// <typeparam name="T">The type of item to resolve.</typeparam>
  77. /// <returns>A <see cref="Task"/> probing the item for metadata.</returns>
  78. public async Task<ItemUpdateType> Probe<T>(
  79. T item,
  80. MetadataRefreshOptions options,
  81. CancellationToken cancellationToken)
  82. where T : Audio
  83. {
  84. var path = item.Path;
  85. var protocol = item.PathProtocol ?? MediaProtocol.File;
  86. if (!item.IsShortcut || options.EnableRemoteContentProbe)
  87. {
  88. if (item.IsShortcut)
  89. {
  90. path = item.ShortcutPath;
  91. protocol = _mediaSourceManager.GetPathProtocol(path);
  92. }
  93. var result = await _mediaEncoder.GetMediaInfo(
  94. new MediaInfoRequest
  95. {
  96. MediaType = DlnaProfileType.Audio,
  97. MediaSource = new MediaSourceInfo
  98. {
  99. Path = path,
  100. Protocol = protocol
  101. }
  102. },
  103. cancellationToken).ConfigureAwait(false);
  104. cancellationToken.ThrowIfCancellationRequested();
  105. await FetchAsync(item, result, options, cancellationToken).ConfigureAwait(false);
  106. }
  107. var libraryOptions = _libraryManager.GetLibraryOptions(item);
  108. bool foundLUFSValue = false;
  109. if (libraryOptions.UseReplayGainTags)
  110. {
  111. using (var process = new Process()
  112. {
  113. StartInfo = new ProcessStartInfo
  114. {
  115. FileName = _mediaEncoder.ProbePath,
  116. Arguments = $"-hide_banner -i \"{path}\"",
  117. RedirectStandardOutput = false,
  118. RedirectStandardError = true
  119. },
  120. })
  121. {
  122. try
  123. {
  124. process.Start();
  125. }
  126. catch (Exception ex)
  127. {
  128. _logger.LogError(ex, "Error starting ffmpeg");
  129. throw;
  130. }
  131. using var reader = process.StandardError;
  132. var output = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  133. cancellationToken.ThrowIfCancellationRequested();
  134. Match split = ReplayGainTagRegex().Match(output);
  135. if (split.Success)
  136. {
  137. item.LUFS = DefaultLUFSValue - float.Parse(split.Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  138. foundLUFSValue = true;
  139. }
  140. else
  141. {
  142. item.LUFS = DefaultLUFSValue;
  143. }
  144. }
  145. }
  146. if (libraryOptions.EnableLUFSScan && !foundLUFSValue)
  147. {
  148. using (var process = new Process()
  149. {
  150. StartInfo = new ProcessStartInfo
  151. {
  152. FileName = _mediaEncoder.EncoderPath,
  153. Arguments = $"-hide_banner -i \"{path}\" -af ebur128=framelog=verbose -f null -",
  154. RedirectStandardOutput = false,
  155. RedirectStandardError = true
  156. },
  157. })
  158. {
  159. try
  160. {
  161. process.Start();
  162. }
  163. catch (Exception ex)
  164. {
  165. _logger.LogError(ex, "Error starting ffmpeg");
  166. throw;
  167. }
  168. using var reader = process.StandardError;
  169. var output = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  170. cancellationToken.ThrowIfCancellationRequested();
  171. MatchCollection split = LUFSRegex().Matches(output);
  172. if (split.Count != 0)
  173. {
  174. item.LUFS = float.Parse(split[0].Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  175. }
  176. else
  177. {
  178. item.LUFS = DefaultLUFSValue;
  179. }
  180. }
  181. }
  182. if (!libraryOptions.EnableLUFSScan && !libraryOptions.UseReplayGainTags)
  183. {
  184. item.LUFS = DefaultLUFSValue;
  185. }
  186. _logger.LogDebug("LUFS for {ItemName} is {LUFS}.", item.Name, item.LUFS);
  187. return ItemUpdateType.MetadataImport;
  188. }
  189. /// <summary>
  190. /// Fetches the specified audio.
  191. /// </summary>
  192. /// <param name="audio">The <see cref="Audio"/>.</param>
  193. /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
  194. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  195. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  196. /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
  197. private async Task FetchAsync(
  198. Audio audio,
  199. Model.MediaInfo.MediaInfo mediaInfo,
  200. MetadataRefreshOptions options,
  201. CancellationToken cancellationToken)
  202. {
  203. audio.Container = mediaInfo.Container;
  204. audio.TotalBitrate = mediaInfo.Bitrate;
  205. audio.RunTimeTicks = mediaInfo.RunTimeTicks;
  206. audio.Size = mediaInfo.Size;
  207. audio.PremiereDate = mediaInfo.PremiereDate;
  208. if (!audio.IsLocked)
  209. {
  210. await FetchDataFromTags(audio, mediaInfo, options).ConfigureAwait(false);
  211. }
  212. var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
  213. AddExternalLyrics(audio, mediaStreams, options);
  214. audio.HasLyrics = mediaStreams.Any(s => s.Type == MediaStreamType.Lyric);
  215. _itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
  216. }
  217. /// <summary>
  218. /// Fetches data from the tags.
  219. /// </summary>
  220. /// <param name="audio">The <see cref="Audio"/>.</param>
  221. /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
  222. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  223. private async Task FetchDataFromTags(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, MetadataRefreshOptions options)
  224. {
  225. using var file = TagLib.File.Create(audio.Path);
  226. var tagTypes = file.TagTypesOnDisk;
  227. Tag? tags = null;
  228. if (tagTypes.HasFlag(TagTypes.Id3v2))
  229. {
  230. tags = file.GetTag(TagTypes.Id3v2);
  231. }
  232. else if (tagTypes.HasFlag(TagTypes.Ape))
  233. {
  234. tags = file.GetTag(TagTypes.Ape);
  235. }
  236. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  237. {
  238. tags = file.GetTag(TagTypes.FlacMetadata);
  239. }
  240. else if (tagTypes.HasFlag(TagTypes.Apple))
  241. {
  242. tags = file.GetTag(TagTypes.Apple);
  243. }
  244. else if (tagTypes.HasFlag(TagTypes.Xiph))
  245. {
  246. tags = file.GetTag(TagTypes.Xiph);
  247. }
  248. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  249. {
  250. tags = file.GetTag(TagTypes.AudibleMetadata);
  251. }
  252. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  253. {
  254. tags = file.GetTag(TagTypes.Id3v1);
  255. }
  256. if (tags is not null)
  257. {
  258. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  259. {
  260. var people = new List<PersonInfo>();
  261. var albumArtists = tags.AlbumArtists;
  262. foreach (var albumArtist in albumArtists)
  263. {
  264. if (!string.IsNullOrEmpty(albumArtist))
  265. {
  266. PeopleHelper.AddPerson(people, new PersonInfo
  267. {
  268. Name = albumArtist,
  269. Type = PersonKind.AlbumArtist
  270. });
  271. }
  272. }
  273. var performers = tags.Performers;
  274. foreach (var performer in performers)
  275. {
  276. if (!string.IsNullOrEmpty(performer))
  277. {
  278. PeopleHelper.AddPerson(people, new PersonInfo
  279. {
  280. Name = performer,
  281. Type = PersonKind.Artist
  282. });
  283. }
  284. }
  285. foreach (var composer in tags.Composers)
  286. {
  287. if (!string.IsNullOrEmpty(composer))
  288. {
  289. PeopleHelper.AddPerson(people, new PersonInfo
  290. {
  291. Name = composer,
  292. Type = PersonKind.Composer
  293. });
  294. }
  295. }
  296. _libraryManager.UpdatePeople(audio, people);
  297. if (options.ReplaceAllMetadata && performers.Length != 0)
  298. {
  299. audio.Artists = performers;
  300. }
  301. else if (!options.ReplaceAllMetadata
  302. && (audio.Artists is null || audio.Artists.Count == 0))
  303. {
  304. audio.Artists = performers;
  305. }
  306. if (albumArtists.Length == 0)
  307. {
  308. // Album artists not provided, fall back to performers (artists).
  309. albumArtists = performers;
  310. }
  311. if (options.ReplaceAllMetadata && albumArtists.Length != 0)
  312. {
  313. audio.AlbumArtists = albumArtists;
  314. }
  315. else if (!options.ReplaceAllMetadata
  316. && (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0))
  317. {
  318. audio.AlbumArtists = albumArtists;
  319. }
  320. }
  321. if (!audio.LockedFields.Contains(MetadataField.Name) && !string.IsNullOrEmpty(tags.Title))
  322. {
  323. audio.Name = tags.Title;
  324. }
  325. if (options.ReplaceAllMetadata)
  326. {
  327. audio.Album = tags.Album;
  328. audio.IndexNumber = Convert.ToInt32(tags.Track);
  329. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  330. }
  331. else
  332. {
  333. audio.Album ??= tags.Album;
  334. audio.IndexNumber ??= Convert.ToInt32(tags.Track);
  335. audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
  336. }
  337. if (tags.Year != 0)
  338. {
  339. var year = Convert.ToInt32(tags.Year);
  340. audio.ProductionYear = year;
  341. if (!audio.PremiereDate.HasValue)
  342. {
  343. audio.PremiereDate = new DateTime(year, 01, 01);
  344. }
  345. }
  346. if (!audio.LockedFields.Contains(MetadataField.Genres))
  347. {
  348. audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
  349. ? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
  350. : audio.Genres;
  351. }
  352. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
  353. {
  354. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  355. }
  356. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
  357. {
  358. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  359. }
  360. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
  361. {
  362. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  363. }
  364. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
  365. {
  366. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  367. }
  368. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
  369. {
  370. // Fallback to ffprobe as TagLib incorrectly provides recording MBID in `tags.MusicBrainzTrackId`.
  371. // See https://github.com/mono/taglib-sharp/issues/304
  372. var trackMbId = mediaInfo.GetProviderId(MetadataProvider.MusicBrainzTrack);
  373. if (trackMbId is not null)
  374. {
  375. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, trackMbId);
  376. }
  377. }
  378. // Save extracted lyrics if they exist,
  379. // and if we are replacing all metadata or the audio doesn't yet have lyrics.
  380. if (!string.IsNullOrWhiteSpace(tags.Lyrics)
  381. && (options.ReplaceAllMetadata || audio.GetMediaStreams().All(s => s.Type != MediaStreamType.Lyric)))
  382. {
  383. await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
  384. }
  385. }
  386. }
  387. private void AddExternalLyrics(
  388. Audio audio,
  389. List<MediaStream> currentStreams,
  390. MetadataRefreshOptions options)
  391. {
  392. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  393. var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, false);
  394. audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray();
  395. currentStreams.AddRange(externalLyricFiles);
  396. }
  397. }
  398. }