AudioFileProber.cs 14 KB

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