ProbeResultNormalizer.cs 35 KB

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