FFProbeVideoInfo.cs 31 KB

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