FFProbeVideoInfo.cs 28 KB

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