ProbeResultNormalizer.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Model.Dto;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Extensions;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using CommonIO;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.MediaInfo;
  13. namespace MediaBrowser.MediaEncoding.Probing
  14. {
  15. public class ProbeResultNormalizer
  16. {
  17. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  18. private readonly ILogger _logger;
  19. private readonly IFileSystem _fileSystem;
  20. public ProbeResultNormalizer(ILogger logger, IFileSystem fileSystem)
  21. {
  22. _logger = logger;
  23. _fileSystem = fileSystem;
  24. }
  25. public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType videoType, bool isAudio, string path, MediaProtocol protocol)
  26. {
  27. var info = new MediaInfo
  28. {
  29. Path = path,
  30. Protocol = protocol
  31. };
  32. FFProbeHelpers.NormalizeFFProbeResult(data);
  33. SetSize(data, info);
  34. var internalStreams = data.streams ?? new MediaStreamInfo[] { };
  35. info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.format))
  36. .Where(i => i != null)
  37. .ToList();
  38. if (data.format != null)
  39. {
  40. info.Container = data.format.format_name;
  41. if (!string.IsNullOrEmpty(data.format.bit_rate))
  42. {
  43. int value;
  44. if (int.TryParse(data.format.bit_rate, NumberStyles.Any, _usCulture, out value))
  45. {
  46. info.Bitrate = value;
  47. }
  48. }
  49. }
  50. var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  51. var tagStreamType = isAudio ? "info" : "video";
  52. if (data.streams != null)
  53. {
  54. var tagStream = data.streams.FirstOrDefault(i => string.Equals(i.codec_type, tagStreamType, StringComparison.OrdinalIgnoreCase));
  55. if (tagStream != null && tagStream.tags != null)
  56. {
  57. foreach (var pair in tagStream.tags)
  58. {
  59. tags[pair.Key] = pair.Value;
  60. }
  61. }
  62. }
  63. if (data.format != null && data.format.tags != null)
  64. {
  65. foreach (var pair in data.format.tags)
  66. {
  67. tags[pair.Key] = pair.Value;
  68. }
  69. }
  70. FetchGenres(info, tags);
  71. var shortOverview = FFProbeHelpers.GetDictionaryValue(tags, "description");
  72. var overview = FFProbeHelpers.GetDictionaryValue(tags, "synopsis");
  73. if (string.IsNullOrWhiteSpace(overview))
  74. {
  75. overview = shortOverview;
  76. shortOverview = null;
  77. }
  78. if (string.IsNullOrWhiteSpace(overview))
  79. {
  80. overview = FFProbeHelpers.GetDictionaryValue(tags, "desc");
  81. }
  82. if (!string.IsNullOrWhiteSpace(overview))
  83. {
  84. info.Overview = overview;
  85. }
  86. if (!string.IsNullOrWhiteSpace(shortOverview))
  87. {
  88. info.ShortOverview = shortOverview;
  89. }
  90. var title = FFProbeHelpers.GetDictionaryValue(tags, "title");
  91. if (!string.IsNullOrWhiteSpace(title))
  92. {
  93. info.Name = title;
  94. }
  95. info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
  96. // Several different forms of retaildate
  97. info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
  98. FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
  99. FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
  100. FFProbeHelpers.GetDictionaryDateTime(tags, "date");
  101. if (isAudio)
  102. {
  103. SetAudioRuntimeTicks(data, info);
  104. // tags are normally located under data.format, but we've seen some cases with ogg where they're part of the info stream
  105. // so let's create a combined list of both
  106. SetAudioInfoFromTags(info, tags);
  107. }
  108. else
  109. {
  110. FetchStudios(info, tags, "copyright");
  111. var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC");
  112. if (!string.IsNullOrWhiteSpace(iTunEXTC))
  113. {
  114. var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
  115. // Example
  116. // mpaa|G|100|For crude humor
  117. if (parts.Length == 4)
  118. {
  119. info.OfficialRating = parts[1];
  120. info.OfficialRatingDescription = parts[3];
  121. }
  122. }
  123. var itunesXml = FFProbeHelpers.GetDictionaryValue(tags, "iTunMOVI");
  124. if (!string.IsNullOrWhiteSpace(itunesXml))
  125. {
  126. FetchFromItunesInfo(itunesXml, info);
  127. }
  128. if (data.format != null && !string.IsNullOrEmpty(data.format.duration))
  129. {
  130. info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
  131. }
  132. FetchWtvInfo(info, data);
  133. if (data.Chapters != null)
  134. {
  135. info.Chapters = data.Chapters.Select(GetChapterInfo).ToList();
  136. }
  137. ExtractTimestamp(info);
  138. }
  139. return info;
  140. }
  141. private void FetchFromItunesInfo(string xml, MediaInfo info)
  142. {
  143. // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>cast</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Blender Foundation</string>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Janus Bager Kristensen</string>\n\t\t</dict>\n\t</array>\n\t<key>directors</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Sacha Goedegebure</string>\n\t\t</dict>\n\t</array>\n\t<key>studio</key>\n\t<string>Blender Foundation</string>\n</dict>\n</plist>\n
  144. }
  145. /// <summary>
  146. /// Converts ffprobe stream info to our MediaStream class
  147. /// </summary>
  148. /// <param name="isAudio">if set to <c>true</c> [is info].</param>
  149. /// <param name="streamInfo">The stream info.</param>
  150. /// <param name="formatInfo">The format info.</param>
  151. /// <returns>MediaStream.</returns>
  152. private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  153. {
  154. // These are mp4 chapters
  155. if (string.Equals(streamInfo.codec_name, "mov_text", StringComparison.OrdinalIgnoreCase))
  156. {
  157. return null;
  158. }
  159. var stream = new MediaStream
  160. {
  161. Codec = streamInfo.codec_name,
  162. Profile = streamInfo.profile,
  163. Level = streamInfo.level,
  164. Index = streamInfo.index,
  165. PixelFormat = streamInfo.pix_fmt
  166. };
  167. // Filter out junk
  168. if (!string.IsNullOrWhiteSpace(streamInfo.codec_tag_string) && streamInfo.codec_tag_string.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
  169. {
  170. stream.CodecTag = streamInfo.codec_tag_string;
  171. }
  172. if (streamInfo.tags != null)
  173. {
  174. stream.Language = GetDictionaryValue(streamInfo.tags, "language");
  175. stream.Comment = GetDictionaryValue(streamInfo.tags, "comment");
  176. }
  177. if (string.Equals(streamInfo.codec_type, "info", StringComparison.OrdinalIgnoreCase))
  178. {
  179. stream.Type = MediaStreamType.Audio;
  180. stream.Channels = streamInfo.channels;
  181. if (!string.IsNullOrEmpty(streamInfo.sample_rate))
  182. {
  183. int value;
  184. if (int.TryParse(streamInfo.sample_rate, NumberStyles.Any, _usCulture, out value))
  185. {
  186. stream.SampleRate = value;
  187. }
  188. }
  189. stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout);
  190. if (streamInfo.bits_per_sample > 0)
  191. {
  192. stream.BitDepth = streamInfo.bits_per_sample;
  193. }
  194. else if (streamInfo.bits_per_raw_sample > 0)
  195. {
  196. stream.BitDepth = streamInfo.bits_per_raw_sample;
  197. }
  198. }
  199. else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase))
  200. {
  201. stream.Type = MediaStreamType.Subtitle;
  202. }
  203. else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase))
  204. {
  205. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase)
  206. ? MediaStreamType.EmbeddedImage
  207. : MediaStreamType.Video;
  208. stream.Width = streamInfo.width;
  209. stream.Height = streamInfo.height;
  210. stream.AspectRatio = GetAspectRatio(streamInfo);
  211. stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate);
  212. stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate);
  213. if (streamInfo.bits_per_sample > 0)
  214. {
  215. stream.BitDepth = streamInfo.bits_per_sample;
  216. }
  217. else if (streamInfo.bits_per_raw_sample > 0)
  218. {
  219. stream.BitDepth = streamInfo.bits_per_raw_sample;
  220. }
  221. //stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  222. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  223. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  224. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  225. stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase);
  226. if (streamInfo.refs > 0)
  227. {
  228. stream.RefFrames = streamInfo.refs;
  229. }
  230. }
  231. else
  232. {
  233. return null;
  234. }
  235. // Get stream bitrate
  236. var bitrate = 0;
  237. if (!string.IsNullOrEmpty(streamInfo.bit_rate))
  238. {
  239. int value;
  240. if (int.TryParse(streamInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  241. {
  242. bitrate = value;
  243. }
  244. }
  245. if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate) && stream.Type == MediaStreamType.Video)
  246. {
  247. // If the stream info doesn't have a bitrate get the value from the media format info
  248. int value;
  249. if (int.TryParse(formatInfo.bit_rate, NumberStyles.Any, _usCulture, out value))
  250. {
  251. bitrate = value;
  252. }
  253. }
  254. if (bitrate > 0)
  255. {
  256. stream.BitRate = bitrate;
  257. }
  258. if (streamInfo.disposition != null)
  259. {
  260. var isDefault = GetDictionaryValue(streamInfo.disposition, "default");
  261. var isForced = GetDictionaryValue(streamInfo.disposition, "forced");
  262. stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase);
  263. stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase);
  264. }
  265. return stream;
  266. }
  267. /// <summary>
  268. /// Gets a string from an FFProbeResult tags dictionary
  269. /// </summary>
  270. /// <param name="tags">The tags.</param>
  271. /// <param name="key">The key.</param>
  272. /// <returns>System.String.</returns>
  273. private string GetDictionaryValue(Dictionary<string, string> tags, string key)
  274. {
  275. if (tags == null)
  276. {
  277. return null;
  278. }
  279. string val;
  280. tags.TryGetValue(key, out val);
  281. return val;
  282. }
  283. private string ParseChannelLayout(string input)
  284. {
  285. if (string.IsNullOrEmpty(input))
  286. {
  287. return input;
  288. }
  289. return input.Split('(').FirstOrDefault();
  290. }
  291. private string GetAspectRatio(MediaStreamInfo info)
  292. {
  293. var original = info.display_aspect_ratio;
  294. int height;
  295. int width;
  296. var parts = (original ?? string.Empty).Split(':');
  297. if (!(parts.Length == 2 &&
  298. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out width) &&
  299. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out height) &&
  300. width > 0 &&
  301. height > 0))
  302. {
  303. width = info.width;
  304. height = info.height;
  305. }
  306. if (width > 0 && height > 0)
  307. {
  308. double ratio = width;
  309. ratio /= height;
  310. if (IsClose(ratio, 1.777777778, .03))
  311. {
  312. return "16:9";
  313. }
  314. if (IsClose(ratio, 1.3333333333, .05))
  315. {
  316. return "4:3";
  317. }
  318. if (IsClose(ratio, 1.41))
  319. {
  320. return "1.41:1";
  321. }
  322. if (IsClose(ratio, 1.5))
  323. {
  324. return "1.5:1";
  325. }
  326. if (IsClose(ratio, 1.6))
  327. {
  328. return "1.6:1";
  329. }
  330. if (IsClose(ratio, 1.66666666667))
  331. {
  332. return "5:3";
  333. }
  334. if (IsClose(ratio, 1.85, .02))
  335. {
  336. return "1.85:1";
  337. }
  338. if (IsClose(ratio, 2.35, .025))
  339. {
  340. return "2.35:1";
  341. }
  342. if (IsClose(ratio, 2.4, .025))
  343. {
  344. return "2.40:1";
  345. }
  346. }
  347. return original;
  348. }
  349. private bool IsClose(double d1, double d2, double variance = .005)
  350. {
  351. return Math.Abs(d1 - d2) <= variance;
  352. }
  353. /// <summary>
  354. /// Gets a frame rate from a string value in ffprobe output
  355. /// This could be a number or in the format of 2997/125.
  356. /// </summary>
  357. /// <param name="value">The value.</param>
  358. /// <returns>System.Nullable{System.Single}.</returns>
  359. private float? GetFrameRate(string value)
  360. {
  361. if (!string.IsNullOrEmpty(value))
  362. {
  363. var parts = value.Split('/');
  364. float result;
  365. if (parts.Length == 2)
  366. {
  367. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  368. }
  369. else
  370. {
  371. result = float.Parse(parts[0], _usCulture);
  372. }
  373. return float.IsNaN(result) ? (float?)null : result;
  374. }
  375. return null;
  376. }
  377. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, Model.MediaInfo.MediaInfo data)
  378. {
  379. if (result.streams != null)
  380. {
  381. // Get the first info stream
  382. var stream = result.streams.FirstOrDefault(s => string.Equals(s.codec_type, "info", StringComparison.OrdinalIgnoreCase));
  383. if (stream != null)
  384. {
  385. // Get duration from stream properties
  386. var duration = stream.duration;
  387. // If it's not there go into format properties
  388. if (string.IsNullOrEmpty(duration))
  389. {
  390. duration = result.format.duration;
  391. }
  392. // If we got something, parse it
  393. if (!string.IsNullOrEmpty(duration))
  394. {
  395. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  396. }
  397. }
  398. }
  399. }
  400. private void SetSize(InternalMediaInfoResult data, Model.MediaInfo.MediaInfo info)
  401. {
  402. if (data.format != null)
  403. {
  404. if (!string.IsNullOrEmpty(data.format.size))
  405. {
  406. info.Size = long.Parse(data.format.size, _usCulture);
  407. }
  408. else
  409. {
  410. info.Size = null;
  411. }
  412. }
  413. }
  414. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  415. {
  416. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  417. if (!string.IsNullOrWhiteSpace(composer))
  418. {
  419. foreach (var person in Split(composer, false))
  420. {
  421. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  422. }
  423. }
  424. var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  425. if (!string.IsNullOrWhiteSpace(conductor))
  426. {
  427. foreach (var person in Split(conductor, false))
  428. {
  429. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  430. }
  431. }
  432. var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  433. if (!string.IsNullOrWhiteSpace(lyricist))
  434. {
  435. foreach (var person in Split(lyricist, false))
  436. {
  437. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  438. }
  439. }
  440. // Check for writer some music is tagged that way as alternative to composer/lyricist
  441. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  442. if (!string.IsNullOrWhiteSpace(writer))
  443. {
  444. foreach (var person in Split(writer, false))
  445. {
  446. audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  447. }
  448. }
  449. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  450. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  451. if (!string.IsNullOrWhiteSpace(artists))
  452. {
  453. audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
  454. .Distinct(StringComparer.OrdinalIgnoreCase)
  455. .ToList();
  456. }
  457. else
  458. {
  459. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  460. if (string.IsNullOrWhiteSpace(artist))
  461. {
  462. audio.Artists.Clear();
  463. }
  464. else
  465. {
  466. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  467. .Distinct(StringComparer.OrdinalIgnoreCase)
  468. .ToList();
  469. }
  470. }
  471. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  472. if (string.IsNullOrWhiteSpace(albumArtist))
  473. {
  474. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  475. }
  476. if (string.IsNullOrWhiteSpace(albumArtist))
  477. {
  478. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  479. }
  480. if (string.IsNullOrWhiteSpace(albumArtist))
  481. {
  482. audio.AlbumArtists = new List<string>();
  483. }
  484. else
  485. {
  486. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  487. .Distinct(StringComparer.OrdinalIgnoreCase)
  488. .ToList();
  489. }
  490. // Track number
  491. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  492. // Disc number
  493. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  494. // If we don't have a ProductionYear try and get it from PremiereDate
  495. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  496. {
  497. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  498. }
  499. // There's several values in tags may or may not be present
  500. FetchStudios(audio, tags, "organization");
  501. FetchStudios(audio, tags, "ensemble");
  502. FetchStudios(audio, tags, "publisher");
  503. FetchStudios(audio, tags, "label");
  504. // These support mulitple values, but for now we only store the first.
  505. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  506. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  507. audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);
  508. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  509. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  510. audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);
  511. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  512. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  513. audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);
  514. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  515. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  516. audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);
  517. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
  518. if (mb == null) mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  519. audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
  520. }
  521. private string GetMultipleMusicBrainzId(string value)
  522. {
  523. if (string.IsNullOrWhiteSpace(value))
  524. {
  525. return null;
  526. }
  527. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  528. .Select(i => i.Trim())
  529. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  530. }
  531. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  532. /// <summary>
  533. /// Splits the specified val.
  534. /// </summary>
  535. /// <param name="val">The val.</param>
  536. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  537. /// <returns>System.String[][].</returns>
  538. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  539. {
  540. // Only use the comma as a delimeter if there are no slashes or pipes.
  541. // We want to be careful not to split names that have commas in them
  542. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  543. _nameDelimiters :
  544. new[] { ',' };
  545. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  546. .Where(i => !string.IsNullOrWhiteSpace(i))
  547. .Select(i => i.Trim());
  548. }
  549. private const string ArtistReplaceValue = " | ";
  550. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  551. {
  552. if (splitFeaturing)
  553. {
  554. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  555. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  556. }
  557. var artistsFound = new List<string>();
  558. foreach (var whitelistArtist in GetSplitWhitelist())
  559. {
  560. var originalVal = val;
  561. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  562. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  563. {
  564. artistsFound.Add(whitelistArtist);
  565. }
  566. }
  567. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  568. .Where(i => !string.IsNullOrWhiteSpace(i))
  569. .Select(i => i.Trim());
  570. artistsFound.AddRange(artists);
  571. return artistsFound;
  572. }
  573. private List<string> _splitWhiteList = null;
  574. private IEnumerable<string> GetSplitWhitelist()
  575. {
  576. if (_splitWhiteList == null)
  577. {
  578. var file = GetType().Namespace + ".whitelist.txt";
  579. using (var stream = GetType().Assembly.GetManifestResourceStream(file))
  580. {
  581. using (var reader = new StreamReader(stream))
  582. {
  583. var list = new List<string>();
  584. while (!reader.EndOfStream)
  585. {
  586. var val = reader.ReadLine();
  587. if (!string.IsNullOrWhiteSpace(val))
  588. {
  589. list.Add(val);
  590. }
  591. }
  592. _splitWhiteList = list;
  593. }
  594. }
  595. }
  596. return _splitWhiteList;
  597. }
  598. /// <summary>
  599. /// Gets the studios from the tags collection
  600. /// </summary>
  601. /// <param name="info">The info.</param>
  602. /// <param name="tags">The tags.</param>
  603. /// <param name="tagName">Name of the tag.</param>
  604. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  605. {
  606. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  607. if (!string.IsNullOrEmpty(val))
  608. {
  609. var studios = Split(val, true);
  610. foreach (var studio in studios)
  611. {
  612. // Sometimes the artist name is listed here, account for that
  613. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  614. {
  615. continue;
  616. }
  617. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  618. {
  619. continue;
  620. }
  621. info.Studios.Add(studio);
  622. }
  623. info.Studios = info.Studios
  624. .Where(i => !string.IsNullOrWhiteSpace(i))
  625. .Distinct(StringComparer.OrdinalIgnoreCase)
  626. .ToList();
  627. }
  628. }
  629. /// <summary>
  630. /// Gets the genres from the tags collection
  631. /// </summary>
  632. /// <param name="info">The information.</param>
  633. /// <param name="tags">The tags.</param>
  634. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  635. {
  636. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  637. if (!string.IsNullOrEmpty(val))
  638. {
  639. foreach (var genre in Split(val, true))
  640. {
  641. info.Genres.Add(genre);
  642. }
  643. info.Genres = info.Genres
  644. .Where(i => !string.IsNullOrWhiteSpace(i))
  645. .Distinct(StringComparer.OrdinalIgnoreCase)
  646. .ToList();
  647. }
  648. }
  649. /// <summary>
  650. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  651. /// </summary>
  652. /// <param name="tags">The tags.</param>
  653. /// <param name="tagName">Name of the tag.</param>
  654. /// <returns>System.Nullable{System.Int32}.</returns>
  655. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  656. {
  657. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  658. if (!string.IsNullOrEmpty(disc))
  659. {
  660. disc = disc.Split('/')[0];
  661. int num;
  662. if (int.TryParse(disc, out num))
  663. {
  664. return num;
  665. }
  666. }
  667. return null;
  668. }
  669. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  670. {
  671. var info = new ChapterInfo();
  672. if (chapter.tags != null)
  673. {
  674. string name;
  675. if (chapter.tags.TryGetValue("title", out name))
  676. {
  677. info.Name = name;
  678. }
  679. }
  680. // Limit accuracy to milliseconds to match xml saving
  681. var secondsString = chapter.start_time;
  682. double seconds;
  683. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
  684. {
  685. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  686. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  687. }
  688. return info;
  689. }
  690. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  691. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  692. {
  693. if (data.format == null || data.format.tags == null)
  694. {
  695. return;
  696. }
  697. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");
  698. if (!string.IsNullOrWhiteSpace(genres))
  699. {
  700. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  701. .Where(i => !string.IsNullOrWhiteSpace(i))
  702. .Select(i => i.Trim())
  703. .ToList();
  704. // If this is empty then don't overwrite genres that might have been fetched earlier
  705. if (genreList.Count > 0)
  706. {
  707. video.Genres = genreList;
  708. }
  709. }
  710. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  711. if (!string.IsNullOrWhiteSpace(officialRating))
  712. {
  713. video.OfficialRating = officialRating;
  714. }
  715. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  716. if (!string.IsNullOrEmpty(people))
  717. {
  718. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  719. .Where(i => !string.IsNullOrWhiteSpace(i))
  720. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  721. .ToList();
  722. }
  723. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  724. if (!string.IsNullOrWhiteSpace(year))
  725. {
  726. int val;
  727. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  728. {
  729. video.ProductionYear = val;
  730. }
  731. }
  732. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");
  733. if (!string.IsNullOrWhiteSpace(premiereDateString))
  734. {
  735. DateTime val;
  736. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  737. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  738. if (DateTime.TryParse(year, null, DateTimeStyles.None, out val))
  739. {
  740. video.PremiereDate = val.ToUniversalTime();
  741. }
  742. }
  743. var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  744. var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");
  745. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  746. // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, extract if possible. See ticket https://mcebuddy2x.codeplex.com/workitem/1910
  747. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  748. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  749. // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the Doctor puts Amy, Rory and his beloved TARDIS in grave danger. Also in HD. [AD,S]
  750. // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in the middle of the big city. Some of Abney and Teal's favourite objects are missing. [S]
  751. if (String.IsNullOrWhiteSpace(subTitle) && !String.IsNullOrWhiteSpace(description) && description.Substring(0, Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)).Contains(":")) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
  752. {
  753. string[] parts = description.Split(':');
  754. if (parts.Length > 0)
  755. {
  756. string subtitle = parts[0];
  757. try
  758. {
  759. if (subtitle.Contains("/")) // It contains a episode number and season number
  760. {
  761. string[] numbers = subtitle.Split(' ');
  762. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  763. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  764. description = String.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  765. }
  766. else
  767. throw new Exception(); // Switch to default parsing
  768. }
  769. catch // Default parsing
  770. {
  771. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  772. description = String.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  773. else
  774. description = subtitle.Trim(); // Clean up whitespaces and save it
  775. }
  776. }
  777. }
  778. if (!string.IsNullOrWhiteSpace(description))
  779. {
  780. video.Overview = description;
  781. }
  782. }
  783. private void ExtractTimestamp(MediaInfo video)
  784. {
  785. if (video.VideoType == VideoType.VideoFile)
  786. {
  787. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  788. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  789. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  790. {
  791. try
  792. {
  793. video.Timestamp = GetMpegTimestamp(video.Path);
  794. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  795. }
  796. catch (Exception ex)
  797. {
  798. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  799. video.Timestamp = null;
  800. }
  801. }
  802. }
  803. }
  804. private TransportStreamTimestamp GetMpegTimestamp(string path)
  805. {
  806. var packetBuffer = new byte['Å'];
  807. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  808. {
  809. fs.Read(packetBuffer, 0, packetBuffer.Length);
  810. }
  811. if (packetBuffer[0] == 71)
  812. {
  813. return TransportStreamTimestamp.None;
  814. }
  815. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  816. {
  817. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  818. {
  819. return TransportStreamTimestamp.Zero;
  820. }
  821. return TransportStreamTimestamp.Valid;
  822. }
  823. return TransportStreamTimestamp.None;
  824. }
  825. }
  826. }