FFProbeVideoInfo.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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 (blurayInfo != null)
  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 >= 1260);
  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. try
  299. {
  300. return _blurayExaminer.GetDiscInfo(path);
  301. }
  302. catch (Exception ex)
  303. {
  304. _logger.ErrorException("Error getting BDInfo", ex);
  305. return null;
  306. }
  307. }
  308. private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  309. {
  310. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  311. if (!video.LockedFields.Contains(MetadataFields.OfficialRating))
  312. {
  313. if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
  314. {
  315. video.OfficialRating = data.OfficialRating;
  316. }
  317. }
  318. if (!video.LockedFields.Contains(MetadataFields.Genres))
  319. {
  320. if (video.Genres.Count == 0 || isFullRefresh)
  321. {
  322. video.Genres.Clear();
  323. foreach (var genre in data.Genres)
  324. {
  325. video.AddGenre(genre);
  326. }
  327. }
  328. }
  329. if (!video.LockedFields.Contains(MetadataFields.Studios))
  330. {
  331. if (video.Studios.Count == 0 || isFullRefresh)
  332. {
  333. video.Studios.Clear();
  334. foreach (var studio in data.Studios)
  335. {
  336. video.AddStudio(studio);
  337. }
  338. }
  339. }
  340. if (data.ProductionYear.HasValue)
  341. {
  342. if (!video.ProductionYear.HasValue || isFullRefresh)
  343. {
  344. video.ProductionYear = data.ProductionYear;
  345. }
  346. }
  347. if (data.PremiereDate.HasValue)
  348. {
  349. if (!video.PremiereDate.HasValue || isFullRefresh)
  350. {
  351. video.PremiereDate = data.PremiereDate;
  352. }
  353. }
  354. if (data.IndexNumber.HasValue)
  355. {
  356. if (!video.IndexNumber.HasValue || isFullRefresh)
  357. {
  358. video.IndexNumber = data.IndexNumber;
  359. }
  360. }
  361. if (data.ParentIndexNumber.HasValue)
  362. {
  363. if (!video.ParentIndexNumber.HasValue || isFullRefresh)
  364. {
  365. video.ParentIndexNumber = data.ParentIndexNumber;
  366. }
  367. }
  368. // If we don't have a ProductionYear try and get it from PremiereDate
  369. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  370. {
  371. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  372. }
  373. if (!video.LockedFields.Contains(MetadataFields.Overview))
  374. {
  375. if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
  376. {
  377. video.Overview = data.Overview;
  378. }
  379. }
  380. }
  381. private async Task FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  382. {
  383. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  384. if (!video.LockedFields.Contains(MetadataFields.Cast))
  385. {
  386. if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
  387. {
  388. var people = new List<PersonInfo>();
  389. foreach (var person in data.People)
  390. {
  391. PeopleHelper.AddPerson(people, new PersonInfo
  392. {
  393. Name = person.Name,
  394. Type = person.Type,
  395. Role = person.Role
  396. });
  397. }
  398. await _libraryManager.UpdatePeople(video, people);
  399. }
  400. }
  401. }
  402. private SubtitleOptions GetOptions()
  403. {
  404. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  405. }
  406. /// <summary>
  407. /// Adds the external subtitles.
  408. /// </summary>
  409. /// <param name="video">The video.</param>
  410. /// <param name="currentStreams">The current streams.</param>
  411. /// <param name="options">The options.</param>
  412. /// <param name="cancellationToken">The cancellation token.</param>
  413. /// <returns>Task.</returns>
  414. private async Task AddExternalSubtitles(Video video,
  415. List<MediaStream> currentStreams,
  416. MetadataRefreshOptions options,
  417. CancellationToken cancellationToken)
  418. {
  419. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  420. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  421. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false).ToList();
  422. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  423. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  424. var subtitleOptions = GetOptions();
  425. if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
  426. video is Episode) ||
  427. (subtitleOptions.DownloadMovieSubtitles &&
  428. video is Movie))
  429. {
  430. var downloadedLanguages = await new SubtitleDownloader(_logger,
  431. _subtitleManager)
  432. .DownloadSubtitles(video,
  433. currentStreams.Concat(externalSubtitleStreams).ToList(),
  434. subtitleOptions.SkipIfGraphicalSubtitlesPresent,
  435. subtitleOptions.SkipIfAudioTrackMatches,
  436. subtitleOptions.DownloadLanguages,
  437. cancellationToken).ConfigureAwait(false);
  438. // Rescan
  439. if (downloadedLanguages.Count > 0)
  440. {
  441. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true).ToList();
  442. }
  443. }
  444. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  445. currentStreams.AddRange(externalSubtitleStreams);
  446. }
  447. private async Task<List<ChapterInfo>> DownloadChapters(Video video, List<ChapterInfo> currentChapters, ChapterOptions options, CancellationToken cancellationToken)
  448. {
  449. if ((options.DownloadEpisodeChapters &&
  450. video is Episode) ||
  451. (options.DownloadMovieChapters &&
  452. video is Movie))
  453. {
  454. var results = await _chapterManager.Search(video, cancellationToken).ConfigureAwait(false);
  455. var result = results.FirstOrDefault();
  456. if (result != null)
  457. {
  458. var chapters = await _chapterManager.GetChapters(result.Id, cancellationToken).ConfigureAwait(false);
  459. var chapterInfos = chapters.Chapters.Select(i => new ChapterInfo
  460. {
  461. Name = i.Name,
  462. StartPositionTicks = i.StartPositionTicks
  463. }).ToList();
  464. if (chapterInfos.All(i => i.StartPositionTicks == 0))
  465. {
  466. if (currentChapters.Count >= chapterInfos.Count)
  467. {
  468. var index = 0;
  469. foreach (var info in chapterInfos)
  470. {
  471. info.StartPositionTicks = currentChapters[index].StartPositionTicks;
  472. index++;
  473. }
  474. }
  475. else
  476. {
  477. chapterInfos.Clear();
  478. }
  479. }
  480. return chapterInfos;
  481. }
  482. }
  483. return new List<ChapterInfo>();
  484. }
  485. /// <summary>
  486. /// The dummy chapter duration
  487. /// </summary>
  488. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  489. /// <summary>
  490. /// Adds the dummy chapters.
  491. /// </summary>
  492. /// <param name="video">The video.</param>
  493. /// <param name="chapters">The chapters.</param>
  494. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  495. {
  496. var runtime = video.RunTimeTicks ?? 0;
  497. if (runtime < 0)
  498. {
  499. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  500. }
  501. if (runtime < _dummyChapterDuration)
  502. {
  503. return;
  504. }
  505. long currentChapterTicks = 0;
  506. var index = 1;
  507. // Limit to 100 chapters just in case there's some incorrect metadata here
  508. while (currentChapterTicks < runtime && index < 100)
  509. {
  510. chapters.Add(new ChapterInfo
  511. {
  512. StartPositionTicks = currentChapterTicks
  513. });
  514. index++;
  515. currentChapterTicks += _dummyChapterDuration;
  516. }
  517. }
  518. /// <summary>
  519. /// Called when [pre fetch].
  520. /// </summary>
  521. /// <param name="item">The item.</param>
  522. /// <param name="mount">The mount.</param>
  523. /// <param name="blurayDiscInfo">The bluray disc information.</param>
  524. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  525. {
  526. if (item.VideoType == VideoType.Iso)
  527. {
  528. item.IsoType = DetermineIsoType(mount);
  529. }
  530. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  531. {
  532. FetchFromDvdLib(item, mount);
  533. }
  534. if (blurayDiscInfo != null)
  535. {
  536. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  537. }
  538. }
  539. private void FetchFromDvdLib(Video item, IIsoMount mount)
  540. {
  541. var path = mount == null ? item.Path : mount.MountedPath;
  542. var dvd = new Dvd(path);
  543. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  544. byte? titleNumber = null;
  545. if (primaryTitle != null)
  546. {
  547. titleNumber = primaryTitle.VideoTitleSetNumber;
  548. item.RunTimeTicks = GetRuntime(primaryTitle);
  549. }
  550. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  551. .Select(Path.GetFileName)
  552. .ToList();
  553. }
  554. private long GetRuntime(Title title)
  555. {
  556. return title.ProgramChains
  557. .Select(i => (TimeSpan)i.PlaybackTime)
  558. .Select(i => i.Ticks)
  559. .Sum();
  560. }
  561. /// <summary>
  562. /// Mounts the iso if needed.
  563. /// </summary>
  564. /// <param name="item">The item.</param>
  565. /// <param name="cancellationToken">The cancellation token.</param>
  566. /// <returns>IsoMount.</returns>
  567. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  568. {
  569. if (item.VideoType == VideoType.Iso)
  570. {
  571. return _isoManager.Mount(item.Path, cancellationToken);
  572. }
  573. return Task.FromResult<IIsoMount>(null);
  574. }
  575. /// <summary>
  576. /// Determines the type of the iso.
  577. /// </summary>
  578. /// <param name="isoMount">The iso mount.</param>
  579. /// <returns>System.Nullable{IsoType}.</returns>
  580. private IsoType? DetermineIsoType(IIsoMount isoMount)
  581. {
  582. var fileSystemEntries = Directory.EnumerateFileSystemEntries(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  583. if (fileSystemEntries.Contains("video_ts", StringComparer.OrdinalIgnoreCase) ||
  584. fileSystemEntries.Contains("VIDEO_TS.IFO", StringComparer.OrdinalIgnoreCase))
  585. {
  586. return IsoType.Dvd;
  587. }
  588. if (fileSystemEntries.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  589. {
  590. return IsoType.BluRay;
  591. }
  592. return null;
  593. }
  594. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  595. {
  596. // min size 300 mb
  597. const long minPlayableSize = 314572800;
  598. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  599. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  600. // Once we reach a file that is at least the minimum, return all subsequent ones
  601. var allVobs = _fileSystem.GetFiles(root, true)
  602. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  603. .OrderBy(i => i.FullName)
  604. .ToList();
  605. // If we didn't find any satisfying the min length, just take them all
  606. if (allVobs.Count == 0)
  607. {
  608. _logger.Error("No vobs found in dvd structure.");
  609. return new List<string>();
  610. }
  611. if (titleNumber.HasValue)
  612. {
  613. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  614. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  615. if (vobs.Count > 0)
  616. {
  617. var minSizeVobs = vobs
  618. .SkipWhile(f => f.Length < minPlayableSize)
  619. .ToList();
  620. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  621. }
  622. _logger.Info("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  623. }
  624. var files = allVobs
  625. .SkipWhile(f => f.Length < minPlayableSize)
  626. .ToList();
  627. // If we didn't find any satisfying the min length, just take them all
  628. if (files.Count == 0)
  629. {
  630. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  631. files = allVobs;
  632. }
  633. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  634. if (files.Count > 0)
  635. {
  636. var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
  637. if (parts.Length == 3)
  638. {
  639. var title = parts[1];
  640. files = files.TakeWhile(f =>
  641. {
  642. var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
  643. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  644. }).ToList();
  645. // If this resulted in not getting any vobs, just take them all
  646. if (files.Count == 0)
  647. {
  648. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  649. files = allVobs;
  650. }
  651. }
  652. }
  653. return files.Select(i => i.FullName);
  654. }
  655. }
  656. }