FFProbeVideoInfo.cs 25 KB

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