FFProbeVideoInfo.cs 31 KB

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