FFProbeVideoInfo.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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.Common.IO;
  29. using MediaBrowser.Controller.IO;
  30. using MediaBrowser.Model.IO;
  31. using MediaBrowser.Model.Globalization;
  32. namespace MediaBrowser.Providers.MediaInfo
  33. {
  34. public class FFProbeVideoInfo
  35. {
  36. private readonly ILogger _logger;
  37. private readonly IIsoManager _isoManager;
  38. private readonly IMediaEncoder _mediaEncoder;
  39. private readonly IItemRepository _itemRepo;
  40. private readonly IBlurayExaminer _blurayExaminer;
  41. private readonly ILocalizationManager _localization;
  42. private readonly IApplicationPaths _appPaths;
  43. private readonly IJsonSerializer _json;
  44. private readonly IEncodingManager _encodingManager;
  45. private readonly IFileSystem _fileSystem;
  46. private readonly IServerConfigurationManager _config;
  47. private readonly ISubtitleManager _subtitleManager;
  48. private readonly IChapterManager _chapterManager;
  49. private readonly ILibraryManager _libraryManager;
  50. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  51. 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)
  52. {
  53. _logger = logger;
  54. _isoManager = isoManager;
  55. _mediaEncoder = mediaEncoder;
  56. _itemRepo = itemRepo;
  57. _blurayExaminer = blurayExaminer;
  58. _localization = localization;
  59. _appPaths = appPaths;
  60. _json = json;
  61. _encodingManager = encodingManager;
  62. _fileSystem = fileSystem;
  63. _config = config;
  64. _subtitleManager = subtitleManager;
  65. _chapterManager = chapterManager;
  66. _libraryManager = libraryManager;
  67. }
  68. public async Task<ItemUpdateType> ProbeVideo<T>(T item,
  69. MetadataRefreshOptions options,
  70. CancellationToken cancellationToken)
  71. where T : Video
  72. {
  73. var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
  74. BlurayDiscInfo blurayDiscInfo = null;
  75. try
  76. {
  77. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  78. {
  79. var inputPath = isoMount != null ? isoMount.MountedPath : item.Path;
  80. blurayDiscInfo = GetBDInfo(inputPath);
  81. }
  82. OnPreFetch(item, isoMount, blurayDiscInfo);
  83. // If we didn't find any satisfying the min length, just take them all
  84. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  85. {
  86. if (item.PlayableStreamFileNames.Count == 0)
  87. {
  88. _logger.Error("No playable vobs found in dvd structure, skipping ffprobe.");
  89. return ItemUpdateType.MetadataImport;
  90. }
  91. }
  92. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  93. {
  94. if (item.PlayableStreamFileNames.Count == 0)
  95. {
  96. _logger.Error("No playable vobs found in bluray structure, skipping ffprobe.");
  97. return ItemUpdateType.MetadataImport;
  98. }
  99. }
  100. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  101. cancellationToken.ThrowIfCancellationRequested();
  102. await Fetch(item, cancellationToken, result, isoMount, blurayDiscInfo, options).ConfigureAwait(false);
  103. }
  104. finally
  105. {
  106. if (isoMount != null)
  107. {
  108. isoMount.Dispose();
  109. }
  110. }
  111. return ItemUpdateType.MetadataImport;
  112. }
  113. private const string SchemaVersion = "6";
  114. private async Task<Model.MediaInfo.MediaInfo> GetMediaInfo(Video item,
  115. IIsoMount isoMount,
  116. CancellationToken cancellationToken)
  117. {
  118. cancellationToken.ThrowIfCancellationRequested();
  119. var protocol = item.LocationType == LocationType.Remote
  120. ? MediaProtocol.Http
  121. : MediaProtocol.File;
  122. var result = await _mediaEncoder.GetMediaInfo(new MediaInfoRequest
  123. {
  124. PlayableStreamFileNames = item.PlayableStreamFileNames,
  125. MountedIso = isoMount,
  126. ExtractChapters = true,
  127. VideoType = item.VideoType,
  128. MediaType = DlnaProfileType.Video,
  129. InputPath = item.Path,
  130. Protocol = protocol
  131. }, cancellationToken).ConfigureAwait(false);
  132. //Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
  133. //_json.SerializeToFile(result, cachePath);
  134. return result;
  135. }
  136. protected async Task Fetch(Video video,
  137. CancellationToken cancellationToken,
  138. Model.MediaInfo.MediaInfo mediaInfo,
  139. IIsoMount isoMount,
  140. BlurayDiscInfo blurayInfo,
  141. MetadataRefreshOptions options)
  142. {
  143. var mediaStreams = mediaInfo.MediaStreams;
  144. video.TotalBitrate = mediaInfo.Bitrate;
  145. //video.FormatName = (mediaInfo.Container ?? string.Empty)
  146. // .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
  147. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  148. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  149. if (needToSetRuntime)
  150. {
  151. video.RunTimeTicks = mediaInfo.RunTimeTicks;
  152. }
  153. if (video.VideoType == VideoType.VideoFile)
  154. {
  155. var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');
  156. video.Container = extension;
  157. }
  158. else
  159. {
  160. video.Container = null;
  161. }
  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. FetchEmbeddedInfo(video, mediaInfo, options);
  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 libraryOptions = _libraryManager.GetLibraryOptions(video);
  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 options)
  286. {
  287. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  288. if (!video.LockedFields.Contains(MetadataFields.OfficialRating))
  289. {
  290. if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
  291. {
  292. video.OfficialRating = data.OfficialRating;
  293. }
  294. }
  295. if (!string.IsNullOrWhiteSpace(data.OfficialRatingDescription) || isFullRefresh)
  296. {
  297. video.OfficialRatingDescription = data.OfficialRatingDescription;
  298. }
  299. if (!video.LockedFields.Contains(MetadataFields.Genres))
  300. {
  301. if (video.Genres.Count == 0 || isFullRefresh)
  302. {
  303. video.Genres.Clear();
  304. foreach (var genre in data.Genres)
  305. {
  306. video.AddGenre(genre);
  307. }
  308. }
  309. }
  310. if (!video.LockedFields.Contains(MetadataFields.Studios))
  311. {
  312. if (video.Studios.Count == 0 || isFullRefresh)
  313. {
  314. video.Studios.Clear();
  315. foreach (var studio in data.Studios)
  316. {
  317. video.AddStudio(studio);
  318. }
  319. }
  320. }
  321. if (data.ProductionYear.HasValue)
  322. {
  323. if (!video.ProductionYear.HasValue || isFullRefresh)
  324. {
  325. video.ProductionYear = data.ProductionYear;
  326. }
  327. }
  328. if (data.PremiereDate.HasValue)
  329. {
  330. if (!video.PremiereDate.HasValue || isFullRefresh)
  331. {
  332. video.PremiereDate = data.PremiereDate;
  333. }
  334. }
  335. if (data.IndexNumber.HasValue)
  336. {
  337. if (!video.IndexNumber.HasValue || isFullRefresh)
  338. {
  339. video.IndexNumber = data.IndexNumber;
  340. }
  341. }
  342. if (data.ParentIndexNumber.HasValue)
  343. {
  344. if (!video.ParentIndexNumber.HasValue || isFullRefresh)
  345. {
  346. video.ParentIndexNumber = data.ParentIndexNumber;
  347. }
  348. }
  349. if (!string.IsNullOrWhiteSpace(data.Name))
  350. {
  351. if (string.IsNullOrWhiteSpace(video.Name) || (string.Equals(video.Name, Path.GetFileNameWithoutExtension(video.Path), StringComparison.OrdinalIgnoreCase) && !video.ProviderIds.Any()))
  352. {
  353. // Don't use the embedded name for extras because it will often be the same name as the movie
  354. if (!video.ExtraType.HasValue && !video.IsOwnedItem)
  355. {
  356. video.Name = data.Name;
  357. }
  358. }
  359. }
  360. // If we don't have a ProductionYear try and get it from PremiereDate
  361. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  362. {
  363. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  364. }
  365. if (!video.LockedFields.Contains(MetadataFields.Overview))
  366. {
  367. if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
  368. {
  369. video.Overview = data.Overview;
  370. }
  371. }
  372. if (string.IsNullOrWhiteSpace(video.ShortOverview) || isFullRefresh)
  373. {
  374. video.ShortOverview = data.ShortOverview;
  375. }
  376. }
  377. private async Task FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  378. {
  379. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  380. if (!video.LockedFields.Contains(MetadataFields.Cast))
  381. {
  382. if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
  383. {
  384. var people = new List<PersonInfo>();
  385. foreach (var person in data.People)
  386. {
  387. PeopleHelper.AddPerson(people, new PersonInfo
  388. {
  389. Name = person.Name,
  390. Type = person.Type,
  391. Role = person.Role
  392. });
  393. }
  394. await _libraryManager.UpdatePeople(video, people);
  395. }
  396. }
  397. }
  398. private SubtitleOptions GetOptions()
  399. {
  400. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  401. }
  402. /// <summary>
  403. /// Adds the external subtitles.
  404. /// </summary>
  405. /// <param name="video">The video.</param>
  406. /// <param name="currentStreams">The current streams.</param>
  407. /// <param name="options">The options.</param>
  408. /// <param name="cancellationToken">The cancellation token.</param>
  409. /// <returns>Task.</returns>
  410. private async Task AddExternalSubtitles(Video video,
  411. List<MediaStream> currentStreams,
  412. MetadataRefreshOptions options,
  413. CancellationToken cancellationToken)
  414. {
  415. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  416. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  417. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false).ToList();
  418. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  419. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  420. var subtitleOptions = GetOptions();
  421. if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
  422. video is Episode) ||
  423. (subtitleOptions.DownloadMovieSubtitles &&
  424. video is Movie))
  425. {
  426. var downloadedLanguages = await new SubtitleDownloader(_logger,
  427. _subtitleManager)
  428. .DownloadSubtitles(video,
  429. currentStreams.Concat(externalSubtitleStreams).ToList(),
  430. subtitleOptions.SkipIfEmbeddedSubtitlesPresent,
  431. subtitleOptions.SkipIfAudioTrackMatches,
  432. subtitleOptions.RequirePerfectMatch,
  433. subtitleOptions.DownloadLanguages,
  434. cancellationToken).ConfigureAwait(false);
  435. // Rescan
  436. if (downloadedLanguages.Count > 0)
  437. {
  438. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true).ToList();
  439. }
  440. }
  441. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  442. currentStreams.AddRange(externalSubtitleStreams);
  443. }
  444. /// <summary>
  445. /// The dummy chapter duration
  446. /// </summary>
  447. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  448. /// <summary>
  449. /// Adds the dummy chapters.
  450. /// </summary>
  451. /// <param name="video">The video.</param>
  452. /// <param name="chapters">The chapters.</param>
  453. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  454. {
  455. var runtime = video.RunTimeTicks ?? 0;
  456. if (runtime < 0)
  457. {
  458. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  459. }
  460. if (runtime < _dummyChapterDuration)
  461. {
  462. return;
  463. }
  464. long currentChapterTicks = 0;
  465. var index = 1;
  466. // Limit to 100 chapters just in case there's some incorrect metadata here
  467. while (currentChapterTicks < runtime && index < 100)
  468. {
  469. chapters.Add(new ChapterInfo
  470. {
  471. StartPositionTicks = currentChapterTicks
  472. });
  473. index++;
  474. currentChapterTicks += _dummyChapterDuration;
  475. }
  476. }
  477. /// <summary>
  478. /// Called when [pre fetch].
  479. /// </summary>
  480. /// <param name="item">The item.</param>
  481. /// <param name="mount">The mount.</param>
  482. /// <param name="blurayDiscInfo">The bluray disc information.</param>
  483. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  484. {
  485. if (item.VideoType == VideoType.Iso)
  486. {
  487. item.IsoType = DetermineIsoType(mount);
  488. }
  489. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  490. {
  491. FetchFromDvdLib(item, mount);
  492. }
  493. if (blurayDiscInfo != null)
  494. {
  495. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  496. }
  497. }
  498. private void FetchFromDvdLib(Video item, IIsoMount mount)
  499. {
  500. var path = mount == null ? item.Path : mount.MountedPath;
  501. var dvd = new Dvd(path, _fileSystem);
  502. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  503. byte? titleNumber = null;
  504. if (primaryTitle != null)
  505. {
  506. titleNumber = primaryTitle.VideoTitleSetNumber;
  507. item.RunTimeTicks = GetRuntime(primaryTitle);
  508. }
  509. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  510. .Select(Path.GetFileName)
  511. .ToList();
  512. }
  513. private long GetRuntime(Title title)
  514. {
  515. return title.ProgramChains
  516. .Select(i => (TimeSpan)i.PlaybackTime)
  517. .Select(i => i.Ticks)
  518. .Sum();
  519. }
  520. /// <summary>
  521. /// Mounts the iso if needed.
  522. /// </summary>
  523. /// <param name="item">The item.</param>
  524. /// <param name="cancellationToken">The cancellation token.</param>
  525. /// <returns>IsoMount.</returns>
  526. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  527. {
  528. if (item.VideoType == VideoType.Iso)
  529. {
  530. return _isoManager.Mount(item.Path, cancellationToken);
  531. }
  532. return Task.FromResult<IIsoMount>(null);
  533. }
  534. /// <summary>
  535. /// Determines the type of the iso.
  536. /// </summary>
  537. /// <param name="isoMount">The iso mount.</param>
  538. /// <returns>System.Nullable{IsoType}.</returns>
  539. private IsoType? DetermineIsoType(IIsoMount isoMount)
  540. {
  541. var fileSystemEntries = _fileSystem.GetFileSystemEntryPaths(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  542. if (fileSystemEntries.Contains("video_ts", StringComparer.OrdinalIgnoreCase) ||
  543. fileSystemEntries.Contains("VIDEO_TS.IFO", StringComparer.OrdinalIgnoreCase))
  544. {
  545. return IsoType.Dvd;
  546. }
  547. if (fileSystemEntries.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  548. {
  549. return IsoType.BluRay;
  550. }
  551. return null;
  552. }
  553. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  554. {
  555. // min size 300 mb
  556. const long minPlayableSize = 314572800;
  557. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  558. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  559. // Once we reach a file that is at least the minimum, return all subsequent ones
  560. var allVobs = _fileSystem.GetFiles(root, true)
  561. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  562. .OrderBy(i => i.FullName)
  563. .ToList();
  564. // If we didn't find any satisfying the min length, just take them all
  565. if (allVobs.Count == 0)
  566. {
  567. _logger.Error("No vobs found in dvd structure.");
  568. return new List<string>();
  569. }
  570. if (titleNumber.HasValue)
  571. {
  572. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  573. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  574. if (vobs.Count > 0)
  575. {
  576. var minSizeVobs = vobs
  577. .SkipWhile(f => f.Length < minPlayableSize)
  578. .ToList();
  579. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  580. }
  581. _logger.Info("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  582. }
  583. var files = allVobs
  584. .SkipWhile(f => f.Length < minPlayableSize)
  585. .ToList();
  586. // If we didn't find any satisfying the min length, just take them all
  587. if (files.Count == 0)
  588. {
  589. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  590. files = allVobs;
  591. }
  592. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  593. if (files.Count > 0)
  594. {
  595. var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
  596. if (parts.Length == 3)
  597. {
  598. var title = parts[1];
  599. files = files.TakeWhile(f =>
  600. {
  601. var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
  602. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  603. }).ToList();
  604. // If this resulted in not getting any vobs, just take them all
  605. if (files.Count == 0)
  606. {
  607. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  608. files = allVobs;
  609. }
  610. }
  611. }
  612. return files.Select(i => i.FullName);
  613. }
  614. }
  615. }