FFProbeVideoInfo.cs 27 KB

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