ProbeResultNormalizer.cs 51 KB

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