FFProbeVideoInfo.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. using DvdLib.Ifo;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Model.Dlna;
  4. using MediaBrowser.Controller.Chapters;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Movies;
  8. using MediaBrowser.Controller.Entities.TV;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Controller.Subtitles;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.MediaInfo;
  19. using MediaBrowser.Model.Providers;
  20. using MediaBrowser.Model.Serialization;
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using MediaBrowser.Controller.IO;
  29. using MediaBrowser.Model.IO;
  30. using MediaBrowser.Model.Globalization;
  31. namespace MediaBrowser.Providers.MediaInfo
  32. {
  33. public class FFProbeVideoInfo
  34. {
  35. private readonly ILogger _logger;
  36. private readonly IIsoManager _isoManager;
  37. private readonly IMediaEncoder _mediaEncoder;
  38. private readonly IItemRepository _itemRepo;
  39. private readonly IBlurayExaminer _blurayExaminer;
  40. private readonly ILocalizationManager _localization;
  41. private readonly IApplicationPaths _appPaths;
  42. private readonly IJsonSerializer _json;
  43. private readonly IEncodingManager _encodingManager;
  44. private readonly IFileSystem _fileSystem;
  45. private readonly IServerConfigurationManager _config;
  46. private readonly ISubtitleManager _subtitleManager;
  47. private readonly IChapterManager _chapterManager;
  48. private readonly ILibraryManager _libraryManager;
  49. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  50. public FFProbeVideoInfo(ILogger logger, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IBlurayExaminer blurayExaminer, ILocalizationManager localization, IApplicationPaths appPaths, IJsonSerializer json, IEncodingManager encodingManager, IFileSystem fileSystem, IServerConfigurationManager config, ISubtitleManager subtitleManager, IChapterManager chapterManager, ILibraryManager libraryManager)
  51. {
  52. _logger = logger;
  53. _isoManager = isoManager;
  54. _mediaEncoder = mediaEncoder;
  55. _itemRepo = itemRepo;
  56. _blurayExaminer = blurayExaminer;
  57. _localization = localization;
  58. _appPaths = appPaths;
  59. _json = json;
  60. _encodingManager = encodingManager;
  61. _fileSystem = fileSystem;
  62. _config = config;
  63. _subtitleManager = subtitleManager;
  64. _chapterManager = chapterManager;
  65. _libraryManager = libraryManager;
  66. }
  67. public async Task<ItemUpdateType> ProbeVideo<T>(T item,
  68. MetadataRefreshOptions options,
  69. CancellationToken cancellationToken)
  70. where T : Video
  71. {
  72. var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
  73. BlurayDiscInfo blurayDiscInfo = null;
  74. try
  75. {
  76. List<string> streamFileNames = null;
  77. if (item.VideoType == VideoType.Iso)
  78. {
  79. item.IsoType = DetermineIsoType(isoMount);
  80. }
  81. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  82. {
  83. streamFileNames = FetchFromDvdLib(item, isoMount);
  84. if (streamFileNames.Count == 0)
  85. {
  86. _logger.Error("No playable vobs found in dvd structure, skipping ffprobe.");
  87. return ItemUpdateType.MetadataImport;
  88. }
  89. }
  90. else if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  91. {
  92. var inputPath = isoMount != null ? isoMount.MountedPath : item.Path;
  93. blurayDiscInfo = GetBDInfo(inputPath);
  94. streamFileNames = blurayDiscInfo.Files;
  95. if (streamFileNames.Count == 0)
  96. {
  97. _logger.Error("No playable vobs found in bluray structure, skipping ffprobe.");
  98. return ItemUpdateType.MetadataImport;
  99. }
  100. }
  101. if (streamFileNames == null)
  102. {
  103. streamFileNames = new List<string>();
  104. }
  105. var result = await GetMediaInfo(item, isoMount, streamFileNames, cancellationToken).ConfigureAwait(false);
  106. cancellationToken.ThrowIfCancellationRequested();
  107. await Fetch(item, cancellationToken, result, isoMount, blurayDiscInfo, options).ConfigureAwait(false);
  108. }
  109. finally
  110. {
  111. if (isoMount != null)
  112. {
  113. isoMount.Dispose();
  114. }
  115. }
  116. return ItemUpdateType.MetadataImport;
  117. }
  118. private Task<Model.MediaInfo.MediaInfo> GetMediaInfo(Video item,
  119. IIsoMount isoMount,
  120. List<string> streamFileNames,
  121. CancellationToken cancellationToken)
  122. {
  123. cancellationToken.ThrowIfCancellationRequested();
  124. var protocol = item.LocationType == LocationType.Remote
  125. ? MediaProtocol.Http
  126. : MediaProtocol.File;
  127. return _mediaEncoder.GetMediaInfo(new MediaInfoRequest
  128. {
  129. PlayableStreamFileNames = streamFileNames,
  130. MountedIso = isoMount,
  131. ExtractChapters = true,
  132. VideoType = item.VideoType,
  133. MediaType = DlnaProfileType.Video,
  134. InputPath = item.Path,
  135. Protocol = protocol
  136. }, cancellationToken);
  137. }
  138. protected async Task Fetch(Video video,
  139. CancellationToken cancellationToken,
  140. Model.MediaInfo.MediaInfo mediaInfo,
  141. IIsoMount isoMount,
  142. BlurayDiscInfo blurayInfo,
  143. MetadataRefreshOptions options)
  144. {
  145. var mediaStreams = mediaInfo.MediaStreams;
  146. video.TotalBitrate = mediaInfo.Bitrate;
  147. //video.FormatName = (mediaInfo.Container ?? string.Empty)
  148. // .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
  149. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  150. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  151. if (needToSetRuntime)
  152. {
  153. video.RunTimeTicks = mediaInfo.RunTimeTicks;
  154. }
  155. if (video.VideoType == VideoType.VideoFile)
  156. {
  157. var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');
  158. video.Container = extension;
  159. }
  160. else
  161. {
  162. video.Container = null;
  163. }
  164. video.Container = mediaInfo.Container;
  165. var chapters = mediaInfo.Chapters ?? new List<ChapterInfo>();
  166. if (blurayInfo != null)
  167. {
  168. FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
  169. }
  170. await AddExternalSubtitles(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
  171. var libraryOptions = _libraryManager.GetLibraryOptions(video);
  172. FetchEmbeddedInfo(video, mediaInfo, options, libraryOptions);
  173. await FetchPeople(video, mediaInfo, options).ConfigureAwait(false);
  174. video.IsHD = mediaStreams.Any(i => i.Type == MediaStreamType.Video && i.Width.HasValue && i.Width.Value >= 1260);
  175. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  176. video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;
  177. video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
  178. video.Timestamp = mediaInfo.Timestamp;
  179. video.Video3DFormat = video.Video3DFormat ?? mediaInfo.Video3DFormat;
  180. await _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken).ConfigureAwait(false);
  181. if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh ||
  182. options.MetadataRefreshMode == MetadataRefreshMode.Default)
  183. {
  184. if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
  185. {
  186. AddDummyChapters(video, chapters);
  187. }
  188. NormalizeChapterNames(chapters);
  189. var extractDuringScan = false;
  190. if (libraryOptions != null)
  191. {
  192. extractDuringScan = libraryOptions.ExtractChapterImagesDuringLibraryScan;
  193. }
  194. await _encodingManager.RefreshChapterImages(video, chapters, extractDuringScan, false, cancellationToken).ConfigureAwait(false);
  195. await _chapterManager.SaveChapters(video.Id.ToString(), chapters).ConfigureAwait(false);
  196. }
  197. }
  198. private void NormalizeChapterNames(List<ChapterInfo> chapters)
  199. {
  200. var index = 1;
  201. foreach (var chapter in chapters)
  202. {
  203. TimeSpan time;
  204. // Check if the name is empty and/or if the name is a time
  205. // Some ripping programs do that.
  206. if (string.IsNullOrWhiteSpace(chapter.Name) ||
  207. TimeSpan.TryParse(chapter.Name, out time))
  208. {
  209. chapter.Name = string.Format(_localization.GetLocalizedString("LabelChapterName"), index.ToString(CultureInfo.InvariantCulture));
  210. }
  211. index++;
  212. }
  213. }
  214. private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
  215. {
  216. var video = (Video)item;
  217. //video.PlayableStreamFileNames = blurayInfo.Files.ToList();
  218. // Use BD Info if it has multiple m2ts. Otherwise, treat it like a video file and rely more on ffprobe output
  219. if (blurayInfo.Files.Count > 1)
  220. {
  221. int? currentHeight = null;
  222. int? currentWidth = null;
  223. int? currentBitRate = null;
  224. var videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  225. // Grab the values that ffprobe recorded
  226. if (videoStream != null)
  227. {
  228. currentBitRate = videoStream.BitRate;
  229. currentWidth = videoStream.Width;
  230. currentHeight = videoStream.Height;
  231. }
  232. // Fill video properties from the BDInfo result
  233. mediaStreams.Clear();
  234. mediaStreams.AddRange(blurayInfo.MediaStreams);
  235. if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
  236. {
  237. video.RunTimeTicks = blurayInfo.RunTimeTicks;
  238. }
  239. if (blurayInfo.Chapters != null)
  240. {
  241. chapters.Clear();
  242. chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
  243. {
  244. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  245. }));
  246. }
  247. videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  248. // Use the ffprobe values if these are empty
  249. if (videoStream != null)
  250. {
  251. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  252. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  253. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  254. }
  255. }
  256. }
  257. private bool IsEmpty(int? num)
  258. {
  259. return !num.HasValue || num.Value == 0;
  260. }
  261. /// <summary>
  262. /// Gets information about the longest playlist on a bdrom
  263. /// </summary>
  264. /// <param name="path">The path.</param>
  265. /// <returns>VideoStream.</returns>
  266. private BlurayDiscInfo GetBDInfo(string path)
  267. {
  268. if (string.IsNullOrWhiteSpace(path))
  269. {
  270. throw new ArgumentNullException("path");
  271. }
  272. try
  273. {
  274. return _blurayExaminer.GetDiscInfo(path);
  275. }
  276. catch (Exception ex)
  277. {
  278. _logger.ErrorException("Error getting BDInfo", ex);
  279. return null;
  280. }
  281. }
  282. private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions refreshOptions, LibraryOptions libraryOptions)
  283. {
  284. var isFullRefresh = refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  285. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.OfficialRating))
  286. {
  287. if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
  288. {
  289. video.OfficialRating = data.OfficialRating;
  290. }
  291. }
  292. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Genres))
  293. {
  294. if (video.Genres.Count == 0 || isFullRefresh)
  295. {
  296. video.Genres.Clear();
  297. foreach (var genre in data.Genres)
  298. {
  299. video.AddGenre(genre);
  300. }
  301. }
  302. }
  303. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Studios))
  304. {
  305. if (video.Studios.Length == 0 || isFullRefresh)
  306. {
  307. video.SetStudios(data.Studios);
  308. }
  309. }
  310. if (data.ProductionYear.HasValue)
  311. {
  312. if (!video.ProductionYear.HasValue || isFullRefresh)
  313. {
  314. video.ProductionYear = data.ProductionYear;
  315. }
  316. }
  317. if (data.PremiereDate.HasValue)
  318. {
  319. if (!video.PremiereDate.HasValue || isFullRefresh)
  320. {
  321. video.PremiereDate = data.PremiereDate;
  322. }
  323. }
  324. if (data.IndexNumber.HasValue)
  325. {
  326. if (!video.IndexNumber.HasValue || isFullRefresh)
  327. {
  328. video.IndexNumber = data.IndexNumber;
  329. }
  330. }
  331. if (data.ParentIndexNumber.HasValue)
  332. {
  333. if (!video.ParentIndexNumber.HasValue || isFullRefresh)
  334. {
  335. video.ParentIndexNumber = data.ParentIndexNumber;
  336. }
  337. }
  338. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Name))
  339. {
  340. if (!string.IsNullOrWhiteSpace(data.Name) && libraryOptions.EnableEmbeddedTitles)
  341. {
  342. // Don't use the embedded name for extras because it will often be the same name as the movie
  343. if (!video.ExtraType.HasValue && !video.IsOwnedItem)
  344. {
  345. video.Name = data.Name;
  346. }
  347. }
  348. }
  349. // If we don't have a ProductionYear try and get it from PremiereDate
  350. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  351. {
  352. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  353. }
  354. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Overview))
  355. {
  356. if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
  357. {
  358. video.Overview = data.Overview;
  359. }
  360. }
  361. }
  362. private async Task FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  363. {
  364. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  365. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Cast))
  366. {
  367. if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
  368. {
  369. var people = new List<PersonInfo>();
  370. foreach (var person in data.People)
  371. {
  372. PeopleHelper.AddPerson(people, new PersonInfo
  373. {
  374. Name = person.Name,
  375. Type = person.Type,
  376. Role = person.Role
  377. });
  378. }
  379. await _libraryManager.UpdatePeople(video, people);
  380. }
  381. }
  382. }
  383. private SubtitleOptions GetOptions()
  384. {
  385. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  386. }
  387. /// <summary>
  388. /// Adds the external subtitles.
  389. /// </summary>
  390. /// <param name="video">The video.</param>
  391. /// <param name="currentStreams">The current streams.</param>
  392. /// <param name="options">The refreshOptions.</param>
  393. /// <param name="cancellationToken">The cancellation token.</param>
  394. /// <returns>Task.</returns>
  395. private async Task AddExternalSubtitles(Video video,
  396. List<MediaStream> currentStreams,
  397. MetadataRefreshOptions options,
  398. CancellationToken cancellationToken)
  399. {
  400. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  401. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  402. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false).ToList();
  403. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  404. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  405. var subtitleOptions = GetOptions();
  406. if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
  407. video is Episode) ||
  408. (subtitleOptions.DownloadMovieSubtitles &&
  409. video is Movie))
  410. {
  411. var downloadedLanguages = await new SubtitleDownloader(_logger,
  412. _subtitleManager)
  413. .DownloadSubtitles(video,
  414. currentStreams.Concat(externalSubtitleStreams).ToList(),
  415. subtitleOptions.SkipIfEmbeddedSubtitlesPresent,
  416. subtitleOptions.SkipIfAudioTrackMatches,
  417. subtitleOptions.RequirePerfectMatch,
  418. subtitleOptions.DownloadLanguages,
  419. cancellationToken).ConfigureAwait(false);
  420. // Rescan
  421. if (downloadedLanguages.Count > 0)
  422. {
  423. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true).ToList();
  424. }
  425. }
  426. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToArray();
  427. currentStreams.AddRange(externalSubtitleStreams);
  428. }
  429. /// <summary>
  430. /// The dummy chapter duration
  431. /// </summary>
  432. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  433. /// <summary>
  434. /// Adds the dummy chapters.
  435. /// </summary>
  436. /// <param name="video">The video.</param>
  437. /// <param name="chapters">The chapters.</param>
  438. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  439. {
  440. var runtime = video.RunTimeTicks ?? 0;
  441. if (runtime < 0)
  442. {
  443. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  444. }
  445. if (runtime < _dummyChapterDuration)
  446. {
  447. return;
  448. }
  449. long currentChapterTicks = 0;
  450. var index = 1;
  451. // Limit to 100 chapters just in case there's some incorrect metadata here
  452. while (currentChapterTicks < runtime && index < 100)
  453. {
  454. chapters.Add(new ChapterInfo
  455. {
  456. StartPositionTicks = currentChapterTicks
  457. });
  458. index++;
  459. currentChapterTicks += _dummyChapterDuration;
  460. }
  461. }
  462. private List<string> FetchFromDvdLib(Video item, IIsoMount mount)
  463. {
  464. var path = mount == null ? item.Path : mount.MountedPath;
  465. var dvd = new Dvd(path, _fileSystem);
  466. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  467. byte? titleNumber = null;
  468. if (primaryTitle != null)
  469. {
  470. titleNumber = primaryTitle.VideoTitleSetNumber;
  471. item.RunTimeTicks = GetRuntime(primaryTitle);
  472. }
  473. return GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  474. .Select(Path.GetFileName)
  475. .ToList();
  476. }
  477. private long GetRuntime(Title title)
  478. {
  479. return title.ProgramChains
  480. .Select(i => (TimeSpan)i.PlaybackTime)
  481. .Select(i => i.Ticks)
  482. .Sum();
  483. }
  484. /// <summary>
  485. /// Mounts the iso if needed.
  486. /// </summary>
  487. /// <param name="item">The item.</param>
  488. /// <param name="cancellationToken">The cancellation token.</param>
  489. /// <returns>IsoMount.</returns>
  490. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  491. {
  492. if (item.VideoType == VideoType.Iso)
  493. {
  494. return _isoManager.Mount(item.Path, cancellationToken);
  495. }
  496. return Task.FromResult<IIsoMount>(null);
  497. }
  498. /// <summary>
  499. /// Determines the type of the iso.
  500. /// </summary>
  501. /// <param name="isoMount">The iso mount.</param>
  502. /// <returns>System.Nullable{IsoType}.</returns>
  503. private IsoType? DetermineIsoType(IIsoMount isoMount)
  504. {
  505. var fileSystemEntries = _fileSystem.GetFileSystemEntryPaths(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  506. if (fileSystemEntries.Contains("video_ts", StringComparer.OrdinalIgnoreCase) ||
  507. fileSystemEntries.Contains("VIDEO_TS.IFO", StringComparer.OrdinalIgnoreCase))
  508. {
  509. return IsoType.Dvd;
  510. }
  511. if (fileSystemEntries.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  512. {
  513. return IsoType.BluRay;
  514. }
  515. return null;
  516. }
  517. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  518. {
  519. // min size 300 mb
  520. const long minPlayableSize = 314572800;
  521. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  522. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  523. // Once we reach a file that is at least the minimum, return all subsequent ones
  524. var allVobs = _fileSystem.GetFiles(root, new[] { ".vob" }, false, true)
  525. .OrderBy(i => i.FullName)
  526. .ToList();
  527. // If we didn't find any satisfying the min length, just take them all
  528. if (allVobs.Count == 0)
  529. {
  530. _logger.Error("No vobs found in dvd structure.");
  531. return new List<string>();
  532. }
  533. if (titleNumber.HasValue)
  534. {
  535. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  536. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  537. if (vobs.Count > 0)
  538. {
  539. var minSizeVobs = vobs
  540. .SkipWhile(f => f.Length < minPlayableSize)
  541. .ToList();
  542. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  543. }
  544. _logger.Info("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  545. }
  546. var files = allVobs
  547. .SkipWhile(f => f.Length < minPlayableSize)
  548. .ToList();
  549. // If we didn't find any satisfying the min length, just take them all
  550. if (files.Count == 0)
  551. {
  552. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  553. files = allVobs;
  554. }
  555. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  556. if (files.Count > 0)
  557. {
  558. var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
  559. if (parts.Length == 3)
  560. {
  561. var title = parts[1];
  562. files = files.TakeWhile(f =>
  563. {
  564. var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
  565. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  566. }).ToList();
  567. // If this resulted in not getting any vobs, just take them all
  568. if (files.Count == 0)
  569. {
  570. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  571. files = allVobs;
  572. }
  573. }
  574. }
  575. return files.Select(i => i.FullName);
  576. }
  577. }
  578. }