FFProbeVideoInfo.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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" };
  336. }
  337. }
  338. public IEnumerable<FileSystemInfo> GetSubtitleFiles(Video video, IDirectoryService directoryService)
  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);
  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).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.RequireExternalSubtitles,
  385. _config.Configuration.SubtitleOptions.DownloadLanguages,
  386. cancellationToken).ConfigureAwait(false);
  387. // Rescan
  388. if (downloadedLanguages.Count > 0)
  389. {
  390. externalSubtitleStreams = GetExternalSubtitleStreams(video, currentStreams.Count, directoryService).ToList();
  391. }
  392. }
  393. video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
  394. currentStreams.AddRange(externalSubtitleStreams);
  395. }
  396. private IEnumerable<MediaStream> GetExternalSubtitleStreams(Video video,
  397. int startIndex,
  398. IDirectoryService directoryService)
  399. {
  400. var files = GetSubtitleFiles(video, directoryService);
  401. var streams = new List<MediaStream>();
  402. var videoFileNameWithoutExtension = Path.GetFileNameWithoutExtension(video.Path);
  403. foreach (var file in files)
  404. {
  405. var fullName = file.FullName;
  406. var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullName);
  407. // If the subtitle file matches the video file name
  408. if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
  409. {
  410. streams.Add(new MediaStream
  411. {
  412. Index = startIndex++,
  413. Type = MediaStreamType.Subtitle,
  414. IsExternal = true,
  415. Path = fullName,
  416. Codec = Path.GetExtension(fullName).ToLower().TrimStart('.')
  417. });
  418. }
  419. else if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
  420. {
  421. // Support xbmc naming conventions - 300.spanish.srt
  422. var language = fileNameWithoutExtension.Split('.').LastOrDefault();
  423. // Try to translate to three character code
  424. // Be flexible and check against both the full and three character versions
  425. var culture = _localization.GetCultures()
  426. .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));
  427. if (culture != null)
  428. {
  429. language = culture.ThreeLetterISOLanguageName;
  430. }
  431. streams.Add(new MediaStream
  432. {
  433. Index = startIndex++,
  434. Type = MediaStreamType.Subtitle,
  435. IsExternal = true,
  436. Path = fullName,
  437. Codec = Path.GetExtension(fullName).ToLower().TrimStart('.'),
  438. Language = language
  439. });
  440. }
  441. }
  442. return streams;
  443. }
  444. /// <summary>
  445. /// The dummy chapter duration
  446. /// </summary>
  447. private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
  448. /// <summary>
  449. /// Adds the dummy chapters.
  450. /// </summary>
  451. /// <param name="video">The video.</param>
  452. /// <param name="chapters">The chapters.</param>
  453. private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
  454. {
  455. var runtime = video.RunTimeTicks ?? 0;
  456. if (runtime < 0)
  457. {
  458. throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
  459. }
  460. if (runtime < _dummyChapterDuration)
  461. {
  462. return;
  463. }
  464. long currentChapterTicks = 0;
  465. var index = 1;
  466. // Limit to 100 chapters just in case there's some incorrect metadata here
  467. while (currentChapterTicks < runtime && index < 100)
  468. {
  469. chapters.Add(new ChapterInfo
  470. {
  471. Name = "Chapter " + index,
  472. StartPositionTicks = currentChapterTicks
  473. });
  474. index++;
  475. currentChapterTicks += _dummyChapterDuration;
  476. }
  477. }
  478. /// <summary>
  479. /// Called when [pre fetch].
  480. /// </summary>
  481. /// <param name="item">The item.</param>
  482. /// <param name="mount">The mount.</param>
  483. private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
  484. {
  485. if (item.VideoType == VideoType.Iso)
  486. {
  487. item.IsoType = DetermineIsoType(mount);
  488. }
  489. if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
  490. {
  491. FetchFromDvdLib(item, mount);
  492. }
  493. if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType.Value == IsoType.BluRay))
  494. {
  495. item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
  496. }
  497. }
  498. private void ExtractTimestamp(Video video)
  499. {
  500. if (video.VideoType == VideoType.VideoFile)
  501. {
  502. if (string.Equals(video.Container, "mpeg2ts", StringComparison.OrdinalIgnoreCase) ||
  503. string.Equals(video.Container, "m2ts", StringComparison.OrdinalIgnoreCase) ||
  504. string.Equals(video.Container, "ts", StringComparison.OrdinalIgnoreCase))
  505. {
  506. try
  507. {
  508. video.Timestamp = GetMpegTimestamp(video.Path);
  509. _logger.Debug("Video has {0} timestamp", video.Timestamp);
  510. }
  511. catch (Exception ex)
  512. {
  513. _logger.ErrorException("Error extracting timestamp info from {0}", ex, video.Path);
  514. video.Timestamp = null;
  515. }
  516. }
  517. }
  518. }
  519. private TransportStreamTimestamp GetMpegTimestamp(string path)
  520. {
  521. var packetBuffer = new byte['Å'];
  522. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
  523. {
  524. fs.Read(packetBuffer, 0, packetBuffer.Length);
  525. }
  526. if (packetBuffer[0] == 71)
  527. {
  528. return TransportStreamTimestamp.None;
  529. }
  530. if ((packetBuffer[4] == 71) && (packetBuffer['Ä'] == 71))
  531. {
  532. if ((packetBuffer[0] == 0) && (packetBuffer[1] == 0) && (packetBuffer[2] == 0) && (packetBuffer[3] == 0))
  533. {
  534. return TransportStreamTimestamp.Zero;
  535. }
  536. return TransportStreamTimestamp.Valid;
  537. }
  538. return TransportStreamTimestamp.None;
  539. }
  540. private void FetchFromDvdLib(Video item, IIsoMount mount)
  541. {
  542. var path = mount == null ? item.Path : mount.MountedPath;
  543. var dvd = new Dvd(path);
  544. var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
  545. byte? titleNumber = null;
  546. if (primaryTitle != null)
  547. {
  548. titleNumber = primaryTitle.VideoTitleSetNumber;
  549. item.RunTimeTicks = GetRuntime(primaryTitle);
  550. }
  551. item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
  552. .Select(Path.GetFileName)
  553. .ToList();
  554. }
  555. private long GetRuntime(Title title)
  556. {
  557. return title.ProgramChains
  558. .Select(i => (TimeSpan)i.PlaybackTime)
  559. .Select(i => i.Ticks)
  560. .Sum();
  561. }
  562. /// <summary>
  563. /// Mounts the iso if needed.
  564. /// </summary>
  565. /// <param name="item">The item.</param>
  566. /// <param name="cancellationToken">The cancellation token.</param>
  567. /// <returns>IsoMount.</returns>
  568. protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
  569. {
  570. if (item.VideoType == VideoType.Iso)
  571. {
  572. return _isoManager.Mount(item.Path, cancellationToken);
  573. }
  574. return Task.FromResult<IIsoMount>(null);
  575. }
  576. /// <summary>
  577. /// Determines the type of the iso.
  578. /// </summary>
  579. /// <param name="isoMount">The iso mount.</param>
  580. /// <returns>System.Nullable{IsoType}.</returns>
  581. private IsoType? DetermineIsoType(IIsoMount isoMount)
  582. {
  583. var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
  584. if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
  585. {
  586. return IsoType.Dvd;
  587. }
  588. if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
  589. {
  590. return IsoType.BluRay;
  591. }
  592. return null;
  593. }
  594. private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
  595. {
  596. // min size 300 mb
  597. const long minPlayableSize = 314572800;
  598. var root = isoMount != null ? isoMount.MountedPath : video.Path;
  599. // Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
  600. // Once we reach a file that is at least the minimum, return all subsequent ones
  601. var allVobs = new DirectoryInfo(root).EnumerateFiles("*", SearchOption.AllDirectories)
  602. .Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
  603. .OrderBy(i => i.FullName)
  604. .ToList();
  605. // If we didn't find any satisfying the min length, just take them all
  606. if (allVobs.Count == 0)
  607. {
  608. _logger.Error("No vobs found in dvd structure.");
  609. return new List<string>();
  610. }
  611. if (titleNumber.HasValue)
  612. {
  613. var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
  614. var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
  615. if (vobs.Count > 0)
  616. {
  617. var minSizeVobs = vobs
  618. .SkipWhile(f => f.Length < minPlayableSize)
  619. .ToList();
  620. return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
  621. }
  622. _logger.Debug("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
  623. }
  624. var files = allVobs
  625. .SkipWhile(f => f.Length < minPlayableSize)
  626. .ToList();
  627. // If we didn't find any satisfying the min length, just take them all
  628. if (files.Count == 0)
  629. {
  630. _logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
  631. files = allVobs;
  632. }
  633. // Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
  634. if (files.Count > 0)
  635. {
  636. var parts = Path.GetFileNameWithoutExtension(files[0].FullName).Split('_');
  637. if (parts.Length == 3)
  638. {
  639. var title = parts[1];
  640. files = files.TakeWhile(f =>
  641. {
  642. var fileParts = Path.GetFileNameWithoutExtension(f.FullName).Split('_');
  643. return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
  644. }).ToList();
  645. // If this resulted in not getting any vobs, just take them all
  646. if (files.Count == 0)
  647. {
  648. _logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
  649. files = allVobs;
  650. }
  651. }
  652. }
  653. return files.Select(i => i.FullName);
  654. }
  655. }
  656. }