FFProbeVideoInfo.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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(new ChapterImageRefreshOptions
  195. {
  196. Chapters = chapters,
  197. Video = video,
  198. ExtractImages = extractDuringScan,
  199. SaveChapters = false
  200. }, cancellationToken).ConfigureAwait(false);
  201. await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
  202. }
  203. }
  204. private void NormalizeChapterNames(List<ChapterInfo> chapters)
  205. {
  206. var index = 1;
  207. foreach (var chapter in chapters)
  208. {
  209. TimeSpan time;
  210. // Check if the name is empty and/or if the name is a time
  211. // Some ripping programs do that.
  212. if (string.IsNullOrWhiteSpace(chapter.Name) ||
  213. TimeSpan.TryParse(chapter.Name, out time))
  214. {
  215. chapter.Name = string.Format(_localization.GetLocalizedString("LabelChapterName"), index.ToString(CultureInfo.InvariantCulture));
  216. }
  217. index++;
  218. }
  219. }
  220. private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
  221. {
  222. var video = (Video)item;
  223. //video.PlayableStreamFileNames = blurayInfo.Files.ToList();
  224. // Use BD Info if it has multiple m2ts. Otherwise, treat it like a video file and rely more on ffprobe output
  225. if (blurayInfo.Files.Count > 1)
  226. {
  227. int? currentHeight = null;
  228. int? currentWidth = null;
  229. int? currentBitRate = null;
  230. var videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  231. // Grab the values that ffprobe recorded
  232. if (videoStream != null)
  233. {
  234. currentBitRate = videoStream.BitRate;
  235. currentWidth = videoStream.Width;
  236. currentHeight = videoStream.Height;
  237. }
  238. // Fill video properties from the BDInfo result
  239. mediaStreams.Clear();
  240. mediaStreams.AddRange(blurayInfo.MediaStreams);
  241. if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
  242. {
  243. video.RunTimeTicks = blurayInfo.RunTimeTicks;
  244. }
  245. if (blurayInfo.Chapters != null)
  246. {
  247. chapters.Clear();
  248. chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
  249. {
  250. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  251. }));
  252. }
  253. videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  254. // Use the ffprobe values if these are empty
  255. if (videoStream != null)
  256. {
  257. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  258. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  259. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  260. }
  261. }
  262. }
  263. private bool IsEmpty(int? num)
  264. {
  265. return !num.HasValue || num.Value == 0;
  266. }
  267. /// <summary>
  268. /// Gets information about the longest playlist on a bdrom
  269. /// </summary>
  270. /// <param name="path">The path.</param>
  271. /// <returns>VideoStream.</returns>
  272. private BlurayDiscInfo GetBDInfo(string path)
  273. {
  274. if (string.IsNullOrWhiteSpace(path))
  275. {
  276. throw new ArgumentNullException("path");
  277. }
  278. try
  279. {
  280. return _blurayExaminer.GetDiscInfo(path);
  281. }
  282. catch (Exception ex)
  283. {
  284. _logger.ErrorException("Error getting BDInfo", ex);
  285. return null;
  286. }
  287. }
  288. private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions refreshOptions, LibraryOptions libraryOptions)
  289. {
  290. var isFullRefresh = refreshOptions.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  291. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.OfficialRating))
  292. {
  293. if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
  294. {
  295. video.OfficialRating = data.OfficialRating;
  296. }
  297. }
  298. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Genres))
  299. {
  300. if (video.Genres.Count == 0 || isFullRefresh)
  301. {
  302. video.Genres.Clear();
  303. foreach (var genre in data.Genres)
  304. {
  305. video.AddGenre(genre);
  306. }
  307. }
  308. }
  309. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Studios))
  310. {
  311. if (video.Studios.Count == 0 || isFullRefresh)
  312. {
  313. video.Studios.Clear();
  314. foreach (var studio in data.Studios)
  315. {
  316. video.AddStudio(studio);
  317. }
  318. }
  319. }
  320. if (data.ProductionYear.HasValue)
  321. {
  322. if (!video.ProductionYear.HasValue || isFullRefresh)
  323. {
  324. video.ProductionYear = data.ProductionYear;
  325. }
  326. }
  327. if (data.PremiereDate.HasValue)
  328. {
  329. if (!video.PremiereDate.HasValue || isFullRefresh)
  330. {
  331. video.PremiereDate = data.PremiereDate;
  332. }
  333. }
  334. if (data.IndexNumber.HasValue)
  335. {
  336. if (!video.IndexNumber.HasValue || isFullRefresh)
  337. {
  338. video.IndexNumber = data.IndexNumber;
  339. }
  340. }
  341. if (data.ParentIndexNumber.HasValue)
  342. {
  343. if (!video.ParentIndexNumber.HasValue || isFullRefresh)
  344. {
  345. video.ParentIndexNumber = data.ParentIndexNumber;
  346. }
  347. }
  348. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Name))
  349. {
  350. if (!string.IsNullOrWhiteSpace(data.Name) && libraryOptions.EnableEmbeddedTitles)
  351. {
  352. // Don't use the embedded name for extras because it will often be the same name as the movie
  353. if (!video.ExtraType.HasValue && !video.IsOwnedItem)
  354. {
  355. video.Name = data.Name;
  356. }
  357. }
  358. }
  359. // If we don't have a ProductionYear try and get it from PremiereDate
  360. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  361. {
  362. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  363. }
  364. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Overview))
  365. {
  366. if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
  367. {
  368. video.Overview = data.Overview;
  369. }
  370. }
  371. }
  372. private async Task FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  373. {
  374. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  375. if (!video.IsLocked && !video.LockedFields.Contains(MetadataFields.Cast))
  376. {
  377. if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
  378. {
  379. var people = new List<PersonInfo>();
  380. foreach (var person in data.People)
  381. {
  382. PeopleHelper.AddPerson(people, new PersonInfo
  383. {
  384. Name = person.Name,
  385. Type = person.Type,
  386. Role = person.Role
  387. });
  388. }
  389. await _libraryManager.UpdatePeople(video, people);
  390. }
  391. }
  392. }
  393. private SubtitleOptions GetOptions()
  394. {
  395. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  396. }
  397. /// <summary>
  398. /// Adds the external subtitles.
  399. /// </summary>
  400. /// <param name="video">The video.</param>
  401. /// <param name="currentStreams">The current streams.</param>
  402. /// <param name="options">The refreshOptions.</param>
  403. /// <param name="cancellationToken">The cancellation token.</param>
  404. /// <returns>Task.</returns>
  405. private async Task AddExternalSubtitles(Video video,
  406. List<MediaStream> currentStreams,
  407. MetadataRefreshOptions options,
  408. CancellationToken cancellationToken)
  409. {
  410. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  411. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  412. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false).ToList();
  413. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  414. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  415. var subtitleOptions = GetOptions();
  416. if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
  417. video is Episode) ||
  418. (subtitleOptions.DownloadMovieSubtitles &&
  419. video is Movie))
  420. {
  421. var downloadedLanguages = await new SubtitleDownloader(_logger,
  422. _subtitleManager)
  423. .DownloadSubtitles(video,
  424. currentStreams.Concat(externalSubtitleStreams).ToList(),
  425. subtitleOptions.SkipIfEmbeddedSubtitlesPresent,
  426. subtitleOptions.SkipIfAudioTrackMatches,
  427. subtitleOptions.RequirePerfectMatch,
  428. subtitleOptions.DownloadLanguages,
  429. cancellationToken).ConfigureAwait(false);
  430. // Rescan
  431. if (downloadedLanguages.Count > 0)
  432. {
  433. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true).ToList();
  434. }
  435. }
  436. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  437. currentStreams.AddRange(externalSubtitleStreams);
  438. }
  439. /// <summary>
  440. /// The dummy chapter duration
  441. /// </summary>
  442. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  443. /// <summary>
  444. /// Adds the dummy chapters.
  445. /// </summary>
  446. /// <param name="video">The video.</param>
  447. /// <param name="chapters">The chapters.</param>
  448. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  449. {
  450. var runtime = video.RunTimeTicks ?? 0;
  451. if (runtime < 0)
  452. {
  453. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  454. }
  455. if (runtime < _dummyChapterDuration)
  456. {
  457. return;
  458. }
  459. long currentChapterTicks = 0;
  460. var index = 1;
  461. // Limit to 100 chapters just in case there's some incorrect metadata here
  462. while (currentChapterTicks < runtime && index < 100)
  463. {
  464. chapters.Add(new ChapterInfo
  465. {
  466. StartPositionTicks = currentChapterTicks
  467. });
  468. index++;
  469. currentChapterTicks += _dummyChapterDuration;
  470. }
  471. }
  472. private List<string> FetchFromDvdLib(Video item, IIsoMount mount)
  473. {
  474. var path = mount == null ? item.Path : mount.MountedPath;
  475. var dvd = new Dvd(path, _fileSystem);
  476. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  477. byte? titleNumber = null;
  478. if (primaryTitle != null)
  479. {
  480. titleNumber = primaryTitle.VideoTitleSetNumber;
  481. item.RunTimeTicks = GetRuntime(primaryTitle);
  482. }
  483. return GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  484. .Select(Path.GetFileName)
  485. .ToList();
  486. }
  487. private long GetRuntime(Title title)
  488. {
  489. return title.ProgramChains
  490. .Select(i => (TimeSpan)i.PlaybackTime)
  491. .Select(i => i.Ticks)
  492. .Sum();
  493. }
  494. /// <summary>
  495. /// Mounts the iso if needed.
  496. /// </summary>
  497. /// <param name="item">The item.</param>
  498. /// <param name="cancellationToken">The cancellation token.</param>
  499. /// <returns>IsoMount.</returns>
  500. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  501. {
  502. if (item.VideoType == VideoType.Iso)
  503. {
  504. return _isoManager.Mount(item.Path, cancellationToken);
  505. }
  506. return Task.FromResult<IIsoMount>(null);
  507. }
  508. /// <summary>
  509. /// Determines the type of the iso.
  510. /// </summary>
  511. /// <param name="isoMount">The iso mount.</param>
  512. /// <returns>System.Nullable{IsoType}.</returns>
  513. private IsoType? DetermineIsoType(IIsoMount isoMount)
  514. {
  515. var fileSystemEntries = _fileSystem.GetFileSystemEntryPaths(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  516. if (fileSystemEntries.Contains("video_ts", StringComparer.OrdinalIgnoreCase) ||
  517. fileSystemEntries.Contains("VIDEO_TS.IFO", StringComparer.OrdinalIgnoreCase))
  518. {
  519. return IsoType.Dvd;
  520. }
  521. if (fileSystemEntries.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  522. {
  523. return IsoType.BluRay;
  524. }
  525. return null;
  526. }
  527. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  528. {
  529. // min size 300 mb
  530. const long minPlayableSize = 314572800;
  531. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  532. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  533. // Once we reach a file that is at least the minimum, return all subsequent ones
  534. var allVobs = _fileSystem.GetFiles(root, new[] { ".vob" }, false, true)
  535. .OrderBy(i => i.FullName)
  536. .ToList();
  537. // If we didn't find any satisfying the min length, just take them all
  538. if (allVobs.Count == 0)
  539. {
  540. _logger.Error("No vobs found in dvd structure.");
  541. return new List<string>();
  542. }
  543. if (titleNumber.HasValue)
  544. {
  545. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  546. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  547. if (vobs.Count > 0)
  548. {
  549. var minSizeVobs = vobs
  550. .SkipWhile(f => f.Length < minPlayableSize)
  551. .ToList();
  552. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  553. }
  554. _logger.Info("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  555. }
  556. var files = allVobs
  557. .SkipWhile(f => f.Length < minPlayableSize)
  558. .ToList();
  559. // If we didn't find any satisfying the min length, just take them all
  560. if (files.Count == 0)
  561. {
  562. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  563. files = allVobs;
  564. }
  565. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  566. if (files.Count > 0)
  567. {
  568. var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
  569. if (parts.Length == 3)
  570. {
  571. var title = parts[1];
  572. files = files.TakeWhile(f =>
  573. {
  574. var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
  575. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  576. }).ToList();
  577. // If this resulted in not getting any vobs, just take them all
  578. if (files.Count == 0)
  579. {
  580. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  581. files = allVobs;
  582. }
  583. }
  584. }
  585. return files.Select(i => i.FullName);
  586. }
  587. }
  588. }