FFProbeAudioInfoProvider.cs 9.3 KB

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