FFProbeAudioInfo.cs 15 KB

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