FFProbeVideoInfo.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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, bool enableSubtitleDownloading, 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, enableSubtitleDownloading).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, bool enableSubtitleDownloading)
  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, enableSubtitleDownloading, 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. /// <param name="directoryService">The directory service.</param>
  339. /// <param name="enableSubtitleDownloading">if set to <c>true</c> [enable subtitle downloading].</param>
  340. /// <param name="cancellationToken">The cancellation token.</param>
  341. /// <returns>Task.</returns>
  342. private async Task AddExternalSubtitles(Video video, List<MediaStream> currentStreams, IDirectoryService directoryService, bool enableSubtitleDownloading, CancellationToken cancellationToken)
  343. {
  344. var subtitleResolver = new SubtitleResolver(_localization);
  345. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, currentStreams.Count, directoryService, false).ToList();
  346. if (enableSubtitleDownloading && (_config.Configuration.SubtitleOptions.DownloadEpisodeSubtitles &&
  347. video is Episode) ||
  348. (_config.Configuration.SubtitleOptions.DownloadMovieSubtitles &&
  349. video is Movie))
  350. {
  351. var downloadedLanguages = await new SubtitleDownloader(_logger,
  352. _subtitleManager)
  353. .DownloadSubtitles(video,
  354. currentStreams,
  355. externalSubtitleStreams,
  356. _config.Configuration.SubtitleOptions.SkipIfGraphicalSubtitlesPresent,
  357. _config.Configuration.SubtitleOptions.SkipIfAudioTrackMatches,
  358. _config.Configuration.SubtitleOptions.DownloadLanguages,
  359. cancellationToken).ConfigureAwait(false);
  360. // Rescan
  361. if (downloadedLanguages.Count > 0)
  362. {
  363. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, currentStreams.Count, directoryService, true).ToList();
  364. }
  365. }
  366. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  367. currentStreams.AddRange(externalSubtitleStreams);
  368. }
  369. /// <summary>
  370. /// The dummy chapter duration
  371. /// </summary>
  372. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  373. /// <summary>
  374. /// Adds the dummy chapters.
  375. /// </summary>
  376. /// <param name="video">The video.</param>
  377. /// <param name="chapters">The chapters.</param>
  378. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  379. {
  380. var runtime = video.RunTimeTicks ?? 0;
  381. if (runtime < 0)
  382. {
  383. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  384. }
  385. if (runtime < _dummyChapterDuration)
  386. {
  387. return;
  388. }
  389. long currentChapterTicks = 0;
  390. var index = 1;
  391. // Limit to 100 chapters just in case there's some incorrect metadata here
  392. while (currentChapterTicks < runtime && index < 100)
  393. {
  394. chapters.Add(new ChapterInfo
  395. {
  396. Name = "Chapter " + index,
  397. StartPositionTicks = currentChapterTicks
  398. });
  399. index++;
  400. currentChapterTicks += _dummyChapterDuration;
  401. }
  402. }
  403. /// <summary>
  404. /// Called when [pre fetch].
  405. /// </summary>
  406. /// <param name="item">The item.</param>
  407. /// <param name="mount">The mount.</param>
  408. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  409. {
  410. if (item.VideoType == VideoType.Iso)
  411. {
  412. item.IsoType = DetermineIsoType(mount);
  413. }
  414. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  415. {
  416. FetchFromDvdLib(item, mount);
  417. }
  418. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType.Value == IsoType.BluRay))
  419. {
  420. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  421. }
  422. }
  423. private void ExtractTimestamp(Video video)
  424. {
  425. if (video.VideoType == VideoType.VideoFile)
  426. {
  427. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  428. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  429. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  430. {
  431. try
  432. {
  433. video.Timestamp = GetMpegTimestamp(video.Path);
  434. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  435. }
  436. catch (Exception ex)
  437. {
  438. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  439. video.Timestamp = null;
  440. }
  441. }
  442. }
  443. }
  444. private TransportStreamTimestamp GetMpegTimestamp(string path)
  445. {
  446. var packetBuffer = new byte['Å'];
  447. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  448. {
  449. fs.Read(packetBuffer, 0, packetBuffer.Length);
  450. }
  451. if (packetBuffer[0] == 71)
  452. {
  453. return TransportStreamTimestamp.None;
  454. }
  455. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  456. {
  457. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  458. {
  459. return TransportStreamTimestamp.Zero;
  460. }
  461. return TransportStreamTimestamp.Valid;
  462. }
  463. return TransportStreamTimestamp.None;
  464. }
  465. private void FetchFromDvdLib(Video item, IIsoMount mount)
  466. {
  467. var path = mount == null ? item.Path : mount.MountedPath;
  468. var dvd = new Dvd(path);
  469. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  470. byte? titleNumber = null;
  471. if (primaryTitle != null)
  472. {
  473. titleNumber = primaryTitle.VideoTitleSetNumber;
  474. item.RunTimeTicks = GetRuntime(primaryTitle);
  475. }
  476. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  477. .Select(Path.GetFileName)
  478. .ToList();
  479. }
  480. private long GetRuntime(Title title)
  481. {
  482. return title.ProgramChains
  483. .Select(i => (TimeSpan)i.PlaybackTime)
  484. .Select(i => i.Ticks)
  485. .Sum();
  486. }
  487. /// <summary>
  488. /// Mounts the iso if needed.
  489. /// </summary>
  490. /// <param name="item">The item.</param>
  491. /// <param name="cancellationToken">The cancellation token.</param>
  492. /// <returns>IsoMount.</returns>
  493. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  494. {
  495. if (item.VideoType == VideoType.Iso)
  496. {
  497. return _isoManager.Mount(item.Path, cancellationToken);
  498. }
  499. return Task.FromResult<IIsoMount>(null);
  500. }
  501. /// <summary>
  502. /// Determines the type of the iso.
  503. /// </summary>
  504. /// <param name="isoMount">The iso mount.</param>
  505. /// <returns>System.Nullable{IsoType}.</returns>
  506. private IsoType? DetermineIsoType(IIsoMount isoMount)
  507. {
  508. var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  509. if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
  510. {
  511. return IsoType.Dvd;
  512. }
  513. if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  514. {
  515. return IsoType.BluRay;
  516. }
  517. return null;
  518. }
  519. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  520. {
  521. // min size 300 mb
  522. const long minPlayableSize = 314572800;
  523. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  524. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  525. // Once we reach a file that is at least the minimum, return all subsequent ones
  526. var allVobs = new DirectoryInfo(root).EnumerateFiles("*", SearchOption.AllDirectories)
  527. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  528. .OrderBy(i => i.FullName)
  529. .ToList();
  530. // If we didn't find any satisfying the min length, just take them all
  531. if (allVobs.Count == 0)
  532. {
  533. _logger.Error("No vobs found in dvd structure.");
  534. return new List<string>();
  535. }
  536. if (titleNumber.HasValue)
  537. {
  538. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  539. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  540. if (vobs.Count > 0)
  541. {
  542. var minSizeVobs = vobs
  543. .SkipWhile(f => f.Length < minPlayableSize)
  544. .ToList();
  545. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  546. }
  547. _logger.Debug("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  548. }
  549. var files = allVobs
  550. .SkipWhile(f => f.Length < minPlayableSize)
  551. .ToList();
  552. // If we didn't find any satisfying the min length, just take them all
  553. if (files.Count == 0)
  554. {
  555. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  556. files = allVobs;
  557. }
  558. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  559. if (files.Count > 0)
  560. {
  561. var parts = Path.GetFileNameWithoutExtension(files[0].FullName).Split('_');
  562. if (parts.Length == 3)
  563. {
  564. var title = parts[1];
  565. files = files.TakeWhile(f =>
  566. {
  567. var fileParts = Path.GetFileNameWithoutExtension(f.FullName).Split('_');
  568. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  569. }).ToList();
  570. // If this resulted in not getting any vobs, just take them all
  571. if (files.Count == 0)
  572. {
  573. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  574. files = allVobs;
  575. }
  576. }
  577. }
  578. return files.Select(i => i.FullName);
  579. }
  580. }
  581. }