FFProbeVideoInfo.cs 26 KB

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