FFProbeVideoInfo.cs 30 KB

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