ProbeResultNormalizer.cs 34 KB

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