FFProbeVideoInfo.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. using DvdLib.Ifo;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Controller.Chapters;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Movies;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.Localization;
  12. using MediaBrowser.Controller.MediaEncoding;
  13. using MediaBrowser.Controller.Persistence;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Controller.Subtitles;
  16. using MediaBrowser.Model.Configuration;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.MediaInfo;
  21. using MediaBrowser.Model.Providers;
  22. using MediaBrowser.Model.Serialization;
  23. using System;
  24. using System.Collections.Generic;
  25. using System.Globalization;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  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 CultureInfo _usCulture = new CultureInfo("en-US");
  48. 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)
  49. {
  50. _logger = logger;
  51. _isoManager = isoManager;
  52. _mediaEncoder = mediaEncoder;
  53. _itemRepo = itemRepo;
  54. _blurayExaminer = blurayExaminer;
  55. _localization = localization;
  56. _appPaths = appPaths;
  57. _json = json;
  58. _encodingManager = encodingManager;
  59. _fileSystem = fileSystem;
  60. _config = config;
  61. _subtitleManager = subtitleManager;
  62. _chapterManager = chapterManager;
  63. }
  64. public async Task<ItemUpdateType> ProbeVideo<T>(T item,
  65. MetadataRefreshOptions options,
  66. CancellationToken cancellationToken)
  67. where T : Video
  68. {
  69. var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
  70. BlurayDiscInfo blurayDiscInfo = null;
  71. try
  72. {
  73. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  74. {
  75. var inputPath = isoMount != null ? isoMount.MountedPath : item.Path;
  76. blurayDiscInfo = GetBDInfo(inputPath);
  77. }
  78. OnPreFetch(item, isoMount, blurayDiscInfo);
  79. // If we didn't find any satisfying the min length, just take them all
  80. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  81. {
  82. if (item.PlayableStreamFileNames.Count == 0)
  83. {
  84. _logger.Error("No playable vobs found in dvd structure, skipping ffprobe.");
  85. return ItemUpdateType.MetadataImport;
  86. }
  87. }
  88. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
  89. {
  90. if (item.PlayableStreamFileNames.Count == 0)
  91. {
  92. _logger.Error("No playable vobs found in bluray structure, skipping ffprobe.");
  93. return ItemUpdateType.MetadataImport;
  94. }
  95. }
  96. var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
  97. cancellationToken.ThrowIfCancellationRequested();
  98. FFProbeHelpers.NormalizeFFProbeResult(result);
  99. cancellationToken.ThrowIfCancellationRequested();
  100. await Fetch(item, cancellationToken, result, isoMount, blurayDiscInfo, options).ConfigureAwait(false);
  101. }
  102. finally
  103. {
  104. if (isoMount != null)
  105. {
  106. isoMount.Dispose();
  107. }
  108. }
  109. return ItemUpdateType.MetadataImport;
  110. }
  111. private const string SchemaVersion = "1";
  112. private async Task<InternalMediaInfoResult> GetMediaInfo(Video item,
  113. IIsoMount isoMount,
  114. CancellationToken cancellationToken)
  115. {
  116. cancellationToken.ThrowIfCancellationRequested();
  117. var idString = item.Id.ToString("N");
  118. var cachePath = Path.Combine(_appPaths.CachePath,
  119. "ffprobe-video",
  120. idString.Substring(0, 2), idString, "v" + SchemaVersion + _mediaEncoder.Version + item.DateModified.Ticks.ToString(_usCulture) + ".json");
  121. try
  122. {
  123. return _json.DeserializeFromFile<InternalMediaInfoResult>(cachePath);
  124. }
  125. catch (FileNotFoundException)
  126. {
  127. }
  128. catch (DirectoryNotFoundException)
  129. {
  130. }
  131. var protocol = item.LocationType == LocationType.Remote
  132. ? MediaProtocol.Http
  133. : MediaProtocol.File;
  134. var inputPath = MediaEncoderHelpers.GetInputArgument(item.Path, protocol, isoMount, item.PlayableStreamFileNames);
  135. var result = await _mediaEncoder.GetMediaInfo(inputPath, protocol, false, cancellationToken).ConfigureAwait(false);
  136. Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
  137. _json.SerializeToFile(result, cachePath);
  138. return result;
  139. }
  140. protected async Task Fetch(Video video,
  141. CancellationToken cancellationToken,
  142. InternalMediaInfoResult data,
  143. IIsoMount isoMount,
  144. BlurayDiscInfo blurayInfo,
  145. MetadataRefreshOptions options)
  146. {
  147. var mediaInfo = MediaEncoderHelpers.GetMediaInfo(data);
  148. var mediaStreams = mediaInfo.MediaStreams;
  149. video.TotalBitrate = mediaInfo.TotalBitrate;
  150. video.FormatName = (mediaInfo.Format ?? string.Empty)
  151. .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
  152. if (data.format != null)
  153. {
  154. // For dvd's this may not always be accurate, so don't set the runtime if the item already has one
  155. var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
  156. if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
  157. {
  158. video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
  159. }
  160. if (video.VideoType == VideoType.VideoFile)
  161. {
  162. var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');
  163. video.Container = extension;
  164. }
  165. else
  166. {
  167. video.Container = null;
  168. }
  169. if (!string.IsNullOrEmpty(data.format.size))
  170. {
  171. video.Size = long.Parse(data.format.size, _usCulture);
  172. }
  173. else
  174. {
  175. video.Size = null;
  176. }
  177. }
  178. var mediaChapters = (data.Chapters ?? new MediaChapter[] { }).ToList();
  179. var chapters = mediaChapters.Select(GetChapterInfo).ToList();
  180. if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
  181. {
  182. FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
  183. }
  184. await AddExternalSubtitles(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
  185. FetchWtvInfo(video, data);
  186. video.IsHD = mediaStreams.Any(i => i.Type == MediaStreamType.Video && i.Width.HasValue && i.Width.Value >= 1270);
  187. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  188. video.VideoBitRate = videoStream == null ? null : videoStream.BitRate;
  189. video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;
  190. video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
  191. ExtractTimestamp(video);
  192. await _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken).ConfigureAwait(false);
  193. if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh ||
  194. options.MetadataRefreshMode == MetadataRefreshMode.Default)
  195. {
  196. var chapterOptions = _chapterManager.GetConfiguration();
  197. try
  198. {
  199. var remoteChapters = await DownloadChapters(video, chapters, chapterOptions, cancellationToken).ConfigureAwait(false);
  200. if (remoteChapters.Count > 0)
  201. {
  202. chapters = remoteChapters;
  203. }
  204. }
  205. catch (Exception ex)
  206. {
  207. _logger.ErrorException("Error downloading chapters", ex);
  208. }
  209. if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
  210. {
  211. AddDummyChapters(video, chapters);
  212. }
  213. NormalizeChapterNames(chapters);
  214. await _encodingManager.RefreshChapterImages(new ChapterImageRefreshOptions
  215. {
  216. Chapters = chapters,
  217. Video = video,
  218. ExtractImages = chapterOptions.ExtractDuringLibraryScan,
  219. SaveChapters = false
  220. }, cancellationToken).ConfigureAwait(false);
  221. await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
  222. }
  223. }
  224. private void NormalizeChapterNames(List<ChapterInfo> chapters)
  225. {
  226. var index = 1;
  227. foreach (var chapter in chapters)
  228. {
  229. TimeSpan time;
  230. // Check if the name is empty and/or if the name is a time
  231. // Some ripping programs do that.
  232. if (string.IsNullOrWhiteSpace(chapter.Name) ||
  233. TimeSpan.TryParse(chapter.Name, out time))
  234. {
  235. chapter.Name = string.Format(_localization.GetLocalizedString("LabelChapterName"), index.ToString(CultureInfo.InvariantCulture));
  236. }
  237. index++;
  238. }
  239. }
  240. private ChapterInfo GetChapterInfo(MediaChapter chapter)
  241. {
  242. var info = new ChapterInfo();
  243. if (chapter.tags != null)
  244. {
  245. string name;
  246. if (chapter.tags.TryGetValue("title", out name))
  247. {
  248. info.Name = name;
  249. }
  250. }
  251. // Limit accuracy to milliseconds to match xml saving
  252. var secondsString = chapter.start_time;
  253. double seconds;
  254. if (double.TryParse(secondsString, NumberStyles.Any, CultureInfo.InvariantCulture, out seconds))
  255. {
  256. var ms = Math.Round(TimeSpan.FromSeconds(seconds).TotalMilliseconds);
  257. info.StartPositionTicks = TimeSpan.FromMilliseconds(ms).Ticks;
  258. }
  259. return info;
  260. }
  261. private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
  262. {
  263. var video = (Video)item;
  264. int? currentHeight = null;
  265. int? currentWidth = null;
  266. int? currentBitRate = null;
  267. var videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  268. // Grab the values that ffprobe recorded
  269. if (videoStream != null)
  270. {
  271. currentBitRate = videoStream.BitRate;
  272. currentWidth = videoStream.Width;
  273. currentHeight = videoStream.Height;
  274. }
  275. // Fill video properties from the BDInfo result
  276. mediaStreams.Clear();
  277. mediaStreams.AddRange(blurayInfo.MediaStreams);
  278. video.MainFeaturePlaylistName = blurayInfo.PlaylistName;
  279. if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
  280. {
  281. video.RunTimeTicks = blurayInfo.RunTimeTicks;
  282. }
  283. video.PlayableStreamFileNames = blurayInfo.Files.ToList();
  284. if (blurayInfo.Chapters != null)
  285. {
  286. chapters.Clear();
  287. chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
  288. {
  289. StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
  290. }));
  291. }
  292. videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
  293. // Use the ffprobe values if these are empty
  294. if (videoStream != null)
  295. {
  296. videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
  297. videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
  298. videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
  299. }
  300. }
  301. private bool IsEmpty(int? num)
  302. {
  303. return !num.HasValue || num.Value == 0;
  304. }
  305. /// <summary>
  306. /// Gets information about the longest playlist on a bdrom
  307. /// </summary>
  308. /// <param name="path">The path.</param>
  309. /// <returns>VideoStream.</returns>
  310. private BlurayDiscInfo GetBDInfo(string path)
  311. {
  312. return _blurayExaminer.GetDiscInfo(path);
  313. }
  314. private void FetchWtvInfo(Video video, InternalMediaInfoResult data)
  315. {
  316. if (data.format == null || data.format.tags == null)
  317. {
  318. return;
  319. }
  320. if (video.Genres.Count == 0)
  321. {
  322. if (!video.LockedFields.Contains(MetadataFields.Genres))
  323. {
  324. var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "genre");
  325. if (!string.IsNullOrEmpty(genres))
  326. {
  327. video.Genres = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
  328. .Where(i => !string.IsNullOrWhiteSpace(i))
  329. .Select(i => i.Trim())
  330. .ToList();
  331. }
  332. }
  333. }
  334. if (string.IsNullOrEmpty(video.Overview))
  335. {
  336. if (!video.LockedFields.Contains(MetadataFields.Overview))
  337. {
  338. var overview = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");
  339. if (!string.IsNullOrWhiteSpace(overview))
  340. {
  341. video.Overview = overview;
  342. }
  343. }
  344. }
  345. if (string.IsNullOrEmpty(video.OfficialRating))
  346. {
  347. var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");
  348. if (!string.IsNullOrWhiteSpace(officialRating))
  349. {
  350. if (!video.LockedFields.Contains(MetadataFields.OfficialRating))
  351. {
  352. video.OfficialRating = officialRating;
  353. }
  354. }
  355. }
  356. if (video.People.Count == 0)
  357. {
  358. if (!video.LockedFields.Contains(MetadataFields.Cast))
  359. {
  360. var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");
  361. if (!string.IsNullOrEmpty(people))
  362. {
  363. video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
  364. .Where(i => !string.IsNullOrWhiteSpace(i))
  365. .Select(i => new PersonInfo { Name = i.Trim(), Type = PersonType.Actor })
  366. .ToList();
  367. }
  368. }
  369. }
  370. if (!video.ProductionYear.HasValue)
  371. {
  372. var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");
  373. if (!string.IsNullOrWhiteSpace(year))
  374. {
  375. int val;
  376. if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
  377. {
  378. video.ProductionYear = val;
  379. }
  380. }
  381. }
  382. }
  383. private SubtitleOptions GetOptions()
  384. {
  385. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  386. }
  387. /// <summary>
  388. /// Adds the external subtitles.
  389. /// </summary>
  390. /// <param name="video">The video.</param>
  391. /// <param name="currentStreams">The current streams.</param>
  392. /// <param name="options">The options.</param>
  393. /// <param name="cancellationToken">The cancellation token.</param>
  394. /// <returns>Task.</returns>
  395. private async Task AddExternalSubtitles(Video video,
  396. List<MediaStream> currentStreams,
  397. MetadataRefreshOptions options,
  398. CancellationToken cancellationToken)
  399. {
  400. var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
  401. var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, currentStreams.Count, options.DirectoryService, false).ToList();
  402. var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
  403. options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
  404. var subtitleOptions = GetOptions();
  405. if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
  406. video is Episode) ||
  407. (subtitleOptions.DownloadMovieSubtitles &&
  408. video is Movie))
  409. {
  410. var downloadedLanguages = await new SubtitleDownloader(_logger,
  411. _subtitleManager)
  412. .DownloadSubtitles(video,
  413. currentStreams.Concat(externalSubtitleStreams).ToList(),
  414. subtitleOptions.SkipIfGraphicalSubtitlesPresent,
  415. subtitleOptions.SkipIfAudioTrackMatches,
  416. subtitleOptions.DownloadLanguages,
  417. cancellationToken).ConfigureAwait(false);
  418. // Rescan
  419. if (downloadedLanguages.Count > 0)
  420. {
  421. externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, currentStreams.Count, options.DirectoryService, true).ToList();
  422. }
  423. }
  424. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  425. currentStreams.AddRange(externalSubtitleStreams);
  426. }
  427. private async Task<List<ChapterInfo>> DownloadChapters(Video video, List<ChapterInfo> currentChapters, ChapterOptions options, CancellationToken cancellationToken)
  428. {
  429. if ((options.DownloadEpisodeChapters &&
  430. video is Episode) ||
  431. (options.DownloadMovieChapters &&
  432. video is Movie))
  433. {
  434. var results = await _chapterManager.Search(video, cancellationToken).ConfigureAwait(false);
  435. var result = results.FirstOrDefault();
  436. if (result != null)
  437. {
  438. var chapters = await _chapterManager.GetChapters(result.Id, cancellationToken).ConfigureAwait(false);
  439. var chapterInfos = chapters.Chapters.Select(i => new ChapterInfo
  440. {
  441. Name = i.Name,
  442. StartPositionTicks = i.StartPositionTicks
  443. }).ToList();
  444. if (chapterInfos.All(i => i.StartPositionTicks == 0))
  445. {
  446. if (currentChapters.Count >= chapterInfos.Count)
  447. {
  448. var index = 0;
  449. foreach (var info in chapterInfos)
  450. {
  451. info.StartPositionTicks = currentChapters[index].StartPositionTicks;
  452. index++;
  453. }
  454. }
  455. else
  456. {
  457. chapterInfos.Clear();
  458. }
  459. }
  460. return chapterInfos;
  461. }
  462. }
  463. return new List<ChapterInfo>();
  464. }
  465. /// <summary>
  466. /// The dummy chapter duration
  467. /// </summary>
  468. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  469. /// <summary>
  470. /// Adds the dummy chapters.
  471. /// </summary>
  472. /// <param name="video">The video.</param>
  473. /// <param name="chapters">The chapters.</param>
  474. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  475. {
  476. var runtime = video.RunTimeTicks ?? 0;
  477. if (runtime < 0)
  478. {
  479. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  480. }
  481. if (runtime < _dummyChapterDuration)
  482. {
  483. return;
  484. }
  485. long currentChapterTicks = 0;
  486. var index = 1;
  487. // Limit to 100 chapters just in case there's some incorrect metadata here
  488. while (currentChapterTicks < runtime && index < 100)
  489. {
  490. chapters.Add(new ChapterInfo
  491. {
  492. StartPositionTicks = currentChapterTicks
  493. });
  494. index++;
  495. currentChapterTicks += _dummyChapterDuration;
  496. }
  497. }
  498. /// <summary>
  499. /// Called when [pre fetch].
  500. /// </summary>
  501. /// <param name="item">The item.</param>
  502. /// <param name="mount">The mount.</param>
  503. /// <param name="blurayDiscInfo">The bluray disc information.</param>
  504. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  505. {
  506. if (item.VideoType == VideoType.Iso)
  507. {
  508. item.IsoType = DetermineIsoType(mount);
  509. }
  510. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  511. {
  512. FetchFromDvdLib(item, mount);
  513. }
  514. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType.Value == IsoType.BluRay))
  515. {
  516. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  517. }
  518. }
  519. private void ExtractTimestamp(Video video)
  520. {
  521. if (video.VideoType == VideoType.VideoFile)
  522. {
  523. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  524. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  525. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  526. {
  527. try
  528. {
  529. video.Timestamp = GetMpegTimestamp(video.Path);
  530. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  531. }
  532. catch (Exception ex)
  533. {
  534. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  535. video.Timestamp = null;
  536. }
  537. }
  538. }
  539. }
  540. private TransportStreamTimestamp GetMpegTimestamp(string path)
  541. {
  542. var packetBuffer = new byte['Å'];
  543. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  544. {
  545. fs.Read(packetBuffer, 0, packetBuffer.Length);
  546. }
  547. if (packetBuffer[0] == 71)
  548. {
  549. return TransportStreamTimestamp.None;
  550. }
  551. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  552. {
  553. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  554. {
  555. return TransportStreamTimestamp.Zero;
  556. }
  557. return TransportStreamTimestamp.Valid;
  558. }
  559. return TransportStreamTimestamp.None;
  560. }
  561. private void FetchFromDvdLib(Video item, IIsoMount mount)
  562. {
  563. var path = mount == null ? item.Path : mount.MountedPath;
  564. var dvd = new Dvd(path);
  565. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  566. byte? titleNumber = null;
  567. if (primaryTitle != null)
  568. {
  569. titleNumber = primaryTitle.VideoTitleSetNumber;
  570. item.RunTimeTicks = GetRuntime(primaryTitle);
  571. }
  572. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  573. .Select(Path.GetFileName)
  574. .ToList();
  575. }
  576. private long GetRuntime(Title title)
  577. {
  578. return title.ProgramChains
  579. .Select(i => (TimeSpan)i.PlaybackTime)
  580. .Select(i => i.Ticks)
  581. .Sum();
  582. }
  583. /// <summary>
  584. /// Mounts the iso if needed.
  585. /// </summary>
  586. /// <param name="item">The item.</param>
  587. /// <param name="cancellationToken">The cancellation token.</param>
  588. /// <returns>IsoMount.</returns>
  589. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  590. {
  591. if (item.VideoType == VideoType.Iso)
  592. {
  593. return _isoManager.Mount(item.Path, cancellationToken);
  594. }
  595. return Task.FromResult<IIsoMount>(null);
  596. }
  597. /// <summary>
  598. /// Determines the type of the iso.
  599. /// </summary>
  600. /// <param name="isoMount">The iso mount.</param>
  601. /// <returns>System.Nullable{IsoType}.</returns>
  602. private IsoType? DetermineIsoType(IIsoMount isoMount)
  603. {
  604. var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  605. if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
  606. {
  607. return IsoType.Dvd;
  608. }
  609. if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  610. {
  611. return IsoType.BluRay;
  612. }
  613. return null;
  614. }
  615. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  616. {
  617. // min size 300 mb
  618. const long minPlayableSize = 314572800;
  619. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  620. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  621. // Once we reach a file that is at least the minimum, return all subsequent ones
  622. var allVobs = new DirectoryInfo(root).EnumerateFiles("*", SearchOption.AllDirectories)
  623. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  624. .OrderBy(i => i.FullName)
  625. .ToList();
  626. // If we didn't find any satisfying the min length, just take them all
  627. if (allVobs.Count == 0)
  628. {
  629. _logger.Error("No vobs found in dvd structure.");
  630. return new List<string>();
  631. }
  632. if (titleNumber.HasValue)
  633. {
  634. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  635. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  636. if (vobs.Count > 0)
  637. {
  638. var minSizeVobs = vobs
  639. .SkipWhile(f => f.Length < minPlayableSize)
  640. .ToList();
  641. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  642. }
  643. _logger.Debug("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  644. }
  645. var files = allVobs
  646. .SkipWhile(f => f.Length < minPlayableSize)
  647. .ToList();
  648. // If we didn't find any satisfying the min length, just take them all
  649. if (files.Count == 0)
  650. {
  651. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  652. files = allVobs;
  653. }
  654. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  655. if (files.Count > 0)
  656. {
  657. var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
  658. if (parts.Length == 3)
  659. {
  660. var title = parts[1];
  661. files = files.TakeWhile(f =>
  662. {
  663. var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
  664. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  665. }).ToList();
  666. // If this resulted in not getting any vobs, just take them all
  667. if (files.Count == 0)
  668. {
  669. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  670. files = allVobs;
  671. }
  672. }
  673. }
  674. return files.Select(i => i.FullName);
  675. }
  676. }
  677. }