FFProbeAudioInfo.cs 14 KB

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