FFProbeVideoInfo.cs 30 KB

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