FFProbeVideoInfo.cs 29 KB

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