FFProbeAudioInfoProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Providers.MediaInfo
  17. {
  18. /// <summary>
  19. /// Extracts audio information using ffprobe
  20. /// </summary>
  21. public class FFProbeAudioInfoProvider : BaseFFProbeProvider<Audio>
  22. {
  23. private readonly IItemRepository _itemRepo;
  24. public FFProbeAudioInfoProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IJsonSerializer jsonSerializer, IItemRepository itemRepo)
  25. : base(logManager, configurationManager, mediaEncoder, jsonSerializer)
  26. {
  27. _itemRepo = itemRepo;
  28. }
  29. public override async Task<bool> FetchAsync(BaseItem item, bool force, BaseProviderInfo providerInfo, CancellationToken cancellationToken)
  30. {
  31. var myItem = (Audio)item;
  32. OnPreFetch(myItem, null);
  33. var result = await GetMediaInfo(item, null, cancellationToken).ConfigureAwait(false);
  34. cancellationToken.ThrowIfCancellationRequested();
  35. NormalizeFFProbeResult(result);
  36. cancellationToken.ThrowIfCancellationRequested();
  37. await Fetch(myItem, cancellationToken, result).ConfigureAwait(false);
  38. SetLastRefreshed(item, DateTime.UtcNow, providerInfo);
  39. return true;
  40. }
  41. /// <summary>
  42. /// Fetches the specified audio.
  43. /// </summary>
  44. /// <param name="audio">The audio.</param>
  45. /// <param name="cancellationToken">The cancellation token.</param>
  46. /// <param name="data">The data.</param>
  47. /// <returns>Task.</returns>
  48. protected Task Fetch(Audio audio, CancellationToken cancellationToken, MediaInfoResult data)
  49. {
  50. var internalStreams = data.streams ?? new MediaStreamInfo[] { };
  51. var mediaStreams = internalStreams.Select(s => GetMediaStream(s, data.format))
  52. .Where(i => i != null)
  53. .ToList();
  54. audio.HasEmbeddedImage = mediaStreams.Any(i => i.Type == MediaStreamType.Video);
  55. // Get the first audio stream
  56. var stream = internalStreams.FirstOrDefault(s => s.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase));
  57. if (stream != null)
  58. {
  59. // Get duration from stream properties
  60. var duration = stream.duration;
  61. // If it's not there go into format properties
  62. if (string.IsNullOrEmpty(duration))
  63. {
  64. duration = data.format.duration;
  65. }
  66. // If we got something, parse it
  67. if (!string.IsNullOrEmpty(duration))
  68. {
  69. audio.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, UsCulture)).Ticks;
  70. }
  71. }
  72. if (data.format.tags != null)
  73. {
  74. FetchDataFromTags(audio, data.format.tags);
  75. }
  76. return _itemRepo.SaveMediaStreams(audio.Id, mediaStreams, cancellationToken);
  77. }
  78. /// <summary>
  79. /// Fetches data from the tags dictionary
  80. /// </summary>
  81. /// <param name="audio">The audio.</param>
  82. /// <param name="tags">The tags.</param>
  83. private void FetchDataFromTags(Audio audio, Dictionary<string, string> tags)
  84. {
  85. var title = GetDictionaryValue(tags, "title");
  86. // Only set Name if title was found in the dictionary
  87. if (!string.IsNullOrEmpty(title))
  88. {
  89. audio.Name = title;
  90. }
  91. if (!audio.LockedFields.Contains(MetadataFields.Cast))
  92. {
  93. audio.People.Clear();
  94. var composer = GetDictionaryValue(tags, "composer");
  95. if (!string.IsNullOrWhiteSpace(composer))
  96. {
  97. foreach (var person in Split(composer))
  98. {
  99. audio.AddPerson(new PersonInfo { Name = person, Type = PersonType.Composer });
  100. }
  101. }
  102. }
  103. audio.Album = GetDictionaryValue(tags, "album");
  104. var artist = GetDictionaryValue(tags, "artist");
  105. if (string.IsNullOrWhiteSpace(artist))
  106. {
  107. audio.Artists.Clear();
  108. }
  109. else
  110. {
  111. audio.Artists = SplitArtists(artist)
  112. .Distinct(StringComparer.OrdinalIgnoreCase)
  113. .ToList();
  114. }
  115. // Several different forms of albumartist
  116. audio.AlbumArtist = GetDictionaryValue(tags, "albumartist") ?? GetDictionaryValue(tags, "album artist") ?? GetDictionaryValue(tags, "album_artist");
  117. // Track number
  118. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  119. // Disc number
  120. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  121. audio.Language = GetDictionaryValue(tags, "language");
  122. audio.ProductionYear = GetDictionaryNumericValue(tags, "date");
  123. // Several different forms of retaildate
  124. audio.PremiereDate = GetDictionaryDateTime(tags, "retaildate") ?? GetDictionaryDateTime(tags, "retail date") ?? GetDictionaryDateTime(tags, "retail_date");
  125. // If we don't have a ProductionYear try and get it from PremiereDate
  126. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  127. {
  128. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  129. }
  130. if (!audio.LockedFields.Contains(MetadataFields.Genres))
  131. {
  132. FetchGenres(audio, tags);
  133. }
  134. if (!audio.LockedFields.Contains(MetadataFields.Studios))
  135. {
  136. audio.Studios.Clear();
  137. // There's several values in tags may or may not be present
  138. FetchStudios(audio, tags, "organization");
  139. FetchStudios(audio, tags, "ensemble");
  140. FetchStudios(audio, tags, "publisher");
  141. }
  142. }
  143. private readonly char[] _nameDelimiters = new[] { '/', '|', ';', '\\' };
  144. /// <summary>
  145. /// Splits the specified val.
  146. /// </summary>
  147. /// <param name="val">The val.</param>
  148. /// <returns>System.String[][].</returns>
  149. private IEnumerable<string> Split(string val)
  150. {
  151. // Only use the comma as a delimeter if there are no slashes or pipes.
  152. // We want to be careful not to split names that have commas in them
  153. var delimeter = _nameDelimiters.Any(i => val.IndexOf(i) != -1) ? _nameDelimiters : new[] { ',' };
  154. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  155. .Where(i => !string.IsNullOrWhiteSpace(i))
  156. .Select(i => i.Trim());
  157. }
  158. private const string ArtistReplaceValue = " | ";
  159. private IEnumerable<string> SplitArtists(string val)
  160. {
  161. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  162. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  163. // Only use the comma as a delimeter if there are no slashes or pipes.
  164. // We want to be careful not to split names that have commas in them
  165. var delimeter = _nameDelimiters;
  166. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  167. .Where(i => !string.IsNullOrWhiteSpace(i))
  168. .Select(i => i.Trim());
  169. }
  170. /// <summary>
  171. /// Gets the studios from the tags collection
  172. /// </summary>
  173. /// <param name="audio">The audio.</param>
  174. /// <param name="tags">The tags.</param>
  175. /// <param name="tagName">Name of the tag.</param>
  176. private void FetchStudios(Audio audio, Dictionary<string, string> tags, string tagName)
  177. {
  178. var val = GetDictionaryValue(tags, tagName);
  179. if (!string.IsNullOrEmpty(val))
  180. {
  181. // Sometimes the artist name is listed here, account for that
  182. var studios = Split(val).Where(i => !audio.HasArtist(i));
  183. foreach (var studio in studios)
  184. {
  185. audio.AddStudio(studio);
  186. }
  187. }
  188. }
  189. /// <summary>
  190. /// Gets the genres from the tags collection
  191. /// </summary>
  192. /// <param name="audio">The audio.</param>
  193. /// <param name="tags">The tags.</param>
  194. private void FetchGenres(Audio audio, Dictionary<string, string> tags)
  195. {
  196. var val = GetDictionaryValue(tags, "genre");
  197. if (!string.IsNullOrEmpty(val))
  198. {
  199. audio.Genres.Clear();
  200. foreach (var genre in Split(val))
  201. {
  202. audio.AddGenre(genre);
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  208. /// </summary>
  209. /// <param name="tags">The tags.</param>
  210. /// <param name="tagName">Name of the tag.</param>
  211. /// <returns>System.Nullable{System.Int32}.</returns>
  212. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  213. {
  214. var disc = GetDictionaryValue(tags, tagName);
  215. if (!string.IsNullOrEmpty(disc))
  216. {
  217. disc = disc.Split('/')[0];
  218. int num;
  219. if (int.TryParse(disc, out num))
  220. {
  221. return num;
  222. }
  223. }
  224. return null;
  225. }
  226. }
  227. }