FFProbeVideoInfo.cs 32 KB

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