FFProbeVideoInfo.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. using DvdLib.Ifo;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Localization;
  8. using MediaBrowser.Controller.MediaEncoding;
  9. using MediaBrowser.Controller.Persistence;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Model.MediaInfo;
  15. using MediaBrowser.Model.Serialization;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. namespace MediaBrowser.Providers.MediaInfo
  24. {
  25. public class FFProbeVideoInfo
  26. {
  27. private readonly ILogger _logger;
  28. private readonly IIsoManager _isoManager;
  29. private readonly IMediaEncoder _mediaEncoder;
  30. private readonly IItemRepository _itemRepo;
  31. private readonly IBlurayExaminer _blurayExaminer;
  32. private readonly ILocalizationManager _localization;
  33. private readonly IApplicationPaths _appPaths;
  34. private readonly IJsonSerializer _json;
  35. private readonly IEncodingManager _encodingManager;
  36. private readonly IFileSystem _fileSystem;
  37. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  38. public FFProbeVideoInfo(ILogger logger, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IBlurayExaminer blurayExaminer, ILocalizationManager localization, IApplicationPaths appPaths, IJsonSerializer json, IEncodingManager encodingManager, IFileSystem fileSystem)
  39. {
  40. _logger = logger;
  41. _isoManager = isoManager;
  42. _mediaEncoder = mediaEncoder;
  43. _itemRepo = itemRepo;
  44. _blurayExaminer = blurayExaminer;
  45. _localization = localization;
  46. _appPaths = appPaths;
  47. _json = json;
  48. _encodingManager = encodingManager;
  49. _fileSystem = fileSystem;
  50. }
  51. public async Task<ItemUpdateType> ProbeVideo<T>(T item, IDirectoryService directoryService, CancellationToken cancellationToken)
  52. where T : Video
  53. {
  54. var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
  55. BlurayDiscInfo blurayDiscInfo = null;
  56. try
  57. {
  58. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  59. {
  60. var inputPath = isoMount != null ? isoMount.MountedPath : item.Path;
  61. blurayDiscInfo = GetBDInfo(inputPath);
  62. }
  63. OnPreFetch(item, isoMount, blurayDiscInfo);
  64. // If we didn't find any satisfying the min length, just take them all
  65. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  66. {
  67. if (item.PlayableStreamFileNames.Count == 0)
  68. {
  69. _logger.Error("No playable vobs found in dvd structure, skipping ffprobe.");
  70. return ItemUpdateType.MetadataImport;
  71. }
  72. }
  73. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  74. {
  75. if (item.PlayableStreamFileNames.Count == 0)
  76. {
  77. _logger.Error("No playable vobs found in bluray structure, skipping ffprobe.");
  78. return ItemUpdateType.MetadataImport;
  79. }
  80. }
  81. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  82. cancellationToken.ThrowIfCancellationRequested();
  83. FFProbeHelpers.NormalizeFFProbeResult(result);
  84. cancellationToken.ThrowIfCancellationRequested();
  85. await Fetch(item, cancellationToken, result, isoMount, blurayDiscInfo, directoryService).ConfigureAwait(false);
  86. }
  87. finally
  88. {
  89. if (isoMount != null)
  90. {
  91. isoMount.Dispose();
  92. }
  93. }
  94. return ItemUpdateType.MetadataImport;
  95. }
  96. private const string SchemaVersion = "1";
  97. private async Task<InternalMediaInfoResult> GetMediaInfo(BaseItem item, IIsoMount isoMount, CancellationToken cancellationToken)
  98. {
  99. cancellationToken.ThrowIfCancellationRequested();
  100. var idString = item.Id.ToString("N");
  101. var cachePath = Path.Combine(_appPaths.CachePath,
  102. "ffprobe-video",
  103. idString.Substring(0, 2), idString, "v" + SchemaVersion + _mediaEncoder.Version + item.DateModified.Ticks.ToString(_usCulture) + ".json");
  104. try
  105. {
  106. return _json.DeserializeFromFile<InternalMediaInfoResult>(cachePath);
  107. }
  108. catch (FileNotFoundException)
  109. {
  110. }
  111. catch (DirectoryNotFoundException)
  112. {
  113. }
  114. var type = InputType.File;
  115. var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath };
  116. var video = item as Video;
  117. if (video != null)
  118. {
  119. inputPath = MediaEncoderHelpers.GetInputArgument(video.Path, video.LocationType == LocationType.Remote, video.VideoType, video.IsoType, isoMount, video.PlayableStreamFileNames, out type);
  120. }
  121. var result = await _mediaEncoder.GetMediaInfo(inputPath, type, false, cancellationToken).ConfigureAwait(false);
  122. Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
  123. _json.SerializeToFile(result, cachePath);
  124. return result;
  125. }
  126. protected async Task Fetch(Video video, CancellationToken cancellationToken, InternalMediaInfoResult data, IIsoMount isoMount, BlurayDiscInfo blurayInfo, IDirectoryService directoryService)
  127. {
  128. var mediaInfo = MediaEncoderHelpers.GetMediaInfo(data);
  129. var mediaStreams = mediaInfo.MediaStreams;
  130. video.TotalBitrate = mediaInfo.TotalBitrate;
  131. video.FormatName = (mediaInfo.Format ?? string.Empty)
  132. .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
  133. if (data.format != null)
  134. {
  135. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  136. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  137. if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
  138. {
  139. video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
  140. }
  141. if (video.VideoType == VideoType.VideoFile)
  142. {
  143. var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');
  144. video.Container = extension;
  145. }
  146. else
  147. {
  148. video.Container = null;
  149. }
  150. if (!string.IsNullOrEmpty(data.format.size))
  151. {
  152. video.Size = long.Parse(data.format.size, _usCulture);
  153. }
  154. else
  155. {
  156. video.Size = null;
  157. }
  158. }
  159. var mediaChapters = (data.Chapters ?? new MediaChapter[] { }).ToList();
  160. var chapters = mediaChapters.Select(GetChapterInfo).ToList();
  161. if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
  162. {
  163. FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
  164. }
  165. AddExternalSubtitles(video, mediaStreams, directoryService);
  166. FetchWtvInfo(video, data);
  167. video.IsHD = mediaStreams.Any(i => i.Type == MediaStreamType.Video && i.Width.HasValue && i.Width.Value >= 1270);
  168. if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
  169. {
  170. AddDummyChapters(video, chapters);
  171. }
  172. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  173. video.VideoBitRate = videoStream == null ? null : videoStream.BitRate;
  174. video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;
  175. video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
  176. ExtractTimestamp(video);
  177. await _encodingManager.RefreshChapterImages(new ChapterImageRefreshOptions
  178. {
  179. Chapters = chapters,
  180. Video = video,
  181. ExtractImages = false,
  182. SaveChapters = false
  183. }, cancellationToken).ConfigureAwait(false);
  184. await _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken).ConfigureAwait(false);
  185. await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false);
  186. }
  187. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  188. {
  189. var info = new ChapterInfo();
  190. if (chapter.tags != null)
  191. {
  192. string name;
  193. if (chapter.tags.TryGetValue("title", out name))
  194. {
  195. info.Name = name;
  196. }
  197. }
  198. info.StartPositionTicks = chapter.start/100;
  199. return info;
  200. }
  201. private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
  202. {
  203. var video = (Video)item;
  204. int? currentHeight = null;
  205. int? currentWidth = null;
  206. int? currentBitRate = null;
  207. var videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  208. // Grab the values that ffprobe recorded
  209. if (videoStream != null)
  210. {
  211. currentBitRate = videoStream.BitRate;
  212. currentWidth = videoStream.Width;
  213. currentHeight = videoStream.Height;
  214. }
  215. // Fill video properties from the BDInfo result
  216. mediaStreams.Clear();
  217. mediaStreams.AddRange(blurayInfo.MediaStreams);
  218. video.MainFeaturePlaylistName = blurayInfo.PlaylistName;
  219. if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
  220. {
  221. video.RunTimeTicks = blurayInfo.RunTimeTicks;
  222. }
  223. video.PlayableStreamFileNames = blurayInfo.Files.ToList();
  224. if (blurayInfo.Chapters != null)
  225. {
  226. chapters.Clear();
  227. chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
  228. {
  229. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  230. }));
  231. }
  232. videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  233. // Use the ffprobe values if these are empty
  234. if (videoStream != null)
  235. {
  236. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  237. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  238. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  239. }
  240. }
  241. private bool IsEmpty(int? num)
  242. {
  243. return !num.HasValue || num.Value == 0;
  244. }
  245. /// <summary>
  246. /// Gets information about the longest playlist on a bdrom
  247. /// </summary>
  248. /// <param name="path">The path.</param>
  249. /// <returns>VideoStream.</returns>
  250. private BlurayDiscInfo GetBDInfo(string path)
  251. {
  252. return _blurayExaminer.GetDiscInfo(path);
  253. }
  254. private void FetchWtvInfo(Video video, InternalMediaInfoResult data)
  255. {
  256. if (data.format == null || data.format.tags == null)
  257. {
  258. return;
  259. }
  260. if (video.Genres.Count == 0)
  261. {
  262. if (!video.LockedFields.Contains(MetadataFields.Genres))
  263. {
  264. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "genre");
  265. if (!string.IsNullOrEmpty(genres))
  266. {
  267. video.Genres = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  268. .Where(i => !string.IsNullOrWhiteSpace(i))
  269. .Select(i => i.Trim())
  270. .ToList();
  271. }
  272. }
  273. }
  274. if (string.IsNullOrEmpty(video.Overview))
  275. {
  276. if (!video.LockedFields.Contains(MetadataFields.Overview))
  277. {
  278. var overview = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  279. if (!string.IsNullOrWhiteSpace(overview))
  280. {
  281. video.Overview = overview;
  282. }
  283. }
  284. }
  285. if (string.IsNullOrEmpty(video.OfficialRating))
  286. {
  287. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  288. if (!string.IsNullOrWhiteSpace(officialRating))
  289. {
  290. if (!video.LockedFields.Contains(MetadataFields.OfficialRating))
  291. {
  292. video.OfficialRating = officialRating;
  293. }
  294. }
  295. }
  296. if (video.People.Count == 0)
  297. {
  298. if (!video.LockedFields.Contains(MetadataFields.Cast))
  299. {
  300. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  301. if (!string.IsNullOrEmpty(people))
  302. {
  303. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  304. .Where(i => !string.IsNullOrWhiteSpace(i))
  305. .Select(i => new PersonInfo { Name = i.Trim(), Type = PersonType.Actor })
  306. .ToList();
  307. }
  308. }
  309. }
  310. if (!video.ProductionYear.HasValue)
  311. {
  312. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  313. if (!string.IsNullOrWhiteSpace(year))
  314. {
  315. int val;
  316. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  317. {
  318. video.ProductionYear = val;
  319. }
  320. }
  321. }
  322. }
  323. private IEnumerable<string> SubtitleExtensions
  324. {
  325. get
  326. {
  327. return new[] { ".srt", ".ssa", ".ass" };
  328. }
  329. }
  330. public IEnumerable<FileSystemInfo> GetSubtitleFiles(Video video, IDirectoryService directoryService)
  331. {
  332. var containingPath = video.ContainingFolderPath;
  333. if (string.IsNullOrEmpty(containingPath))
  334. {
  335. throw new ArgumentException(string.Format("Cannot search for items that don't have a path: {0} {1}", video.Name, video.Id));
  336. }
  337. var files = directoryService.GetFiles(containingPath);
  338. var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(video.Path);
  339. return files.Where(i =>
  340. {
  341. if (!i.Attributes.HasFlag(FileAttributes.Directory) &&
  342. SubtitleExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
  343. {
  344. var fullName = i.FullName;
  345. var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);
  346. if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
  347. {
  348. return true;
  349. }
  350. if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
  351. {
  352. return true;
  353. }
  354. }
  355. return false;
  356. });
  357. }
  358. /// <summary>
  359. /// Adds the external subtitles.
  360. /// </summary>
  361. /// <param name="video">The video.</param>
  362. /// <param name="currentStreams">The current streams.</param>
  363. private void AddExternalSubtitles(Video video, List<MediaStream> currentStreams, IDirectoryService directoryService)
  364. {
  365. var files = GetSubtitleFiles(video, directoryService);
  366. var startIndex = currentStreams.Count;
  367. var streams = new List<MediaStream>();
  368. var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(video.Path);
  369. foreach (var file in files)
  370. {
  371. var fullName = file.FullName;
  372. var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);
  373. // If the subtitle file matches the video file name
  374. if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
  375. {
  376. streams.Add(new MediaStream
  377. {
  378. Index = startIndex++,
  379. Type = MediaStreamType.Subtitle,
  380. IsExternal = true,
  381. Path = fullName,
  382. Codec = Path.GetExtension(fullName).ToLower().TrimStart('.')
  383. });
  384. }
  385. else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
  386. {
  387. // Support xbmc naming conventions - 300.spanish.srt
  388. var language = fileNameWithoutExtension.Split('.').LastOrDefault();
  389. // Try to translate to three character code
  390. // Be flexible and check against both the full and three character versions
  391. var culture = _localization.GetCultures()
  392. .FirstOrDefault(i => string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.ThreeLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase) || string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));
  393. if (culture != null)
  394. {
  395. language = culture.ThreeLetterISOLanguageName;
  396. }
  397. streams.Add(new MediaStream
  398. {
  399. Index = startIndex++,
  400. Type = MediaStreamType.Subtitle,
  401. IsExternal = true,
  402. Path = fullName,
  403. Codec = Path.GetExtension(fullName).ToLower().TrimStart('.'),
  404. Language = language
  405. });
  406. }
  407. }
  408. video.SubtitleFiles = streams.Select(i => i.Path).OrderBy(i => i).ToList();
  409. currentStreams.AddRange(streams);
  410. }
  411. /// <summary>
  412. /// The dummy chapter duration
  413. /// </summary>
  414. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  415. /// <summary>
  416. /// Adds the dummy chapters.
  417. /// </summary>
  418. /// <param name="video">The video.</param>
  419. /// <param name="chapters">The chapters.</param>
  420. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  421. {
  422. var runtime = video.RunTimeTicks ?? 0;
  423. if (runtime < 0)
  424. {
  425. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  426. }
  427. if (runtime < _dummyChapterDuration)
  428. {
  429. return;
  430. }
  431. long currentChapterTicks = 0;
  432. var index = 1;
  433. // Limit to 100 chapters just in case there's some incorrect metadata here
  434. while (currentChapterTicks < runtime && index < 100)
  435. {
  436. chapters.Add(new ChapterInfo
  437. {
  438. Name = "Chapter " + index,
  439. StartPositionTicks = currentChapterTicks
  440. });
  441. index++;
  442. currentChapterTicks += _dummyChapterDuration;
  443. }
  444. }
  445. /// <summary>
  446. /// Called when [pre fetch].
  447. /// </summary>
  448. /// <param name="item">The item.</param>
  449. /// <param name="mount">The mount.</param>
  450. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  451. {
  452. if (item.VideoType == VideoType.Iso)
  453. {
  454. item.IsoType = DetermineIsoType(mount);
  455. }
  456. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  457. {
  458. FetchFromDvdLib(item, mount);
  459. }
  460. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType.Value == IsoType.BluRay))
  461. {
  462. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  463. }
  464. }
  465. private void ExtractTimestamp(Video video)
  466. {
  467. if (video.VideoType == VideoType.VideoFile)
  468. {
  469. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  470. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  471. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  472. {
  473. try
  474. {
  475. video.Timestamp = GetMpegTimestamp(video.Path);
  476. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  477. }
  478. catch (Exception ex)
  479. {
  480. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  481. video.Timestamp = null;
  482. }
  483. }
  484. }
  485. }
  486. private TransportStreamTimestamp GetMpegTimestamp(string path)
  487. {
  488. var packetBuffer = new byte['Å'];
  489. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  490. {
  491. fs.Read(packetBuffer, 0, packetBuffer.Length);
  492. }
  493. if (packetBuffer[0] == 71)
  494. {
  495. return TransportStreamTimestamp.None;
  496. }
  497. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  498. {
  499. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  500. {
  501. return TransportStreamTimestamp.Zero;
  502. }
  503. return TransportStreamTimestamp.Valid;
  504. }
  505. return TransportStreamTimestamp.None;
  506. }
  507. private void FetchFromDvdLib(Video item, IIsoMount mount)
  508. {
  509. var path = mount == null ? item.Path : mount.MountedPath;
  510. var dvd = new Dvd(path);
  511. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  512. byte? titleNumber = null;
  513. if (primaryTitle != null)
  514. {
  515. titleNumber = primaryTitle.VideoTitleSetNumber;
  516. item.RunTimeTicks = GetRuntime(primaryTitle);
  517. }
  518. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  519. .Select(Path.GetFileName)
  520. .ToList();
  521. }
  522. private long GetRuntime(Title title)
  523. {
  524. return title.ProgramChains
  525. .Select(i => (TimeSpan)i.PlaybackTime)
  526. .Select(i => i.Ticks)
  527. .Sum();
  528. }
  529. /// <summary>
  530. /// Mounts the iso if needed.
  531. /// </summary>
  532. /// <param name="item">The item.</param>
  533. /// <param name="cancellationToken">The cancellation token.</param>
  534. /// <returns>IsoMount.</returns>
  535. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  536. {
  537. if (item.VideoType == VideoType.Iso)
  538. {
  539. return _isoManager.Mount(item.Path, cancellationToken);
  540. }
  541. return Task.FromResult<IIsoMount>(null);
  542. }
  543. /// <summary>
  544. /// Determines the type of the iso.
  545. /// </summary>
  546. /// <param name="isoMount">The iso mount.</param>
  547. /// <returns>System.Nullable{IsoType}.</returns>
  548. private IsoType? DetermineIsoType(IIsoMount isoMount)
  549. {
  550. var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  551. if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
  552. {
  553. return IsoType.Dvd;
  554. }
  555. if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  556. {
  557. return IsoType.BluRay;
  558. }
  559. return null;
  560. }
  561. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  562. {
  563. // min size 300 mb
  564. const long minPlayableSize = 314572800;
  565. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  566. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  567. // Once we reach a file that is at least the minimum, return all subsequent ones
  568. var allVobs = new DirectoryInfo(root).EnumerateFiles("*", SearchOption.AllDirectories)
  569. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  570. .OrderBy(i => i.FullName)
  571. .ToList();
  572. // If we didn't find any satisfying the min length, just take them all
  573. if (allVobs.Count == 0)
  574. {
  575. _logger.Error("No vobs found in dvd structure.");
  576. return new List<string>();
  577. }
  578. if (titleNumber.HasValue)
  579. {
  580. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  581. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  582. if (vobs.Count > 0)
  583. {
  584. var minSizeVobs = vobs
  585. .SkipWhile(f => f.Length < minPlayableSize)
  586. .ToList();
  587. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  588. }
  589. _logger.Debug("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  590. }
  591. var files = allVobs
  592. .SkipWhile(f => f.Length < minPlayableSize)
  593. .ToList();
  594. // If we didn't find any satisfying the min length, just take them all
  595. if (files.Count == 0)
  596. {
  597. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  598. files = allVobs;
  599. }
  600. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  601. if (files.Count > 0)
  602. {
  603. var parts = Path.GetFileNameWithoutExtension(files[0].FullName).Split('_');
  604. if (parts.Length == 3)
  605. {
  606. var title = parts[1];
  607. files = files.TakeWhile(f =>
  608. {
  609. var fileParts = Path.GetFileNameWithoutExtension(f.FullName).Split('_');
  610. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  611. }).ToList();
  612. // If this resulted in not getting any vobs, just take them all
  613. if (files.Count == 0)
  614. {
  615. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  616. files = allVobs;
  617. }
  618. }
  619. }
  620. return files.Select(i => i.FullName);
  621. }
  622. }
  623. }