AudioFileProber.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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, options, cancellationToken);
  95. }
  96. var libraryOptions = _libraryManager.GetLibraryOptions(item);
  97. if (libraryOptions.EnableLUFSScan)
  98. {
  99. using (var process = new Process()
  100. {
  101. StartInfo = new ProcessStartInfo
  102. {
  103. FileName = _mediaEncoder.EncoderPath,
  104. Arguments = $"-hide_banner -i \"{path}\" -af ebur128=framelog=verbose -f null -",
  105. RedirectStandardOutput = false,
  106. RedirectStandardError = true
  107. },
  108. })
  109. {
  110. try
  111. {
  112. process.Start();
  113. }
  114. catch (Exception ex)
  115. {
  116. _logger.LogError(ex, "Error starting ffmpeg");
  117. throw;
  118. }
  119. using var reader = process.StandardError;
  120. var output = await reader.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="options">The <see cref="MetadataRefreshOptions"/>.</param>
  146. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  147. protected void Fetch(Audio audio, Model.MediaInfo.MediaInfo mediaInfo, MetadataRefreshOptions options, 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, options);
  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. /// <param name="options">The <see cref="MetadataRefreshOptions"/>.</param>
  164. private void FetchDataFromTags(Audio audio, MetadataRefreshOptions options)
  165. {
  166. var file = TagLib.File.Create(audio.Path);
  167. var tagTypes = file.TagTypesOnDisk;
  168. Tag? tags = null;
  169. if (tagTypes.HasFlag(TagTypes.Id3v2))
  170. {
  171. tags = file.GetTag(TagTypes.Id3v2);
  172. }
  173. else if (tagTypes.HasFlag(TagTypes.Ape))
  174. {
  175. tags = file.GetTag(TagTypes.Ape);
  176. }
  177. else if (tagTypes.HasFlag(TagTypes.FlacMetadata))
  178. {
  179. tags = file.GetTag(TagTypes.FlacMetadata);
  180. }
  181. else if (tagTypes.HasFlag(TagTypes.Apple))
  182. {
  183. tags = file.GetTag(TagTypes.Apple);
  184. }
  185. else if (tagTypes.HasFlag(TagTypes.Xiph))
  186. {
  187. tags = file.GetTag(TagTypes.Xiph);
  188. }
  189. else if (tagTypes.HasFlag(TagTypes.AudibleMetadata))
  190. {
  191. tags = file.GetTag(TagTypes.AudibleMetadata);
  192. }
  193. else if (tagTypes.HasFlag(TagTypes.Id3v1))
  194. {
  195. tags = file.GetTag(TagTypes.Id3v1);
  196. }
  197. if (tags is not null)
  198. {
  199. if (audio.SupportsPeople && !audio.LockedFields.Contains(MetadataField.Cast))
  200. {
  201. var people = new List<PersonInfo>();
  202. var albumArtists = tags.AlbumArtists;
  203. foreach (var albumArtist in albumArtists)
  204. {
  205. if (!string.IsNullOrEmpty(albumArtist))
  206. {
  207. PeopleHelper.AddPerson(people, new PersonInfo
  208. {
  209. Name = albumArtist,
  210. Type = PersonKind.AlbumArtist
  211. });
  212. }
  213. }
  214. var performers = tags.Performers;
  215. foreach (var performer in performers)
  216. {
  217. if (!string.IsNullOrEmpty(performer))
  218. {
  219. PeopleHelper.AddPerson(people, new PersonInfo
  220. {
  221. Name = performer,
  222. Type = PersonKind.Artist
  223. });
  224. }
  225. }
  226. foreach (var composer in tags.Composers)
  227. {
  228. if (!string.IsNullOrEmpty(composer))
  229. {
  230. PeopleHelper.AddPerson(people, new PersonInfo
  231. {
  232. Name = composer,
  233. Type = PersonKind.Composer
  234. });
  235. }
  236. }
  237. _libraryManager.UpdatePeople(audio, people);
  238. audio.Artists ??= performers;
  239. audio.AlbumArtists ??= albumArtists;
  240. }
  241. if (!audio.LockedFields.Contains(MetadataField.Name))
  242. {
  243. audio.Name = options.ReplaceAllMetadata || string.IsNullOrEmpty(audio.Name) ? tags.Title : audio.Name;
  244. }
  245. if (options.ReplaceAllMetadata)
  246. {
  247. audio.Album = tags.Album;
  248. audio.IndexNumber = Convert.ToInt32(tags.Track);
  249. audio.ParentIndexNumber = Convert.ToInt32(tags.Disc);
  250. }
  251. else
  252. {
  253. audio.Album ??= tags.Album;
  254. audio.IndexNumber ??= Convert.ToInt32(tags.Track);
  255. audio.ParentIndexNumber ??= Convert.ToInt32(tags.Disc);
  256. }
  257. if (tags.Year != 0)
  258. {
  259. var year = Convert.ToInt32(tags.Year);
  260. audio.ProductionYear = year;
  261. audio.PremiereDate = new DateTime(year, 01, 01);
  262. }
  263. if (!audio.LockedFields.Contains(MetadataField.Genres))
  264. {
  265. audio.Genres = options.ReplaceAllMetadata || audio.Genres == null || audio.Genres.Length == 0
  266. ? tags.Genres.Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
  267. : audio.Genres;
  268. }
  269. if (options.ReplaceAllMetadata || !audio.TryGetProviderId("MusicBrainzArtist", out _))
  270. {
  271. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, tags.MusicBrainzArtistId);
  272. }
  273. if (options.ReplaceAllMetadata || !audio.TryGetProviderId("MusicBrainzAlbumArtist", out _))
  274. {
  275. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, tags.MusicBrainzReleaseArtistId);
  276. }
  277. if (options.ReplaceAllMetadata || !audio.TryGetProviderId("MusicBrainzAlbum", out _))
  278. {
  279. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, tags.MusicBrainzReleaseId);
  280. }
  281. if (options.ReplaceAllMetadata || !audio.TryGetProviderId("MusicBrainzReleaseGroup", out _))
  282. {
  283. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, tags.MusicBrainzReleaseGroupId);
  284. }
  285. if (options.ReplaceAllMetadata || !audio.TryGetProviderId("MusicBrainzTrack", out _))
  286. {
  287. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, tags.MusicBrainzTrackId);
  288. }
  289. }
  290. }
  291. }
  292. }