FFProbeVideoInfo.cs 30 KB

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