ProbeResultNormalizer.cs 33 KB

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