AudioFileProber.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. if (!audio.IsLocked)
  208. {
  209. await FetchDataFromTags(audio, options).ConfigureAwait(false);
  210. }
  211. var mediaStreams = new List<MediaStream>(mediaInfo.MediaStreams);
  212. AddExternalLyrics(audio, mediaStreams, options);
  213. audio.HasLyrics = mediaStreams.Any(s => s.Type == MediaStreamType.Lyric);
  214. _itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
  215. }
  216. /// <summary>
  217. /// Fetches data from the tags.
  218. /// </summary>
  219. /// <param name="audio">The <see cref="Audio"/>.</param>
  220. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  221. private async Task FetchDataFromTags(Audio audio, MetadataRefreshOptions options)
  222. {
  223. using var file = TagLib.File.Create(audio.Path);
  224. var tagTypes = file.TagTypesOnDisk;
  225. Tag? tags = null;
  226. if (tagTypes.HasFlag(TagTypes.Id3v2))
  227. {
  228. tags = file.GetTag(TagTypes.Id3v2);
  229. }
  230. else if (tagTypes.HasFlag(TagTypes.Ape))
  231. {
  232. tags = file.GetTag(TagTypes.Ape);
  233. }
  234. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  235. {
  236. tags = file.GetTag(TagTypes.FlacMetadata);
  237. }
  238. else if (tagTypes.HasFlag(TagTypes.Apple))
  239. {
  240. tags = file.GetTag(TagTypes.Apple);
  241. }
  242. else if (tagTypes.HasFlag(TagTypes.Xiph))
  243. {
  244. tags = file.GetTag(TagTypes.Xiph);
  245. }
  246. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  247. {
  248. tags = file.GetTag(TagTypes.AudibleMetadata);
  249. }
  250. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  251. {
  252. tags = file.GetTag(TagTypes.Id3v1);
  253. }
  254. if (tags is not null)
  255. {
  256. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  257. {
  258. var people = new List<PersonInfo>();
  259. var albumArtists = tags.AlbumArtists;
  260. foreach (var albumArtist in albumArtists)
  261. {
  262. if (!string.IsNullOrEmpty(albumArtist))
  263. {
  264. PeopleHelper.AddPerson(people, new PersonInfo
  265. {
  266. Name = albumArtist,
  267. Type = PersonKind.AlbumArtist
  268. });
  269. }
  270. }
  271. var performers = tags.Performers;
  272. foreach (var performer in performers)
  273. {
  274. if (!string.IsNullOrEmpty(performer))
  275. {
  276. PeopleHelper.AddPerson(people, new PersonInfo
  277. {
  278. Name = performer,
  279. Type = PersonKind.Artist
  280. });
  281. }
  282. }
  283. foreach (var composer in tags.Composers)
  284. {
  285. if (!string.IsNullOrEmpty(composer))
  286. {
  287. PeopleHelper.AddPerson(people, new PersonInfo
  288. {
  289. Name = composer,
  290. Type = PersonKind.Composer
  291. });
  292. }
  293. }
  294. _libraryManager.UpdatePeople(audio, people);
  295. if (options.ReplaceAllMetadata && performers.Length != 0)
  296. {
  297. audio.Artists = performers;
  298. }
  299. else if (!options.ReplaceAllMetadata
  300. && (audio.Artists is null || audio.Artists.Count == 0))
  301. {
  302. audio.Artists = performers;
  303. }
  304. if (options.ReplaceAllMetadata && albumArtists.Length != 0)
  305. {
  306. audio.AlbumArtists = albumArtists;
  307. }
  308. else if (!options.ReplaceAllMetadata
  309. && (audio.AlbumArtists is null || audio.AlbumArtists.Count == 0))
  310. {
  311. audio.AlbumArtists = albumArtists;
  312. }
  313. }
  314. if (!audio.LockedFields.Contains(MetadataField.Name))
  315. {
  316. audio.Name = options.ReplaceAllMetadata || string.IsNullOrEmpty(audio.Name) ? tags.Title : audio.Name;
  317. }
  318. if (options.ReplaceAllMetadata)
  319. {
  320. audio.Album = tags.Album;
  321. audio.IndexNumber = Convert.ToInt32(tags.Track);
  322. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  323. }
  324. else
  325. {
  326. audio.Album ??= tags.Album;
  327. audio.IndexNumber ??= Convert.ToInt32(tags.Track);
  328. audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
  329. }
  330. if (tags.Year != 0)
  331. {
  332. var year = Convert.ToInt32(tags.Year);
  333. audio.ProductionYear = year;
  334. audio.PremiereDate = new DateTime(year, 01, 01);
  335. }
  336. if (!audio.LockedFields.Contains(MetadataField.Genres))
  337. {
  338. audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
  339. ? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
  340. : audio.Genres;
  341. }
  342. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzArtist, out _))
  343. {
  344. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  345. }
  346. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbumArtist, out _))
  347. {
  348. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  349. }
  350. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzAlbum, out _))
  351. {
  352. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  353. }
  354. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzReleaseGroup, out _))
  355. {
  356. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  357. }
  358. if (options.ReplaceAllMetadata || !audio.TryGetProviderId(MetadataProvider.MusicBrainzTrack, out _))
  359. {
  360. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, tags.MusicBrainzTrackId);
  361. }
  362. // Save extracted lyrics if they exist,
  363. // and if we are replacing all metadata or the audio doesn't yet have lyrics.
  364. if (!string.IsNullOrWhiteSpace(tags.Lyrics)
  365. && (options.ReplaceAllMetadata || audio.GetMediaStreams().All(s => s.Type != MediaStreamType.Lyric)))
  366. {
  367. await _lyricManager.SaveLyricAsync(audio, "lrc", tags.Lyrics).ConfigureAwait(false);
  368. }
  369. }
  370. }
  371. private void AddExternalLyrics(
  372. Audio audio,
  373. List<MediaStream> currentStreams,
  374. MetadataRefreshOptions options)
  375. {
  376. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  377. var externalLyricFiles = _lyricResolver.GetExternalStreams(audio, startIndex, options.DirectoryService, false);
  378. audio.LyricFiles = externalLyricFiles.Select(i => i.Path).Distinct().ToArray();
  379. currentStreams.AddRange(externalLyricFiles);
  380. }
  381. }
  382. }