FFProbeVideoInfo.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. // Don't use the embedded name for extras because it will often be the same name as the movie
  375. if (!video.ExtraType.HasValue && !video.IsOwnedItem)
  376. {
  377. video.Name = data.Name;
  378. }
  379. }
  380. }
  381. // If we don't have a ProductionYear try and get it from PremiereDate
  382. if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
  383. {
  384. video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
  385. }
  386. if (!video.LockedFields.Contains(MetadataFields.Overview))
  387. {
  388. if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
  389. {
  390. video.Overview = data.Overview;
  391. }
  392. }
  393. if (string.IsNullOrWhiteSpace(video.ShortOverview) || isFullRefresh)
  394. {
  395. video.ShortOverview = data.ShortOverview;
  396. }
  397. }
  398. private async Task FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
  399. {
  400. var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  401. if (!video.LockedFields.Contains(MetadataFields.Cast))
  402. {
  403. if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
  404. {
  405. var people = new List<PersonInfo>();
  406. foreach (var person in data.People)
  407. {
  408. PeopleHelper.AddPerson(people, new PersonInfo
  409. {
  410. Name = person.Name,
  411. Type = person.Type,
  412. Role = person.Role
  413. });
  414. }
  415. await _libraryManager.UpdatePeople(video, people);
  416. }
  417. }
  418. }
  419. private SubtitleOptions GetOptions()
  420. {
  421. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  422. }
  423. /// <summary>
  424. /// Adds the external subtitles.
  425. /// </summary>
  426. /// <param name="video">The video.</param>
  427. /// <param name="currentStreams">The current streams.</param>
  428. /// <param name="options">The options.</param>
  429. /// <param name="cancellationToken">The cancellation token.</param>
  430. /// <returns>Task.</returns>
  431. private async Task AddExternalSubtitles(Video video,
  432. List<MediaStream> currentStreams,
  433. MetadataRefreshOptions options,
  434. CancellationToken cancellationToken)
  435. {
  436. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  437. var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
  438. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false).ToList();
  439. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  440. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  441. var subtitleOptions = GetOptions();
  442. if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
  443. video is Episode) ||
  444. (subtitleOptions.DownloadMovieSubtitles &&
  445. video is Movie))
  446. {
  447. var downloadedLanguages = await new SubtitleDownloader(_logger,
  448. _subtitleManager)
  449. .DownloadSubtitles(video,
  450. currentStreams.Concat(externalSubtitleStreams).ToList(),
  451. subtitleOptions.SkipIfEmbeddedSubtitlesPresent,
  452. subtitleOptions.SkipIfAudioTrackMatches,
  453. subtitleOptions.RequirePerfectMatch,
  454. subtitleOptions.DownloadLanguages,
  455. cancellationToken).ConfigureAwait(false);
  456. // Rescan
  457. if (downloadedLanguages.Count > 0)
  458. {
  459. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true).ToList();
  460. }
  461. }
  462. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  463. currentStreams.AddRange(externalSubtitleStreams);
  464. }
  465. private async Task<List<ChapterInfo>> DownloadChapters(Video video, List<ChapterInfo> currentChapters, ChapterOptions options, CancellationToken cancellationToken)
  466. {
  467. if ((options.DownloadEpisodeChapters &&
  468. video is Episode) ||
  469. (options.DownloadMovieChapters &&
  470. video is Movie))
  471. {
  472. var results = await _chapterManager.Search(video, cancellationToken).ConfigureAwait(false);
  473. var result = results.FirstOrDefault();
  474. if (result != null)
  475. {
  476. var chapters = await _chapterManager.GetChapters(result.Id, cancellationToken).ConfigureAwait(false);
  477. var chapterInfos = chapters.Chapters.Select(i => new ChapterInfo
  478. {
  479. Name = i.Name,
  480. StartPositionTicks = i.StartPositionTicks
  481. }).ToList();
  482. if (chapterInfos.All(i => i.StartPositionTicks == 0))
  483. {
  484. if (currentChapters.Count >= chapterInfos.Count)
  485. {
  486. var index = 0;
  487. foreach (var info in chapterInfos)
  488. {
  489. info.StartPositionTicks = currentChapters[index].StartPositionTicks;
  490. index++;
  491. }
  492. }
  493. else
  494. {
  495. chapterInfos.Clear();
  496. }
  497. }
  498. return chapterInfos;
  499. }
  500. }
  501. return new List<ChapterInfo>();
  502. }
  503. /// <summary>
  504. /// The dummy chapter duration
  505. /// </summary>
  506. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  507. /// <summary>
  508. /// Adds the dummy chapters.
  509. /// </summary>
  510. /// <param name="video">The video.</param>
  511. /// <param name="chapters">The chapters.</param>
  512. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  513. {
  514. var runtime = video.RunTimeTicks ?? 0;
  515. if (runtime < 0)
  516. {
  517. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  518. }
  519. if (runtime < _dummyChapterDuration)
  520. {
  521. return;
  522. }
  523. long currentChapterTicks = 0;
  524. var index = 1;
  525. // Limit to 100 chapters just in case there's some incorrect metadata here
  526. while (currentChapterTicks < runtime && index < 100)
  527. {
  528. chapters.Add(new ChapterInfo
  529. {
  530. StartPositionTicks = currentChapterTicks
  531. });
  532. index++;
  533. currentChapterTicks += _dummyChapterDuration;
  534. }
  535. }
  536. /// <summary>
  537. /// Called when [pre fetch].
  538. /// </summary>
  539. /// <param name="item">The item.</param>
  540. /// <param name="mount">The mount.</param>
  541. /// <param name="blurayDiscInfo">The bluray disc information.</param>
  542. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  543. {
  544. if (item.VideoType == VideoType.Iso)
  545. {
  546. item.IsoType = DetermineIsoType(mount);
  547. }
  548. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  549. {
  550. FetchFromDvdLib(item, mount);
  551. }
  552. if (blurayDiscInfo != null)
  553. {
  554. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  555. }
  556. }
  557. private void FetchFromDvdLib(Video item, IIsoMount mount)
  558. {
  559. var path = mount == null ? item.Path : mount.MountedPath;
  560. var dvd = new Dvd(path);
  561. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  562. byte? titleNumber = null;
  563. if (primaryTitle != null)
  564. {
  565. titleNumber = primaryTitle.VideoTitleSetNumber;
  566. item.RunTimeTicks = GetRuntime(primaryTitle);
  567. }
  568. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  569. .Select(Path.GetFileName)
  570. .ToList();
  571. }
  572. private long GetRuntime(Title title)
  573. {
  574. return title.ProgramChains
  575. .Select(i => (TimeSpan)i.PlaybackTime)
  576. .Select(i => i.Ticks)
  577. .Sum();
  578. }
  579. /// <summary>
  580. /// Mounts the iso if needed.
  581. /// </summary>
  582. /// <param name="item">The item.</param>
  583. /// <param name="cancellationToken">The cancellation token.</param>
  584. /// <returns>IsoMount.</returns>
  585. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  586. {
  587. if (item.VideoType == VideoType.Iso)
  588. {
  589. return _isoManager.Mount(item.Path, cancellationToken);
  590. }
  591. return Task.FromResult<IIsoMount>(null);
  592. }
  593. /// <summary>
  594. /// Determines the type of the iso.
  595. /// </summary>
  596. /// <param name="isoMount">The iso mount.</param>
  597. /// <returns>System.Nullable{IsoType}.</returns>
  598. private IsoType? DetermineIsoType(IIsoMount isoMount)
  599. {
  600. var fileSystemEntries = Directory.EnumerateFileSystemEntries(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  601. if (fileSystemEntries.Contains("video_ts", StringComparer.OrdinalIgnoreCase) ||
  602. fileSystemEntries.Contains("VIDEO_TS.IFO", StringComparer.OrdinalIgnoreCase))
  603. {
  604. return IsoType.Dvd;
  605. }
  606. if (fileSystemEntries.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  607. {
  608. return IsoType.BluRay;
  609. }
  610. return null;
  611. }
  612. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  613. {
  614. // min size 300 mb
  615. const long minPlayableSize = 314572800;
  616. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  617. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  618. // Once we reach a file that is at least the minimum, return all subsequent ones
  619. var allVobs = _fileSystem.GetFiles(root, true)
  620. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  621. .OrderBy(i => i.FullName)
  622. .ToList();
  623. // If we didn't find any satisfying the min length, just take them all
  624. if (allVobs.Count == 0)
  625. {
  626. _logger.Error("No vobs found in dvd structure.");
  627. return new List<string>();
  628. }
  629. if (titleNumber.HasValue)
  630. {
  631. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  632. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  633. if (vobs.Count > 0)
  634. {
  635. var minSizeVobs = vobs
  636. .SkipWhile(f => f.Length < minPlayableSize)
  637. .ToList();
  638. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  639. }
  640. _logger.Info("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  641. }
  642. var files = allVobs
  643. .SkipWhile(f => f.Length < minPlayableSize)
  644. .ToList();
  645. // If we didn't find any satisfying the min length, just take them all
  646. if (files.Count == 0)
  647. {
  648. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  649. files = allVobs;
  650. }
  651. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  652. if (files.Count > 0)
  653. {
  654. var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
  655. if (parts.Length == 3)
  656. {
  657. var title = parts[1];
  658. files = files.TakeWhile(f =>
  659. {
  660. var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
  661. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  662. }).ToList();
  663. // If this resulted in not getting any vobs, just take them all
  664. if (files.Count == 0)
  665. {
  666. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  667. files = allVobs;
  668. }
  669. }
  670. }
  671. return files.Select(i => i.FullName);
  672. }
  673. }
  674. }