AudioFileProber.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. output = await process.StandardError.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  121. cancellationToken.ThrowIfCancellationRequested();
  122. MatchCollection split = LUFSRegex().Matches(output);
  123. if (split.Count != 0)
  124. {
  125. item.LUFS = float.Parse(split[0].Groups[1].ValueSpan, CultureInfo.InvariantCulture.NumberFormat);
  126. }
  127. else
  128. {
  129. item.LUFS = DefaultLUFSValue;
  130. }
  131. }
  132. }
  133. else
  134. {
  135. item.LUFS = DefaultLUFSValue;
  136. }
  137. _logger.LogDebug("LUFS for {ItemName} is {LUFS}.", item.Name, item.LUFS);
  138. return ItemUpdateType.MetadataImport;
  139. }
  140. /// <summary>
  141. /// Fetches the specified audio.
  142. /// </summary>
  143. /// <param name="audio">The <see cref="Audio"/>.</param>
  144. /// <param name="mediaInfo">The <see cref="Model.MediaInfo.MediaInfo"/>.</param>
  145. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  146. protected void Fetch(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, CancellationToken cancellationToken)
  147. {
  148. audio.Container = mediaInfo.Container;
  149. audio.TotalBitrate = mediaInfo.Bitrate;
  150. audio.RunTimeTicks = mediaInfo.RunTimeTicks;
  151. audio.Size = mediaInfo.Size;
  152. if (!audio.IsLocked)
  153. {
  154. FetchDataFromTags(audio);
  155. }
  156. _itemRepo.SaveMediaStreams(audio.Id, mediaInfo.MediaStreams, cancellationToken);
  157. }
  158. /// <summary>
  159. /// Fetches data from the tags.
  160. /// </summary>
  161. /// <param name="audio">The <see cref="Audio"/>.</param>
  162. private void FetchDataFromTags(Audio audio)
  163. {
  164. var file = TagLib.File.Create(audio.Path);
  165. var tagTypes = file.TagTypesOnDisk;
  166. Tag? tags = null;
  167. if (tagTypes.HasFlag(TagTypes.Id3v2))
  168. {
  169. tags = file.GetTag(TagTypes.Id3v2);
  170. }
  171. else if (tagTypes.HasFlag(TagTypes.Ape))
  172. {
  173. tags = file.GetTag(TagTypes.Ape);
  174. }
  175. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  176. {
  177. tags = file.GetTag(TagTypes.FlacMetadata);
  178. }
  179. else if (tagTypes.HasFlag(TagTypes.Apple))
  180. {
  181. tags = file.GetTag(TagTypes.Apple);
  182. }
  183. else if (tagTypes.HasFlag(TagTypes.Xiph))
  184. {
  185. tags = file.GetTag(TagTypes.Xiph);
  186. }
  187. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  188. {
  189. tags = file.GetTag(TagTypes.AudibleMetadata);
  190. }
  191. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  192. {
  193. tags = file.GetTag(TagTypes.Id3v1);
  194. }
  195. if (tags is not null)
  196. {
  197. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  198. {
  199. var people = new List<PersonInfo>();
  200. var albumArtists = tags.AlbumArtists;
  201. foreach (var albumArtist in albumArtists)
  202. {
  203. PeopleHelper.AddPerson(people, new PersonInfo
  204. {
  205. Name = albumArtist,
  206. Type = PersonKind.AlbumArtist
  207. });
  208. }
  209. var performers = tags.Performers;
  210. foreach (var performer in performers)
  211. {
  212. PeopleHelper.AddPerson(people, new PersonInfo
  213. {
  214. Name = performer,
  215. Type = PersonKind.Artist
  216. });
  217. }
  218. foreach (var composer in tags.Composers)
  219. {
  220. PeopleHelper.AddPerson(people, new PersonInfo
  221. {
  222. Name = composer,
  223. Type = PersonKind.Composer
  224. });
  225. }
  226. _libraryManager.UpdatePeople(audio, people);
  227. audio.Artists = performers;
  228. audio.AlbumArtists = albumArtists;
  229. }
  230. audio.Name = tags.Title;
  231. audio.Album = tags.Album;
  232. audio.IndexNumber = Convert.ToInt32(tags.Track);
  233. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  234. if (tags.Year != 0)
  235. {
  236. var year = Convert.ToInt32(tags.Year);
  237. audio.ProductionYear = year;
  238. audio.PremiereDate = new DateTime(year, 01, 01);
  239. }
  240. if (!audio.LockedFields.Contains(MetadataField.Genres))
  241. {
  242. audio.Genres = tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
  243. }
  244. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  245. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  246. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  247. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  248. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, tags.MusicBrainzTrackId);
  249. }
  250. }
  251. }
  252. }