FFProbeVideoInfo.cs 27 KB

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