FFProbeVideoInfo.cs 26 KB

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