ProbeResultNormalizer.cs 34 KB

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