FFProbeVideoInfo.cs 28 KB

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