FFProbeVideoInfo.cs 31 KB

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