FFProbeVideoInfo.cs 25 KB

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