FFProbeVideoInfo.cs 29 KB

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