FFProbeVideoInfo.cs 32 KB

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