FFProbeAudioInfo.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. using System.IO;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.MediaInfo;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Entities;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Providers.MediaInfo
  16. {
  17. class FFProbeAudioInfo
  18. {
  19. private readonly IMediaEncoder _mediaEncoder;
  20. private readonly IItemRepository _itemRepo;
  21. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  22. public FFProbeAudioInfo(IMediaEncoder mediaEncoder, IItemRepository itemRepo)
  23. {
  24. _mediaEncoder = mediaEncoder;
  25. _itemRepo = itemRepo;
  26. }
  27. public async Task<ItemUpdateType> Probe<T>(T item, CancellationToken cancellationToken)
  28. where T : Audio
  29. {
  30. var result = await GetMediaInfo(item, cancellationToken).ConfigureAwait(false);
  31. cancellationToken.ThrowIfCancellationRequested();
  32. FFProbeHelpers.NormalizeFFProbeResult(result);
  33. cancellationToken.ThrowIfCancellationRequested();
  34. await Fetch(item, cancellationToken, result).ConfigureAwait(false);
  35. return ItemUpdateType.MetadataImport;
  36. }
  37. private async Task<InternalMediaInfoResult> GetMediaInfo(BaseItem item, CancellationToken cancellationToken)
  38. {
  39. cancellationToken.ThrowIfCancellationRequested();
  40. const InputType type = InputType.File;
  41. var inputPath = new[] { item.Path };
  42. return await _mediaEncoder.GetMediaInfo(inputPath, type, false, cancellationToken).ConfigureAwait(false);
  43. }
  44. /// <summary>
  45. /// Fetches the specified audio.
  46. /// </summary>
  47. /// <param name="audio">The audio.</param>
  48. /// <param name="cancellationToken">The cancellation token.</param>
  49. /// <param name="data">The data.</param>
  50. /// <returns>Task.</returns>
  51. protected Task Fetch(Audio audio, CancellationToken cancellationToken, InternalMediaInfoResult data)
  52. {
  53. var mediaStreams = MediaEncoderHelpers.GetMediaInfo(data).MediaStreams;
  54. audio.HasEmbeddedImage = mediaStreams.Any(i => i.Type == MediaStreamType.Video);
  55. if (data.streams != null)
  56. {
  57. // Get the first audio stream
  58. var stream = data.streams.FirstOrDefault(s => string.Equals(s.codec_type, "audio", StringComparison.OrdinalIgnoreCase));
  59. if (stream != null)
  60. {
  61. // Get duration from stream properties
  62. var duration = stream.duration;
  63. // If it's not there go into format properties
  64. if (string.IsNullOrEmpty(duration))
  65. {
  66. duration = data.format.duration;
  67. }
  68. // If we got something, parse it
  69. if (!string.IsNullOrEmpty(duration))
  70. {
  71. audio.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  72. }
  73. }
  74. }
  75. if (data.format.tags != null)
  76. {
  77. FetchDataFromTags(audio, data.format.tags);
  78. }
  79. return _itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
  80. }
  81. /// <summary>
  82. /// Fetches data from the tags dictionary
  83. /// </summary>
  84. /// <param name="audio">The audio.</param>
  85. /// <param name="tags">The tags.</param>
  86. private void FetchDataFromTags(Audio audio, Dictionary<string, string> tags)
  87. {
  88. var title = FFProbeHelpers.GetDictionaryValue(tags, "title");
  89. // Only set Name if title was found in the dictionary
  90. if (!string.IsNullOrEmpty(title))
  91. {
  92. audio.Name = title;
  93. }
  94. if (!audio.LockedFields.Contains(MetadataFields.Cast))
  95. {
  96. audio.People.Clear();
  97. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  98. if (!string.IsNullOrWhiteSpace(composer))
  99. {
  100. foreach (var person in Split(composer))
  101. {
  102. audio.AddPerson(new PersonInfo { Name = person, Type = PersonType.Composer });
  103. }
  104. }
  105. }
  106. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  107. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  108. if (string.IsNullOrWhiteSpace(artist))
  109. {
  110. audio.Artists.Clear();
  111. }
  112. else
  113. {
  114. audio.Artists = SplitArtists(artist)
  115. .Distinct(StringComparer.OrdinalIgnoreCase)
  116. .ToList();
  117. }
  118. // Several different forms of albumartist
  119. audio.AlbumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist") ?? FFProbeHelpers.GetDictionaryValue(tags, "album artist") ?? FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  120. // Track number
  121. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  122. // Disc number
  123. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  124. audio.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
  125. // Several different forms of retaildate
  126. audio.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date");
  127. // If we don't have a ProductionYear try and get it from PremiereDate
  128. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  129. {
  130. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  131. }
  132. if (!audio.LockedFields.Contains(MetadataFields.Genres))
  133. {
  134. FetchGenres(audio, tags);
  135. }
  136. if (!audio.LockedFields.Contains(MetadataFields.Studios))
  137. {
  138. audio.Studios.Clear();
  139. // There's several values in tags may or may not be present
  140. FetchStudios(audio, tags, "organization");
  141. FetchStudios(audio, tags, "ensemble");
  142. FetchStudios(audio, tags, "publisher");
  143. }
  144. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  145. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  146. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  147. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  148. }
  149. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  150. /// <summary>
  151. /// Splits the specified val.
  152. /// </summary>
  153. /// <param name="val">The val.</param>
  154. /// <returns>System.String[][].</returns>
  155. private IEnumerable<string> Split(string val)
  156. {
  157. // Only use the comma as a delimeter if there are no slashes or pipes.
  158. // We want to be careful not to split names that have commas in them
  159. var delimeter = _nameDelimiters.Any(i => val.IndexOf(i) != -1) ? _nameDelimiters : new[] { ',' };
  160. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  161. .Where(i => !string.IsNullOrWhiteSpace(i))
  162. .Select(i => i.Trim());
  163. }
  164. private const string ArtistReplaceValue = " | ";
  165. private IEnumerable<string> SplitArtists(string val)
  166. {
  167. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  168. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  169. var artistsFound = new List<string>();
  170. foreach (var whitelistArtist in GetSplitWhitelist())
  171. {
  172. if (val.IndexOf(whitelistArtist, StringComparison.OrdinalIgnoreCase) != -1)
  173. {
  174. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  175. // TODO: Preserve casing from original tag
  176. artistsFound.Add(whitelistArtist);
  177. }
  178. }
  179. // Only use the comma as a delimeter if there are no slashes or pipes.
  180. // We want to be careful not to split names that have commas in them
  181. var delimeter = _nameDelimiters;
  182. var artists = val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  183. .Where(i => !string.IsNullOrWhiteSpace(i))
  184. .Select(i => i.Trim());
  185. artistsFound.AddRange(artists);
  186. return artistsFound;
  187. }
  188. private List<string> _splitWhiteList = null;
  189. private IEnumerable<string> GetSplitWhitelist()
  190. {
  191. if (_splitWhiteList == null)
  192. {
  193. var file = GetType().Namespace + ".whitelist.txt";
  194. using (var stream = GetType().Assembly.GetManifestResourceStream(file))
  195. {
  196. using (var reader = new StreamReader(stream))
  197. {
  198. var list = new List<string>();
  199. while (!reader.EndOfStream)
  200. {
  201. var val = reader.ReadLine();
  202. if (!string.IsNullOrWhiteSpace(val))
  203. {
  204. list.Add(val);
  205. }
  206. }
  207. _splitWhiteList = list;
  208. }
  209. }
  210. }
  211. return _splitWhiteList;
  212. }
  213. /// <summary>
  214. /// Gets the studios from the tags collection
  215. /// </summary>
  216. /// <param name="audio">The audio.</param>
  217. /// <param name="tags">The tags.</param>
  218. /// <param name="tagName">Name of the tag.</param>
  219. private void FetchStudios(Audio audio, Dictionary<string, string> tags, string tagName)
  220. {
  221. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  222. if (!string.IsNullOrEmpty(val))
  223. {
  224. // Sometimes the artist name is listed here, account for that
  225. var studios = Split(val).Where(i => !audio.HasArtist(i));
  226. foreach (var studio in studios)
  227. {
  228. audio.AddStudio(studio);
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// Gets the genres from the tags collection
  234. /// </summary>
  235. /// <param name="audio">The audio.</param>
  236. /// <param name="tags">The tags.</param>
  237. private void FetchGenres(Audio audio, Dictionary<string, string> tags)
  238. {
  239. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  240. if (!string.IsNullOrEmpty(val))
  241. {
  242. audio.Genres.Clear();
  243. foreach (var genre in Split(val))
  244. {
  245. audio.AddGenre(genre);
  246. }
  247. }
  248. }
  249. /// <summary>
  250. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  251. /// </summary>
  252. /// <param name="tags">The tags.</param>
  253. /// <param name="tagName">Name of the tag.</param>
  254. /// <returns>System.Nullable{System.Int32}.</returns>
  255. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  256. {
  257. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  258. if (!string.IsNullOrEmpty(disc))
  259. {
  260. disc = disc.Split('/')[0];
  261. int num;
  262. if (int.TryParse(disc, out num))
  263. {
  264. return num;
  265. }
  266. }
  267. return null;
  268. }
  269. }
  270. }