ProbeResultNormalizer.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Xml;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Globalization;
  12. using MediaBrowser.Model.MediaInfo;
  13. using Microsoft.Extensions.Logging;
  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 ILocalizationManager _localization;
  21. public ProbeResultNormalizer(ILogger logger, ILocalizationManager localization)
  22. {
  23. _logger = logger;
  24. _localization = localization;
  25. }
  26. public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType? videoType, bool isAudio, string path, MediaProtocol protocol)
  27. {
  28. var info = new MediaInfo
  29. {
  30. Path = path,
  31. Protocol = protocol
  32. };
  33. FFProbeHelpers.NormalizeFFProbeResult(data);
  34. SetSize(data, info);
  35. var internalStreams = data.Streams ?? Array.Empty<MediaStreamInfo>();
  36. info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.Format))
  37. .Where(i => i != null)
  38. // Drop subtitle streams if we don't know the codec because it will just cause failures if we don't know how to handle them
  39. .Where(i => i.Type != MediaStreamType.Subtitle || !string.IsNullOrWhiteSpace(i.Codec))
  40. .ToList();
  41. info.MediaAttachments = internalStreams.Select(s => GetMediaAttachment(s))
  42. .Where(i => i != null)
  43. .ToList();
  44. if (data.Format != null)
  45. {
  46. info.Container = NormalizeFormat(data.Format.FormatName);
  47. if (!string.IsNullOrEmpty(data.Format.BitRate))
  48. {
  49. if (int.TryParse(data.Format.BitRate, NumberStyles.Any, _usCulture, out var value))
  50. {
  51. info.Bitrate = value;
  52. }
  53. }
  54. }
  55. var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  56. var tagStreamType = isAudio ? "audio" : "video";
  57. if (data.Streams != null)
  58. {
  59. var tagStream = data.Streams.FirstOrDefault(i => string.Equals(i.CodecType, tagStreamType, StringComparison.OrdinalIgnoreCase));
  60. if (tagStream != null && tagStream.Tags != null)
  61. {
  62. foreach (var pair in tagStream.Tags)
  63. {
  64. tags[pair.Key] = pair.Value;
  65. }
  66. }
  67. }
  68. if (data.Format != null && data.Format.Tags != null)
  69. {
  70. foreach (var pair in data.Format.Tags)
  71. {
  72. tags[pair.Key] = pair.Value;
  73. }
  74. }
  75. FetchGenres(info, tags);
  76. var overview = FFProbeHelpers.GetDictionaryValue(tags, "synopsis");
  77. if (string.IsNullOrWhiteSpace(overview))
  78. {
  79. overview = FFProbeHelpers.GetDictionaryValue(tags, "description");
  80. }
  81. if (string.IsNullOrWhiteSpace(overview))
  82. {
  83. overview = FFProbeHelpers.GetDictionaryValue(tags, "desc");
  84. }
  85. if (!string.IsNullOrWhiteSpace(overview))
  86. {
  87. info.Overview = overview;
  88. }
  89. var title = FFProbeHelpers.GetDictionaryValue(tags, "title");
  90. if (!string.IsNullOrWhiteSpace(title))
  91. {
  92. info.Name = title;
  93. }
  94. info.IndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "episode_sort");
  95. info.ParentIndexNumber = FFProbeHelpers.GetDictionaryNumericValue(tags, "season_number");
  96. info.ShowName = FFProbeHelpers.GetDictionaryValue(tags, "show_name");
  97. info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");
  98. // Several different forms of retaildate
  99. info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
  100. FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
  101. FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
  102. FFProbeHelpers.GetDictionaryDateTime(tags, "date");
  103. if (isAudio)
  104. {
  105. SetAudioRuntimeTicks(data, info);
  106. // tags are normally located under data.format, but we've seen some cases with ogg where they're part of the info stream
  107. // so let's create a combined list of both
  108. SetAudioInfoFromTags(info, tags);
  109. }
  110. else
  111. {
  112. FetchStudios(info, tags, "copyright");
  113. var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC");
  114. if (!string.IsNullOrWhiteSpace(iTunEXTC))
  115. {
  116. var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
  117. // Example
  118. // mpaa|G|100|For crude humor
  119. if (parts.Length > 1)
  120. {
  121. info.OfficialRating = parts[1];
  122. if (parts.Length > 3)
  123. {
  124. info.OfficialRatingDescription = parts[3];
  125. }
  126. }
  127. }
  128. var itunesXml = FFProbeHelpers.GetDictionaryValue(tags, "iTunMOVI");
  129. if (!string.IsNullOrWhiteSpace(itunesXml))
  130. {
  131. FetchFromItunesInfo(itunesXml, info);
  132. }
  133. if (data.Format != null && !string.IsNullOrEmpty(data.Format.Duration))
  134. {
  135. info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.Format.Duration, _usCulture)).Ticks;
  136. }
  137. FetchWtvInfo(info, data);
  138. if (data.Chapters != null)
  139. {
  140. info.Chapters = data.Chapters.Select(GetChapterInfo).ToArray();
  141. }
  142. ExtractTimestamp(info);
  143. var stereoMode = GetDictionaryValue(tags, "stereo_mode");
  144. if (string.Equals(stereoMode, "left_right", StringComparison.OrdinalIgnoreCase))
  145. {
  146. info.Video3DFormat = Video3DFormat.FullSideBySide;
  147. }
  148. foreach (var mediaStream in info.MediaStreams)
  149. {
  150. if (mediaStream.Type == MediaStreamType.Audio && !mediaStream.BitRate.HasValue)
  151. {
  152. mediaStream.BitRate = GetEstimatedAudioBitrate(mediaStream.Codec, mediaStream.Channels);
  153. }
  154. }
  155. var videoStreamsBitrate = info.MediaStreams.Where(i => i.Type == MediaStreamType.Video).Select(i => i.BitRate ?? 0).Sum();
  156. // If ffprobe reported the container bitrate as being the same as the video stream bitrate, then it's wrong
  157. if (videoStreamsBitrate == (info.Bitrate ?? 0))
  158. {
  159. info.InferTotalBitrate(true);
  160. }
  161. }
  162. return info;
  163. }
  164. private string NormalizeFormat(string format)
  165. {
  166. if (string.IsNullOrWhiteSpace(format))
  167. {
  168. return null;
  169. }
  170. if (string.Equals(format, "mpegvideo", StringComparison.OrdinalIgnoreCase))
  171. {
  172. return "mpeg";
  173. }
  174. format = format.Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
  175. return format;
  176. }
  177. private int? GetEstimatedAudioBitrate(string codec, int? channels)
  178. {
  179. if (!channels.HasValue)
  180. {
  181. return null;
  182. }
  183. var channelsValue = channels.Value;
  184. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase) ||
  185. string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  186. {
  187. if (channelsValue <= 2)
  188. {
  189. return 192000;
  190. }
  191. if (channelsValue >= 5)
  192. {
  193. return 320000;
  194. }
  195. }
  196. return null;
  197. }
  198. private void FetchFromItunesInfo(string xml, MediaInfo info)
  199. {
  200. // Make things simpler and strip out the dtd
  201. var plistIndex = xml.IndexOf("<plist", StringComparison.OrdinalIgnoreCase);
  202. if (plistIndex != -1)
  203. {
  204. xml = xml.Substring(plistIndex);
  205. }
  206. xml = "<?xml version=\"1.0\"?>" + xml;
  207. // <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>cast</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Blender Foundation</string>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Janus Bager Kristensen</string>\n\t\t</dict>\n\t</array>\n\t<key>directors</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>name</key>\n\t\t\t<string>Sacha Goedegebure</string>\n\t\t</dict>\n\t</array>\n\t<key>studio</key>\n\t<string>Blender Foundation</string>\n</dict>\n</plist>\n
  208. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
  209. using (var streamReader = new StreamReader(stream))
  210. {
  211. try
  212. {
  213. using (var reader = XmlReader.Create(streamReader))
  214. {
  215. reader.MoveToContent();
  216. reader.Read();
  217. // Loop through each element
  218. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  219. {
  220. if (reader.NodeType == XmlNodeType.Element)
  221. {
  222. switch (reader.Name)
  223. {
  224. case "dict":
  225. if (reader.IsEmptyElement)
  226. {
  227. reader.Read();
  228. continue;
  229. }
  230. using (var subtree = reader.ReadSubtree())
  231. {
  232. ReadFromDictNode(subtree, info);
  233. }
  234. break;
  235. default:
  236. reader.Skip();
  237. break;
  238. }
  239. }
  240. else
  241. {
  242. reader.Read();
  243. }
  244. }
  245. }
  246. }
  247. catch (XmlException)
  248. {
  249. // I've seen probe examples where the iTunMOVI value is just "<"
  250. // So we should not allow this to fail the entire probing operation
  251. }
  252. }
  253. }
  254. private void ReadFromDictNode(XmlReader reader, MediaInfo info)
  255. {
  256. string currentKey = null;
  257. var pairs = new List<NameValuePair>();
  258. reader.MoveToContent();
  259. reader.Read();
  260. // Loop through each element
  261. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  262. {
  263. if (reader.NodeType == XmlNodeType.Element)
  264. {
  265. switch (reader.Name)
  266. {
  267. case "key":
  268. if (!string.IsNullOrWhiteSpace(currentKey))
  269. {
  270. ProcessPairs(currentKey, pairs, info);
  271. }
  272. currentKey = reader.ReadElementContentAsString();
  273. pairs = new List<NameValuePair>();
  274. break;
  275. case "string":
  276. var value = reader.ReadElementContentAsString();
  277. if (!string.IsNullOrWhiteSpace(value))
  278. {
  279. pairs.Add(new NameValuePair
  280. {
  281. Name = value,
  282. Value = value
  283. });
  284. }
  285. break;
  286. case "array":
  287. if (reader.IsEmptyElement)
  288. {
  289. reader.Read();
  290. continue;
  291. }
  292. using (var subtree = reader.ReadSubtree())
  293. {
  294. if (!string.IsNullOrWhiteSpace(currentKey))
  295. {
  296. pairs.AddRange(ReadValueArray(subtree));
  297. }
  298. }
  299. break;
  300. default:
  301. reader.Skip();
  302. break;
  303. }
  304. }
  305. else
  306. {
  307. reader.Read();
  308. }
  309. }
  310. }
  311. private List<NameValuePair> ReadValueArray(XmlReader reader)
  312. {
  313. var pairs = new List<NameValuePair>();
  314. reader.MoveToContent();
  315. reader.Read();
  316. // Loop through each element
  317. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  318. {
  319. if (reader.NodeType == XmlNodeType.Element)
  320. {
  321. switch (reader.Name)
  322. {
  323. case "dict":
  324. if (reader.IsEmptyElement)
  325. {
  326. reader.Read();
  327. continue;
  328. }
  329. using (var subtree = reader.ReadSubtree())
  330. {
  331. var dict = GetNameValuePair(subtree);
  332. if (dict != null)
  333. {
  334. pairs.Add(dict);
  335. }
  336. }
  337. break;
  338. default:
  339. reader.Skip();
  340. break;
  341. }
  342. }
  343. else
  344. {
  345. reader.Read();
  346. }
  347. }
  348. return pairs;
  349. }
  350. private void ProcessPairs(string key, List<NameValuePair> pairs, MediaInfo info)
  351. {
  352. IList<BaseItemPerson> peoples = new List<BaseItemPerson>();
  353. if (string.Equals(key, "studio", StringComparison.OrdinalIgnoreCase))
  354. {
  355. info.Studios = pairs.Select(p => p.Value)
  356. .Where(i => !string.IsNullOrWhiteSpace(i))
  357. .Distinct(StringComparer.OrdinalIgnoreCase)
  358. .ToArray();
  359. }
  360. else if (string.Equals(key, "screenwriters", StringComparison.OrdinalIgnoreCase))
  361. {
  362. foreach (var pair in pairs)
  363. {
  364. peoples.Add(new BaseItemPerson
  365. {
  366. Name = pair.Value,
  367. Type = PersonType.Writer
  368. });
  369. }
  370. }
  371. else if (string.Equals(key, "producers", StringComparison.OrdinalIgnoreCase))
  372. {
  373. foreach (var pair in pairs)
  374. {
  375. peoples.Add(new BaseItemPerson
  376. {
  377. Name = pair.Value,
  378. Type = PersonType.Producer
  379. });
  380. }
  381. }
  382. else if (string.Equals(key, "directors", StringComparison.OrdinalIgnoreCase))
  383. {
  384. foreach (var pair in pairs)
  385. {
  386. peoples.Add(new BaseItemPerson
  387. {
  388. Name = pair.Value,
  389. Type = PersonType.Director
  390. });
  391. }
  392. }
  393. info.People = peoples.ToArray();
  394. }
  395. private NameValuePair GetNameValuePair(XmlReader reader)
  396. {
  397. string name = null;
  398. string value = null;
  399. reader.MoveToContent();
  400. reader.Read();
  401. // Loop through each element
  402. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  403. {
  404. if (reader.NodeType == XmlNodeType.Element)
  405. {
  406. switch (reader.Name)
  407. {
  408. case "key":
  409. name = reader.ReadElementContentAsString();
  410. break;
  411. case "string":
  412. value = reader.ReadElementContentAsString();
  413. break;
  414. default:
  415. reader.Skip();
  416. break;
  417. }
  418. }
  419. else
  420. {
  421. reader.Read();
  422. }
  423. }
  424. if (string.IsNullOrWhiteSpace(name) ||
  425. string.IsNullOrWhiteSpace(value))
  426. {
  427. return null;
  428. }
  429. return new NameValuePair
  430. {
  431. Name = name,
  432. Value = value
  433. };
  434. }
  435. private string NormalizeSubtitleCodec(string codec)
  436. {
  437. if (string.Equals(codec, "dvb_subtitle", StringComparison.OrdinalIgnoreCase))
  438. {
  439. codec = "dvbsub";
  440. }
  441. else if ((codec ?? string.Empty).IndexOf("PGS", StringComparison.OrdinalIgnoreCase) != -1)
  442. {
  443. codec = "PGSSUB";
  444. }
  445. else if ((codec ?? string.Empty).IndexOf("DVD", StringComparison.OrdinalIgnoreCase) != -1)
  446. {
  447. codec = "DVDSUB";
  448. }
  449. return codec;
  450. }
  451. /// <summary>
  452. /// Converts ffprobe stream info to our MediaAttachment class.
  453. /// </summary>
  454. /// <param name="streamInfo">The stream info.</param>
  455. /// <returns>MediaAttachments.</returns>
  456. private MediaAttachment GetMediaAttachment(MediaStreamInfo streamInfo)
  457. {
  458. if (!string.Equals(streamInfo.CodecType, "attachment", StringComparison.OrdinalIgnoreCase))
  459. {
  460. return null;
  461. }
  462. var attachment = new MediaAttachment
  463. {
  464. Codec = streamInfo.CodecName,
  465. Index = streamInfo.Index
  466. };
  467. if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString))
  468. {
  469. attachment.CodecTag = streamInfo.CodecTagString;
  470. }
  471. if (streamInfo.Tags != null)
  472. {
  473. attachment.FileName = GetDictionaryValue(streamInfo.Tags, "filename");
  474. attachment.MimeType = GetDictionaryValue(streamInfo.Tags, "mimetype");
  475. attachment.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
  476. }
  477. return attachment;
  478. }
  479. /// <summary>
  480. /// Converts ffprobe stream info to our MediaStream class.
  481. /// </summary>
  482. /// <param name="isAudio">if set to <c>true</c> [is info].</param>
  483. /// <param name="streamInfo">The stream info.</param>
  484. /// <param name="formatInfo">The format info.</param>
  485. /// <returns>MediaStream.</returns>
  486. private MediaStream GetMediaStream(bool isAudio, MediaStreamInfo streamInfo, MediaFormatInfo formatInfo)
  487. {
  488. // These are mp4 chapters
  489. if (string.Equals(streamInfo.CodecName, "mov_text", StringComparison.OrdinalIgnoreCase))
  490. {
  491. // Edit: but these are also sometimes subtitles?
  492. // return null;
  493. }
  494. var stream = new MediaStream
  495. {
  496. Codec = streamInfo.CodecName,
  497. Profile = streamInfo.Profile,
  498. Level = streamInfo.Level,
  499. Index = streamInfo.Index,
  500. PixelFormat = streamInfo.PixelFormat,
  501. NalLengthSize = streamInfo.NalLengthSize,
  502. TimeBase = streamInfo.TimeBase,
  503. CodecTimeBase = streamInfo.CodecTimeBase
  504. };
  505. if (string.Equals(streamInfo.IsAvc, "true", StringComparison.OrdinalIgnoreCase) ||
  506. string.Equals(streamInfo.IsAvc, "1", StringComparison.OrdinalIgnoreCase))
  507. {
  508. stream.IsAVC = true;
  509. }
  510. else if (string.Equals(streamInfo.IsAvc, "false", StringComparison.OrdinalIgnoreCase) ||
  511. string.Equals(streamInfo.IsAvc, "0", StringComparison.OrdinalIgnoreCase))
  512. {
  513. stream.IsAVC = false;
  514. }
  515. if (!string.IsNullOrWhiteSpace(streamInfo.FieldOrder) && !string.Equals(streamInfo.FieldOrder, "progressive", StringComparison.OrdinalIgnoreCase))
  516. {
  517. stream.IsInterlaced = true;
  518. }
  519. // Filter out junk
  520. if (!string.IsNullOrWhiteSpace(streamInfo.CodecTagString) && streamInfo.CodecTagString.IndexOf("[0]", StringComparison.OrdinalIgnoreCase) == -1)
  521. {
  522. stream.CodecTag = streamInfo.CodecTagString;
  523. }
  524. if (streamInfo.Tags != null)
  525. {
  526. stream.Language = GetDictionaryValue(streamInfo.Tags, "language");
  527. stream.Comment = GetDictionaryValue(streamInfo.Tags, "comment");
  528. stream.Title = GetDictionaryValue(streamInfo.Tags, "title");
  529. }
  530. if (string.Equals(streamInfo.CodecType, "audio", StringComparison.OrdinalIgnoreCase))
  531. {
  532. stream.Type = MediaStreamType.Audio;
  533. stream.Channels = streamInfo.Channels;
  534. if (!string.IsNullOrEmpty(streamInfo.SampleRate))
  535. {
  536. if (int.TryParse(streamInfo.SampleRate, NumberStyles.Any, _usCulture, out var value))
  537. {
  538. stream.SampleRate = value;
  539. }
  540. }
  541. stream.ChannelLayout = ParseChannelLayout(streamInfo.ChannelLayout);
  542. if (streamInfo.BitsPerSample > 0)
  543. {
  544. stream.BitDepth = streamInfo.BitsPerSample;
  545. }
  546. else if (streamInfo.BitsPerRawSample > 0)
  547. {
  548. stream.BitDepth = streamInfo.BitsPerRawSample;
  549. }
  550. }
  551. else if (string.Equals(streamInfo.CodecType, "subtitle", StringComparison.OrdinalIgnoreCase))
  552. {
  553. stream.Type = MediaStreamType.Subtitle;
  554. stream.Codec = NormalizeSubtitleCodec(stream.Codec);
  555. stream.localizedUndefined = _localization.GetLocalizedString("Undefined");
  556. stream.localizedDefault = _localization.GetLocalizedString("Default");
  557. stream.localizedForced = _localization.GetLocalizedString("Forced");
  558. }
  559. else if (string.Equals(streamInfo.CodecType, "video", StringComparison.OrdinalIgnoreCase))
  560. {
  561. stream.Type = isAudio || string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) || string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase)
  562. ? MediaStreamType.EmbeddedImage
  563. : MediaStreamType.Video;
  564. stream.AverageFrameRate = GetFrameRate(streamInfo.AverageFrameRate);
  565. stream.RealFrameRate = GetFrameRate(streamInfo.RFrameRate);
  566. if (isAudio || string.Equals(stream.Codec, "gif", StringComparison.OrdinalIgnoreCase) ||
  567. string.Equals(stream.Codec, "png", StringComparison.OrdinalIgnoreCase))
  568. {
  569. stream.Type = MediaStreamType.EmbeddedImage;
  570. }
  571. else if (string.Equals(stream.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  572. {
  573. // How to differentiate between video and embedded image?
  574. // The only difference I've seen thus far is presence of codec tag, also embedded images have high (unusual) framerates
  575. if (!string.IsNullOrWhiteSpace(stream.CodecTag))
  576. {
  577. stream.Type = MediaStreamType.Video;
  578. }
  579. else
  580. {
  581. stream.Type = MediaStreamType.EmbeddedImage;
  582. }
  583. }
  584. else
  585. {
  586. stream.Type = MediaStreamType.Video;
  587. }
  588. stream.Width = streamInfo.Width;
  589. stream.Height = streamInfo.Height;
  590. stream.AspectRatio = GetAspectRatio(streamInfo);
  591. if (streamInfo.BitsPerSample > 0)
  592. {
  593. stream.BitDepth = streamInfo.BitsPerSample;
  594. }
  595. else if (streamInfo.BitsPerRawSample > 0)
  596. {
  597. stream.BitDepth = streamInfo.BitsPerRawSample;
  598. }
  599. // stream.IsAnamorphic = string.Equals(streamInfo.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase) ||
  600. // string.Equals(stream.AspectRatio, "2.35:1", StringComparison.OrdinalIgnoreCase) ||
  601. // string.Equals(stream.AspectRatio, "2.40:1", StringComparison.OrdinalIgnoreCase);
  602. // http://stackoverflow.com/questions/17353387/how-to-detect-anamorphic-video-with-ffprobe
  603. stream.IsAnamorphic = string.Equals(streamInfo.SampleAspectRatio, "0:1", StringComparison.OrdinalIgnoreCase);
  604. if (streamInfo.Refs > 0)
  605. {
  606. stream.RefFrames = streamInfo.Refs;
  607. }
  608. if (!string.IsNullOrEmpty(streamInfo.ColorRange))
  609. {
  610. stream.ColorRange = streamInfo.ColorRange;
  611. }
  612. if (!string.IsNullOrEmpty(streamInfo.ColorSpace))
  613. {
  614. stream.ColorSpace = streamInfo.ColorSpace;
  615. }
  616. if (!string.IsNullOrEmpty(streamInfo.ColorTransfer))
  617. {
  618. stream.ColorTransfer = streamInfo.ColorTransfer;
  619. }
  620. if (!string.IsNullOrEmpty(streamInfo.ColorPrimaries))
  621. {
  622. stream.ColorPrimaries = streamInfo.ColorPrimaries;
  623. }
  624. }
  625. else
  626. {
  627. return null;
  628. }
  629. // Get stream bitrate
  630. var bitrate = 0;
  631. if (!string.IsNullOrEmpty(streamInfo.BitRate))
  632. {
  633. if (int.TryParse(streamInfo.BitRate, NumberStyles.Any, _usCulture, out var value))
  634. {
  635. bitrate = value;
  636. }
  637. }
  638. if (bitrate == 0 && formatInfo != null && !string.IsNullOrEmpty(formatInfo.BitRate) && stream.Type == MediaStreamType.Video)
  639. {
  640. // If the stream info doesn't have a bitrate get the value from the media format info
  641. if (int.TryParse(formatInfo.BitRate, NumberStyles.Any, _usCulture, out var value))
  642. {
  643. bitrate = value;
  644. }
  645. }
  646. if (bitrate > 0)
  647. {
  648. stream.BitRate = bitrate;
  649. }
  650. var disposition = streamInfo.Disposition;
  651. if (disposition != null)
  652. {
  653. if (disposition.GetValueOrDefault("default") == 1)
  654. {
  655. stream.IsDefault = true;
  656. }
  657. if (disposition.GetValueOrDefault("forced") == 1)
  658. {
  659. stream.IsForced = true;
  660. }
  661. }
  662. NormalizeStreamTitle(stream);
  663. return stream;
  664. }
  665. private void NormalizeStreamTitle(MediaStream stream)
  666. {
  667. if (string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase))
  668. {
  669. stream.Title = null;
  670. }
  671. if (stream.Type == MediaStreamType.EmbeddedImage)
  672. {
  673. stream.Title = null;
  674. }
  675. }
  676. /// <summary>
  677. /// Gets a string from an FFProbeResult tags dictionary.
  678. /// </summary>
  679. /// <param name="tags">The tags.</param>
  680. /// <param name="key">The key.</param>
  681. /// <returns>System.String.</returns>
  682. private string GetDictionaryValue(IReadOnlyDictionary<string, string> tags, string key)
  683. {
  684. if (tags == null)
  685. {
  686. return null;
  687. }
  688. tags.TryGetValue(key, out var val);
  689. return val;
  690. }
  691. private string ParseChannelLayout(string input)
  692. {
  693. if (string.IsNullOrEmpty(input))
  694. {
  695. return input;
  696. }
  697. return input.Split('(').FirstOrDefault();
  698. }
  699. private string GetAspectRatio(MediaStreamInfo info)
  700. {
  701. var original = info.DisplayAspectRatio;
  702. var parts = (original ?? string.Empty).Split(':');
  703. if (!(parts.Length == 2 &&
  704. int.TryParse(parts[0], NumberStyles.Any, _usCulture, out var width) &&
  705. int.TryParse(parts[1], NumberStyles.Any, _usCulture, out var height) &&
  706. width > 0 &&
  707. height > 0))
  708. {
  709. width = info.Width;
  710. height = info.Height;
  711. }
  712. if (width > 0 && height > 0)
  713. {
  714. double ratio = width;
  715. ratio /= height;
  716. if (IsClose(ratio, 1.777777778, .03))
  717. {
  718. return "16:9";
  719. }
  720. if (IsClose(ratio, 1.3333333333, .05))
  721. {
  722. return "4:3";
  723. }
  724. if (IsClose(ratio, 1.41))
  725. {
  726. return "1.41:1";
  727. }
  728. if (IsClose(ratio, 1.5))
  729. {
  730. return "1.5:1";
  731. }
  732. if (IsClose(ratio, 1.6))
  733. {
  734. return "1.6:1";
  735. }
  736. if (IsClose(ratio, 1.66666666667))
  737. {
  738. return "5:3";
  739. }
  740. if (IsClose(ratio, 1.85, .02))
  741. {
  742. return "1.85:1";
  743. }
  744. if (IsClose(ratio, 2.35, .025))
  745. {
  746. return "2.35:1";
  747. }
  748. if (IsClose(ratio, 2.4, .025))
  749. {
  750. return "2.40:1";
  751. }
  752. }
  753. return original;
  754. }
  755. private bool IsClose(double d1, double d2, double variance = .005)
  756. {
  757. return Math.Abs(d1 - d2) <= variance;
  758. }
  759. /// <summary>
  760. /// Gets a frame rate from a string value in ffprobe output
  761. /// This could be a number or in the format of 2997/125.
  762. /// </summary>
  763. /// <param name="value">The value.</param>
  764. /// <returns>System.Nullable{System.Single}.</returns>
  765. private float? GetFrameRate(string value)
  766. {
  767. if (!string.IsNullOrEmpty(value))
  768. {
  769. var parts = value.Split('/');
  770. float result;
  771. if (parts.Length == 2)
  772. {
  773. result = float.Parse(parts[0], _usCulture) / float.Parse(parts[1], _usCulture);
  774. }
  775. else
  776. {
  777. result = float.Parse(parts[0], _usCulture);
  778. }
  779. return float.IsNaN(result) ? (float?)null : result;
  780. }
  781. return null;
  782. }
  783. private void SetAudioRuntimeTicks(InternalMediaInfoResult result, MediaInfo data)
  784. {
  785. if (result.Streams != null)
  786. {
  787. // Get the first info stream
  788. var stream = result.Streams.FirstOrDefault(s => string.Equals(s.CodecType, "audio", StringComparison.OrdinalIgnoreCase));
  789. if (stream != null)
  790. {
  791. // Get duration from stream properties
  792. var duration = stream.Duration;
  793. // If it's not there go into format properties
  794. if (string.IsNullOrEmpty(duration))
  795. {
  796. duration = result.Format.Duration;
  797. }
  798. // If we got something, parse it
  799. if (!string.IsNullOrEmpty(duration))
  800. {
  801. data.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(duration, _usCulture)).Ticks;
  802. }
  803. }
  804. }
  805. }
  806. private void SetSize(InternalMediaInfoResult data, MediaInfo info)
  807. {
  808. if (data.Format != null)
  809. {
  810. if (!string.IsNullOrEmpty(data.Format.Size))
  811. {
  812. info.Size = long.Parse(data.Format.Size, _usCulture);
  813. }
  814. else
  815. {
  816. info.Size = null;
  817. }
  818. }
  819. }
  820. private void SetAudioInfoFromTags(MediaInfo audio, Dictionary<string, string> tags)
  821. {
  822. var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");
  823. if (!string.IsNullOrWhiteSpace(composer))
  824. {
  825. var peoples = new List<BaseItemPerson>();
  826. foreach (var person in Split(composer, false))
  827. {
  828. peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Composer });
  829. }
  830. audio.People = peoples.ToArray();
  831. }
  832. // var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");
  833. // if (!string.IsNullOrWhiteSpace(conductor))
  834. //{
  835. // foreach (var person in Split(conductor, false))
  836. // {
  837. // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Conductor });
  838. // }
  839. //}
  840. // var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");
  841. // if (!string.IsNullOrWhiteSpace(lyricist))
  842. //{
  843. // foreach (var person in Split(lyricist, false))
  844. // {
  845. // audio.People.Add(new BaseItemPerson { Name = person, Type = PersonType.Lyricist });
  846. // }
  847. //}
  848. // Check for writer some music is tagged that way as alternative to composer/lyricist
  849. var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");
  850. if (!string.IsNullOrWhiteSpace(writer))
  851. {
  852. var peoples = new List<BaseItemPerson>();
  853. foreach (var person in Split(writer, false))
  854. {
  855. peoples.Add(new BaseItemPerson { Name = person, Type = PersonType.Writer });
  856. }
  857. audio.People = peoples.ToArray();
  858. }
  859. audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");
  860. var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");
  861. if (!string.IsNullOrWhiteSpace(artists))
  862. {
  863. audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
  864. .DistinctNames()
  865. .ToArray();
  866. }
  867. else
  868. {
  869. var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
  870. if (string.IsNullOrWhiteSpace(artist))
  871. {
  872. audio.Artists = Array.Empty<string>();
  873. }
  874. else
  875. {
  876. audio.Artists = SplitArtists(artist, _nameDelimiters, true)
  877. .DistinctNames()
  878. .ToArray();
  879. }
  880. }
  881. var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");
  882. if (string.IsNullOrWhiteSpace(albumArtist))
  883. {
  884. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
  885. }
  886. if (string.IsNullOrWhiteSpace(albumArtist))
  887. {
  888. albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
  889. }
  890. if (string.IsNullOrWhiteSpace(albumArtist))
  891. {
  892. audio.AlbumArtists = Array.Empty<string>();
  893. }
  894. else
  895. {
  896. audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
  897. .DistinctNames()
  898. .ToArray();
  899. }
  900. if (audio.AlbumArtists.Length == 0)
  901. {
  902. audio.AlbumArtists = audio.Artists;
  903. }
  904. // Track number
  905. audio.IndexNumber = GetDictionaryDiscValue(tags, "track");
  906. // Disc number
  907. audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");
  908. // If we don't have a ProductionYear try and get it from PremiereDate
  909. if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
  910. {
  911. audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
  912. }
  913. // There's several values in tags may or may not be present
  914. FetchStudios(audio, tags, "organization");
  915. FetchStudios(audio, tags, "ensemble");
  916. FetchStudios(audio, tags, "publisher");
  917. FetchStudios(audio, tags, "label");
  918. // These support mulitple values, but for now we only store the first.
  919. var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));
  920. if (mb == null)
  921. {
  922. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
  923. }
  924. audio.SetProviderId(MetadataProvider.MusicBrainzAlbumArtist, mb);
  925. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
  926. if (mb == null)
  927. {
  928. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
  929. }
  930. audio.SetProviderId(MetadataProvider.MusicBrainzArtist, mb);
  931. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
  932. if (mb == null)
  933. {
  934. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
  935. }
  936. audio.SetProviderId(MetadataProvider.MusicBrainzAlbum, mb);
  937. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
  938. if (mb == null)
  939. {
  940. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
  941. }
  942. audio.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, mb);
  943. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
  944. if (mb == null)
  945. {
  946. mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
  947. }
  948. audio.SetProviderId(MetadataProvider.MusicBrainzTrack, mb);
  949. }
  950. private string GetMultipleMusicBrainzId(string value)
  951. {
  952. if (string.IsNullOrWhiteSpace(value))
  953. {
  954. return null;
  955. }
  956. return value.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
  957. .Select(i => i.Trim())
  958. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  959. }
  960. private readonly char[] _nameDelimiters = { '/', '|', ';', '\\' };
  961. /// <summary>
  962. /// Splits the specified val.
  963. /// </summary>
  964. /// <param name="val">The val.</param>
  965. /// <param name="allowCommaDelimiter">if set to <c>true</c> [allow comma delimiter].</param>
  966. /// <returns>System.String[][].</returns>
  967. private IEnumerable<string> Split(string val, bool allowCommaDelimiter)
  968. {
  969. // Only use the comma as a delimeter if there are no slashes or pipes.
  970. // We want to be careful not to split names that have commas in them
  971. var delimeter = !allowCommaDelimiter || _nameDelimiters.Any(i => val.IndexOf(i) != -1) ?
  972. _nameDelimiters :
  973. new[] { ',' };
  974. return val.Split(delimeter, StringSplitOptions.RemoveEmptyEntries)
  975. .Where(i => !string.IsNullOrWhiteSpace(i))
  976. .Select(i => i.Trim());
  977. }
  978. private const string ArtistReplaceValue = " | ";
  979. private IEnumerable<string> SplitArtists(string val, char[] delimiters, bool splitFeaturing)
  980. {
  981. if (splitFeaturing)
  982. {
  983. val = val.Replace(" featuring ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase)
  984. .Replace(" feat. ", ArtistReplaceValue, StringComparison.OrdinalIgnoreCase);
  985. }
  986. var artistsFound = new List<string>();
  987. foreach (var whitelistArtist in GetSplitWhitelist())
  988. {
  989. var originalVal = val;
  990. val = val.Replace(whitelistArtist, "|", StringComparison.OrdinalIgnoreCase);
  991. if (!string.Equals(originalVal, val, StringComparison.OrdinalIgnoreCase))
  992. {
  993. artistsFound.Add(whitelistArtist);
  994. }
  995. }
  996. var artists = val.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
  997. .Where(i => !string.IsNullOrWhiteSpace(i))
  998. .Select(i => i.Trim());
  999. artistsFound.AddRange(artists);
  1000. return artistsFound;
  1001. }
  1002. private List<string> _splitWhiteList = null;
  1003. private IEnumerable<string> GetSplitWhitelist()
  1004. {
  1005. if (_splitWhiteList == null)
  1006. {
  1007. _splitWhiteList = new List<string>
  1008. {
  1009. "AC/DC"
  1010. };
  1011. }
  1012. return _splitWhiteList;
  1013. }
  1014. /// <summary>
  1015. /// Gets the studios from the tags collection.
  1016. /// </summary>
  1017. /// <param name="info">The info.</param>
  1018. /// <param name="tags">The tags.</param>
  1019. /// <param name="tagName">Name of the tag.</param>
  1020. private void FetchStudios(MediaInfo info, Dictionary<string, string> tags, string tagName)
  1021. {
  1022. var val = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  1023. if (!string.IsNullOrEmpty(val))
  1024. {
  1025. var studios = Split(val, true);
  1026. var studioList = new List<string>();
  1027. foreach (var studio in studios)
  1028. {
  1029. // Sometimes the artist name is listed here, account for that
  1030. if (info.Artists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  1031. {
  1032. continue;
  1033. }
  1034. if (info.AlbumArtists.Contains(studio, StringComparer.OrdinalIgnoreCase))
  1035. {
  1036. continue;
  1037. }
  1038. studioList.Add(studio);
  1039. }
  1040. info.Studios = studioList
  1041. .Where(i => !string.IsNullOrWhiteSpace(i))
  1042. .Distinct(StringComparer.OrdinalIgnoreCase)
  1043. .ToArray();
  1044. }
  1045. }
  1046. /// <summary>
  1047. /// Gets the genres from the tags collection.
  1048. /// </summary>
  1049. /// <param name="info">The information.</param>
  1050. /// <param name="tags">The tags.</param>
  1051. private void FetchGenres(MediaInfo info, Dictionary<string, string> tags)
  1052. {
  1053. var val = FFProbeHelpers.GetDictionaryValue(tags, "genre");
  1054. if (!string.IsNullOrEmpty(val))
  1055. {
  1056. var genres = new List<string>(info.Genres);
  1057. foreach (var genre in Split(val, true))
  1058. {
  1059. genres.Add(genre);
  1060. }
  1061. info.Genres = genres
  1062. .Where(i => !string.IsNullOrWhiteSpace(i))
  1063. .Distinct(StringComparer.OrdinalIgnoreCase)
  1064. .ToArray();
  1065. }
  1066. }
  1067. /// <summary>
  1068. /// Gets the disc number, which is sometimes can be in the form of '1', or '1/3'
  1069. /// </summary>
  1070. /// <param name="tags">The tags.</param>
  1071. /// <param name="tagName">Name of the tag.</param>
  1072. /// <returns>System.Nullable{System.Int32}.</returns>
  1073. private int? GetDictionaryDiscValue(Dictionary<string, string> tags, string tagName)
  1074. {
  1075. var disc = FFProbeHelpers.GetDictionaryValue(tags, tagName);
  1076. if (!string.IsNullOrEmpty(disc))
  1077. {
  1078. disc = disc.Split('/')[0];
  1079. if (int.TryParse(disc, out var num))
  1080. {
  1081. return num;
  1082. }
  1083. }
  1084. return null;
  1085. }
  1086. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  1087. {
  1088. var info = new ChapterInfo();
  1089. if (chapter.Tags != null)
  1090. {
  1091. if (chapter.Tags.TryGetValue("title", out string name))
  1092. {
  1093. info.Name = name;
  1094. }
  1095. }
  1096. // Limit accuracy to milliseconds to match xml saving
  1097. var secondsString = chapter.StartTime;
  1098. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out var seconds))
  1099. {
  1100. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  1101. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  1102. }
  1103. return info;
  1104. }
  1105. private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)
  1106. private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
  1107. {
  1108. if (data.Format == null || data.Format.Tags == null)
  1109. {
  1110. return;
  1111. }
  1112. var genres = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/Genre");
  1113. if (!string.IsNullOrWhiteSpace(genres))
  1114. {
  1115. var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  1116. .Where(i => !string.IsNullOrWhiteSpace(i))
  1117. .Select(i => i.Trim())
  1118. .ToList();
  1119. // If this is empty then don't overwrite genres that might have been fetched earlier
  1120. if (genreList.Count > 0)
  1121. {
  1122. video.Genres = genreList.ToArray();
  1123. }
  1124. }
  1125. var officialRating = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/ParentalRating");
  1126. if (!string.IsNullOrWhiteSpace(officialRating))
  1127. {
  1128. video.OfficialRating = officialRating;
  1129. }
  1130. var people = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/MediaCredits");
  1131. if (!string.IsNullOrEmpty(people))
  1132. {
  1133. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  1134. .Where(i => !string.IsNullOrWhiteSpace(i))
  1135. .Select(i => new BaseItemPerson { Name = i.Trim(), Type = PersonType.Actor })
  1136. .ToArray();
  1137. }
  1138. var year = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/OriginalReleaseTime");
  1139. if (!string.IsNullOrWhiteSpace(year))
  1140. {
  1141. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out var val))
  1142. {
  1143. video.ProductionYear = val;
  1144. }
  1145. }
  1146. var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/MediaOriginalBroadcastDateTime");
  1147. if (!string.IsNullOrWhiteSpace(premiereDateString))
  1148. {
  1149. // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1150. // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
  1151. if (DateTime.TryParse(year, null, DateTimeStyles.None, out var val))
  1152. {
  1153. video.PremiereDate = val.ToUniversalTime();
  1154. }
  1155. }
  1156. var description = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/SubTitleDescription");
  1157. var subTitle = FFProbeHelpers.GetDictionaryValue(data.Format.Tags, "WM/SubTitle");
  1158. // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
  1159. // 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
  1160. // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
  1161. // OR -> COMMENT. SUBTITLE: DESCRIPTION
  1162. // 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]
  1163. // 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]
  1164. 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
  1165. {
  1166. string[] parts = description.Split(':');
  1167. if (parts.Length > 0)
  1168. {
  1169. string subtitle = parts[0];
  1170. try
  1171. {
  1172. if (subtitle.Contains("/")) // It contains a episode number and season number
  1173. {
  1174. string[] numbers = subtitle.Split(' ');
  1175. video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
  1176. int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);
  1177. description = string.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
  1178. }
  1179. else
  1180. {
  1181. throw new Exception(); // Switch to default parsing
  1182. }
  1183. }
  1184. catch // Default parsing
  1185. {
  1186. if (subtitle.Contains(".")) // skip the comment, keep the subtitle
  1187. description = string.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
  1188. else
  1189. {
  1190. description = subtitle.Trim(); // Clean up whitespaces and save it
  1191. }
  1192. }
  1193. }
  1194. }
  1195. if (!string.IsNullOrWhiteSpace(description))
  1196. {
  1197. video.Overview = description;
  1198. }
  1199. }
  1200. private void ExtractTimestamp(MediaInfo video)
  1201. {
  1202. if (video.VideoType == VideoType.VideoFile)
  1203. {
  1204. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  1205. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  1206. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  1207. {
  1208. try
  1209. {
  1210. video.Timestamp = GetMpegTimestamp(video.Path);
  1211. _logger.LogDebug("Video has {Timestamp} timestamp", video.Timestamp);
  1212. }
  1213. catch (Exception ex)
  1214. {
  1215. _logger.LogError(ex, "Error extracting timestamp info from {Path}", video.Path);
  1216. video.Timestamp = null;
  1217. }
  1218. }
  1219. }
  1220. }
  1221. // REVIEW: find out why the byte array needs to be 197 bytes long and comment the reason
  1222. private TransportStreamTimestamp GetMpegTimestamp(string path)
  1223. {
  1224. var packetBuffer = new byte[197];
  1225. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  1226. {
  1227. fs.Read(packetBuffer);
  1228. }
  1229. if (packetBuffer[0] == 71)
  1230. {
  1231. return TransportStreamTimestamp.None;
  1232. }
  1233. if ((packetBuffer[4] == 71) && (packetBuffer[196] == 71))
  1234. {
  1235. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  1236. {
  1237. return TransportStreamTimestamp.Zero;
  1238. }
  1239. return TransportStreamTimestamp.Valid;
  1240. }
  1241. return TransportStreamTimestamp.None;
  1242. }
  1243. }
  1244. }