FFProbeVideoInfo.cs 29 KB

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