ProbeResultNormalizer.cs 35 KB

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