FFProbeAudioInfoProvider.cs 9.8 KB

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