FFProbeVideoInfo.cs 29 KB

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