ProbeResultNormalizer.cs 35 KB

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