AudioFileProber.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. /// <summary>
  37. /// Initializes a new instance of the <see cref="AudioFileProber"/> class.
  38. /// </summary>
  39. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  40. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  41. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  42. /// <param name="itemRepo">Instance of the <see cref="IItemRepository"/> interface.</param>
  43. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  44. public AudioFileProber(
  45. ILogger<AudioFileProber> logger,
  46. IMediaSourceManager mediaSourceManager,
  47. IMediaEncoder mediaEncoder,
  48. IItemRepository itemRepo,
  49. ILibraryManager libraryManager)
  50. {
  51. _logger = logger;
  52. _mediaEncoder = mediaEncoder;
  53. _itemRepo = itemRepo;
  54. _libraryManager = libraryManager;
  55. _mediaSourceManager = mediaSourceManager;
  56. }
  57. [GeneratedRegex("I:\\s+(.*?)\\s+LUFS")]
  58. private static partial Regex LUFSRegex();
  59. /// <summary>
  60. /// Probes the specified item for metadata.
  61. /// </summary>
  62. /// <param name="item">The item to probe.</param>
  63. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  64. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  65. /// <typeparam name="T">The type of item to resolve.</typeparam>
  66. /// <returns>A <see cref="Task"/> probing the item for metadata.</returns>
  67. public async Task<ItemUpdateType> Probe<T>(
  68. T item,
  69. MetadataRefreshOptions options,
  70. CancellationToken cancellationToken)
  71. where T : Audio
  72. {
  73. var path = item.Path;
  74. var protocol = item.PathProtocol ?? MediaProtocol.File;
  75. if (!item.IsShortcut || options.EnableRemoteContentProbe)
  76. {
  77. if (item.IsShortcut)
  78. {
  79. path = item.ShortcutPath;
  80. protocol = _mediaSourceManager.GetPathProtocol(path);
  81. }
  82. var result = await _mediaEncoder.GetMediaInfo(
  83. new MediaInfoRequest
  84. {
  85. MediaType = DlnaProfileType.Audio,
  86. MediaSource = new MediaSourceInfo
  87. {
  88. Path = path,
  89. Protocol = protocol
  90. }
  91. },
  92. cancellationToken).ConfigureAwait(false);
  93. cancellationToken.ThrowIfCancellationRequested();
  94. Fetch(item, result, cancellationToken);
  95. }
  96. var libraryOptions = _libraryManager.GetLibraryOptions(item);
  97. if (libraryOptions.EnableLUFSScan)
  98. {
  99. string output;
  100. using (var process = new Process()
  101. {
  102. StartInfo = new ProcessStartInfo
  103. {
  104. FileName = _mediaEncoder.EncoderPath,
  105. Arguments = $"-hide_banner -i \"{path}\" -af ebur128=framelog=verbose -f null -",
  106. RedirectStandardOutput = false,
  107. RedirectStandardError = true
  108. },
  109. })
  110. {
  111. try
  112. {
  113. process.Start();
  114. }
  115. catch (Exception ex)
  116. {
  117. _logger.LogError(ex, "Error starting ffmpeg");
  118. throw;
  119. }
  120. using var reader = process.StandardError;
  121. output = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  122. cancellationToken.ThrowIfCancellationRequested();
  123. MatchCollection split = LUFSRegex().Matches(output);
  124. if (split.Count != 0)
  125. {
  126. item.LUFS = float.Parse(split[0].Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  127. }
  128. else
  129. {
  130. item.LUFS = DefaultLUFSValue;
  131. }
  132. }
  133. }
  134. else
  135. {
  136. item.LUFS = DefaultLUFSValue;
  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="cancellationToken">The <see cref="CancellationToken"/>.</param>
  147. protected void Fetch(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, CancellationToken cancellationToken)
  148. {
  149. audio.Container = mediaInfo.Container;
  150. audio.TotalBitrate = mediaInfo.Bitrate;
  151. audio.RunTimeTicks = mediaInfo.RunTimeTicks;
  152. audio.Size = mediaInfo.Size;
  153. if (!audio.IsLocked)
  154. {
  155. FetchDataFromTags(audio);
  156. }
  157. _itemRepo.SaveMediaStreams(audio.Id, mediaInfo.MediaStreams, cancellationToken);
  158. }
  159. /// <summary>
  160. /// Fetches data from the tags.
  161. /// </summary>
  162. /// <param name="audio">The <see cref="Audio"/>.</param>
  163. private void FetchDataFromTags(Audio audio)
  164. {
  165. var file = TagLib.File.Create(audio.Path);
  166. var tagTypes = file.TagTypesOnDisk;
  167. Tag? tags = null;
  168. if (tagTypes.HasFlag(TagTypes.Id3v2))
  169. {
  170. tags = file.GetTag(TagTypes.Id3v2);
  171. }
  172. else if (tagTypes.HasFlag(TagTypes.Ape))
  173. {
  174. tags = file.GetTag(TagTypes.Ape);
  175. }
  176. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  177. {
  178. tags = file.GetTag(TagTypes.FlacMetadata);
  179. }
  180. else if (tagTypes.HasFlag(TagTypes.Apple))
  181. {
  182. tags = file.GetTag(TagTypes.Apple);
  183. }
  184. else if (tagTypes.HasFlag(TagTypes.Xiph))
  185. {
  186. tags = file.GetTag(TagTypes.Xiph);
  187. }
  188. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  189. {
  190. tags = file.GetTag(TagTypes.AudibleMetadata);
  191. }
  192. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  193. {
  194. tags = file.GetTag(TagTypes.Id3v1);
  195. }
  196. if (tags is not null)
  197. {
  198. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  199. {
  200. var people = new List<PersonInfo>();
  201. var albumArtists = tags.AlbumArtists;
  202. foreach (var albumArtist in albumArtists)
  203. {
  204. if (!string.IsNullOrEmpty(albumArtist))
  205. {
  206. PeopleHelper.AddPerson(people, new PersonInfo
  207. {
  208. Name = albumArtist,
  209. Type = PersonKind.AlbumArtist
  210. });
  211. }
  212. }
  213. var performers = tags.Performers;
  214. foreach (var performer in performers)
  215. {
  216. if (!string.IsNullOrEmpty(performer))
  217. {
  218. PeopleHelper.AddPerson(people, new PersonInfo
  219. {
  220. Name = performer,
  221. Type = PersonKind.Artist
  222. });
  223. }
  224. }
  225. foreach (var composer in tags.Composers)
  226. {
  227. if (!string.IsNullOrEmpty(composer))
  228. {
  229. PeopleHelper.AddPerson(people, new PersonInfo
  230. {
  231. Name = composer,
  232. Type = PersonKind.Composer
  233. });
  234. }
  235. }
  236. _libraryManager.UpdatePeople(audio, people);
  237. audio.Artists = performers;
  238. audio.AlbumArtists = albumArtists;
  239. }
  240. audio.Name = tags.Title;
  241. audio.Album = tags.Album;
  242. audio.IndexNumber = Convert.ToInt32(tags.Track);
  243. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  244. if (tags.Year != 0)
  245. {
  246. var year = Convert.ToInt32(tags.Year);
  247. audio.ProductionYear = year;
  248. audio.PremiereDate = new DateTime(year, 01, 01);
  249. }
  250. if (!audio.LockedFields.Contains(MetadataField.Genres))
  251. {
  252. audio.Genres = tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
  253. }
  254. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  255. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  256. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  257. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  258. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, tags.MusicBrainzTrackId);
  259. }
  260. }
  261. }
  262. }