jellyfin/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs

733 lines
28 KiB
C#
Raw Normal View History

using DvdLib.Ifo;
2014-02-09 21:11:11 +00:00
using MediaBrowser.Common.Configuration;
2015-04-05 15:01:57 +00:00
using MediaBrowser.Model.Dlna;
2014-06-09 19:16:14 +00:00
using MediaBrowser.Controller.Chapters;
2014-05-07 02:28:19 +00:00
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
2014-05-07 02:28:19 +00:00
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
2014-02-10 18:39:41 +00:00
using MediaBrowser.Controller.Providers;
2014-05-07 02:28:19 +00:00
using MediaBrowser.Controller.Subtitles;
2014-08-10 22:13:17 +00:00
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
2014-08-10 22:13:17 +00:00
using MediaBrowser.Model.Providers;
2014-02-09 21:11:11 +00:00
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.IO;
using MediaBrowser.Model.IO;
2016-10-24 02:45:23 +00:00
using MediaBrowser.Model.Globalization;
namespace MediaBrowser.Providers.MediaInfo
{
public class FFProbeVideoInfo
{
private readonly ILogger _logger;
private readonly IIsoManager _isoManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly IItemRepository _itemRepo;
private readonly IBlurayExaminer _blurayExaminer;
private readonly ILocalizationManager _localization;
2014-02-09 21:11:11 +00:00
private readonly IApplicationPaths _appPaths;
private readonly IJsonSerializer _json;
2014-02-20 16:37:41 +00:00
private readonly IEncodingManager _encodingManager;
private readonly IFileSystem _fileSystem;
2014-05-07 02:28:19 +00:00
private readonly IServerConfigurationManager _config;
private readonly ISubtitleManager _subtitleManager;
2014-06-09 19:16:14 +00:00
private readonly IChapterManager _chapterManager;
2015-06-28 17:00:36 +00:00
private readonly ILibraryManager _libraryManager;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
2015-06-28 17:00:36 +00:00
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, ILibraryManager libraryManager)
{
_logger = logger;
_isoManager = isoManager;
_mediaEncoder = mediaEncoder;
_itemRepo = itemRepo;
_blurayExaminer = blurayExaminer;
_localization = localization;
2014-02-09 21:11:11 +00:00
_appPaths = appPaths;
_json = json;
2014-02-20 16:37:41 +00:00
_encodingManager = encodingManager;
2014-04-25 02:45:06 +00:00
_fileSystem = fileSystem;
2014-05-07 02:28:19 +00:00
_config = config;
_subtitleManager = subtitleManager;
2014-06-09 19:16:14 +00:00
_chapterManager = chapterManager;
2015-06-28 17:00:36 +00:00
_libraryManager = libraryManager;
}
2014-06-09 19:16:14 +00:00
public async Task<ItemUpdateType> ProbeVideo<T>(T item,
MetadataRefreshOptions options,
CancellationToken cancellationToken)
where T : Video
{
var isoMount = await MountIsoIfNeeded(item, cancellationToken).ConfigureAwait(false);
2014-03-05 02:59:59 +00:00
BlurayDiscInfo blurayDiscInfo = null;
try
{
2014-03-05 02:59:59 +00:00
if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
{
var inputPath = isoMount != null ? isoMount.MountedPath : item.Path;
blurayDiscInfo = GetBDInfo(inputPath);
}
OnPreFetch(item, isoMount, blurayDiscInfo);
// If we didn't find any satisfying the min length, just take them all
if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
{
if (item.PlayableStreamFileNames.Count == 0)
{
_logger.Error("No playable vobs found in dvd structure, skipping ffprobe.");
return ItemUpdateType.MetadataImport;
}
}
2014-03-05 02:59:59 +00:00
if (item.VideoType == VideoType.BluRay || (item.IsoType.HasValue && item.IsoType == IsoType.BluRay))
{
if (item.PlayableStreamFileNames.Count == 0)
{
_logger.Error("No playable vobs found in bluray structure, skipping ffprobe.");
return ItemUpdateType.MetadataImport;
}
}
var result = await GetMediaInfo(item, isoMount, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
2014-06-09 19:16:14 +00:00
await Fetch(item, cancellationToken, result, isoMount, blurayDiscInfo, options).ConfigureAwait(false);
}
finally
{
if (isoMount != null)
{
isoMount.Dispose();
}
}
return ItemUpdateType.MetadataImport;
}
2015-08-27 15:58:07 +00:00
private const string SchemaVersion = "6";
2014-03-26 21:05:31 +00:00
2015-04-05 15:01:57 +00:00
private async Task<Model.MediaInfo.MediaInfo> GetMediaInfo(Video item,
2014-06-09 19:16:14 +00:00
IIsoMount isoMount,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var protocol = item.LocationType == LocationType.Remote
? MediaProtocol.Http
: MediaProtocol.File;
2015-04-05 15:01:57 +00:00
var result = await _mediaEncoder.GetMediaInfo(new MediaInfoRequest
{
PlayableStreamFileNames = item.PlayableStreamFileNames,
MountedIso = isoMount,
ExtractChapters = true,
VideoType = item.VideoType,
MediaType = DlnaProfileType.Video,
InputPath = item.Path,
2015-12-12 06:49:03 +00:00
Protocol = protocol
2015-04-05 15:01:57 +00:00
}, cancellationToken).ConfigureAwait(false);
2014-02-09 21:11:11 +00:00
2015-08-27 15:58:07 +00:00
//Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
//_json.SerializeToFile(result, cachePath);
2014-02-09 21:11:11 +00:00
return result;
}
2014-06-09 19:16:14 +00:00
protected async Task Fetch(Video video,
CancellationToken cancellationToken,
2015-04-05 15:01:57 +00:00
Model.MediaInfo.MediaInfo mediaInfo,
2014-06-09 19:16:14 +00:00
IIsoMount isoMount,
BlurayDiscInfo blurayInfo,
MetadataRefreshOptions options)
{
2014-04-22 17:25:54 +00:00
var mediaStreams = mediaInfo.MediaStreams;
2015-04-04 19:35:29 +00:00
video.TotalBitrate = mediaInfo.Bitrate;
2015-09-30 04:19:45 +00:00
//video.FormatName = (mediaInfo.Container ?? string.Empty)
// .Replace("matroska", "mkv", StringComparison.OrdinalIgnoreCase);
2014-04-22 17:25:54 +00:00
2015-04-04 19:35:29 +00:00
// For dvd's this may not always be accurate, so don't set the runtime if the item already has one
var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
2014-04-18 05:03:01 +00:00
2015-04-04 19:35:29 +00:00
if (needToSetRuntime)
{
video.RunTimeTicks = mediaInfo.RunTimeTicks;
}
2014-04-18 05:03:01 +00:00
2015-04-04 19:35:29 +00:00
if (video.VideoType == VideoType.VideoFile)
{
var extension = (Path.GetExtension(video.Path) ?? string.Empty).TrimStart('.');
2014-04-18 05:03:01 +00:00
2015-04-04 19:35:29 +00:00
video.Container = extension;
}
else
{
video.Container = null;
}
2015-04-04 19:35:29 +00:00
var chapters = mediaInfo.Chapters ?? new List<ChapterInfo>();
2016-01-29 01:15:59 +00:00
if (blurayInfo != null)
{
2014-03-05 02:59:59 +00:00
FetchBdInfo(video, chapters, mediaStreams, blurayInfo);
}
2014-06-09 19:16:14 +00:00
await AddExternalSubtitles(video, mediaStreams, options, cancellationToken).ConfigureAwait(false);
2015-04-20 18:04:02 +00:00
FetchEmbeddedInfo(video, mediaInfo, options);
2015-06-28 17:00:36 +00:00
await FetchPeople(video, mediaInfo, options).ConfigureAwait(false);
2016-01-23 18:21:46 +00:00
video.IsHD = mediaStreams.Any(i => i.Type == MediaStreamType.Video && i.Width.HasValue && i.Width.Value >= 1260);
var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
video.DefaultVideoStreamIndex = videoStream == null ? (int?)null : videoStream.Index;
video.HasSubtitles = mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle);
2015-04-04 19:35:29 +00:00
video.Timestamp = mediaInfo.Timestamp;
2016-08-09 05:08:36 +00:00
video.Video3DFormat = video.Video3DFormat ?? mediaInfo.Video3DFormat;
2014-06-09 19:16:14 +00:00
await _itemRepo.SaveMediaStreams(video.Id, mediaStreams, cancellationToken).ConfigureAwait(false);
if (options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh ||
options.MetadataRefreshMode == MetadataRefreshMode.Default)
2014-02-20 16:37:41 +00:00
{
2014-06-09 19:16:14 +00:00
if (chapters.Count == 0 && mediaStreams.Any(i => i.Type == MediaStreamType.Video))
{
AddDummyChapters(video, chapters);
}
2014-07-12 02:31:08 +00:00
NormalizeChapterNames(chapters);
var libraryOptions = _libraryManager.GetLibraryOptions(video);
var extractDuringScan = false;
if (libraryOptions != null)
{
extractDuringScan = libraryOptions.ExtractChapterImagesDuringLibraryScan;
}
2014-06-09 19:16:14 +00:00
await _encodingManager.RefreshChapterImages(new ChapterImageRefreshOptions
{
Chapters = chapters,
Video = video,
ExtractImages = extractDuringScan,
2014-06-09 19:16:14 +00:00
SaveChapters = false
}, cancellationToken).ConfigureAwait(false);
2014-06-10 17:36:06 +00:00
await _chapterManager.SaveChapters(video.Id.ToString(), chapters, cancellationToken).ConfigureAwait(false);
2014-06-09 19:16:14 +00:00
}
}
2014-07-12 02:31:08 +00:00
private void NormalizeChapterNames(List<ChapterInfo> chapters)
{
var index = 1;
foreach (var chapter in chapters)
{
TimeSpan time;
// Check if the name is empty and/or if the name is a time
// Some ripping programs do that.
if (string.IsNullOrWhiteSpace(chapter.Name) ||
TimeSpan.TryParse(chapter.Name, out time))
{
chapter.Name = string.Format(_localization.GetLocalizedString("LabelChapterName"), index.ToString(CultureInfo.InvariantCulture));
}
index++;
}
}
2014-03-05 02:59:59 +00:00
private void FetchBdInfo(BaseItem item, List<ChapterInfo> chapters, List<MediaStream> mediaStreams, BlurayDiscInfo blurayInfo)
{
var video = (Video)item;
2015-12-22 17:27:04 +00:00
video.PlayableStreamFileNames = blurayInfo.Files.ToList();
2015-12-22 17:27:04 +00:00
// Use BD Info if it has multiple m2ts. Otherwise, treat it like a video file and rely more on ffprobe output
if (blurayInfo.Files.Count > 1)
{
2015-12-22 17:27:04 +00:00
int? currentHeight = null;
int? currentWidth = null;
int? currentBitRate = null;
2015-12-22 17:27:04 +00:00
var videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
2015-12-22 17:27:04 +00:00
// Grab the values that ffprobe recorded
if (videoStream != null)
{
currentBitRate = videoStream.BitRate;
currentWidth = videoStream.Width;
currentHeight = videoStream.Height;
}
2015-12-22 17:27:04 +00:00
// Fill video properties from the BDInfo result
mediaStreams.Clear();
mediaStreams.AddRange(blurayInfo.MediaStreams);
2015-12-22 17:27:04 +00:00
if (blurayInfo.RunTimeTicks.HasValue && blurayInfo.RunTimeTicks.Value > 0)
{
video.RunTimeTicks = blurayInfo.RunTimeTicks;
}
2015-12-22 17:27:04 +00:00
if (blurayInfo.Chapters != null)
{
2015-12-22 17:27:04 +00:00
chapters.Clear();
2015-12-22 17:27:04 +00:00
chapters.AddRange(blurayInfo.Chapters.Select(c => new ChapterInfo
{
StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
2014-03-05 02:59:59 +00:00
2015-12-22 17:27:04 +00:00
}));
}
2014-03-05 02:59:59 +00:00
2015-12-22 17:27:04 +00:00
videoStream = mediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
// Use the ffprobe values if these are empty
if (videoStream != null)
{
videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
}
2014-03-05 02:59:59 +00:00
}
}
private bool IsEmpty(int? num)
{
return !num.HasValue || num.Value == 0;
}
/// <summary>
/// Gets information about the longest playlist on a bdrom
/// </summary>
/// <param name="path">The path.</param>
/// <returns>VideoStream.</returns>
private BlurayDiscInfo GetBDInfo(string path)
{
2016-12-24 07:41:25 +00:00
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException("path");
}
2016-01-29 01:15:59 +00:00
try
{
return _blurayExaminer.GetDiscInfo(path);
}
catch (Exception ex)
{
_logger.ErrorException("Error getting BDInfo", ex);
return null;
}
}
2015-04-20 18:04:02 +00:00
private void FetchEmbeddedInfo(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
{
2015-04-20 18:04:02 +00:00
var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
2015-03-05 06:34:36 +00:00
if (!video.LockedFields.Contains(MetadataFields.OfficialRating))
{
2015-04-20 18:04:02 +00:00
if (!string.IsNullOrWhiteSpace(data.OfficialRating) || isFullRefresh)
{
2015-04-04 19:35:29 +00:00
video.OfficialRating = data.OfficialRating;
}
}
2016-02-18 02:55:15 +00:00
if (!string.IsNullOrWhiteSpace(data.OfficialRatingDescription) || isFullRefresh)
{
video.OfficialRatingDescription = data.OfficialRatingDescription;
}
2015-04-04 19:35:29 +00:00
if (!video.LockedFields.Contains(MetadataFields.Genres))
2015-03-05 06:34:36 +00:00
{
2015-04-20 18:04:02 +00:00
if (video.Genres.Count == 0 || isFullRefresh)
2015-03-05 06:34:36 +00:00
{
2015-04-20 18:04:02 +00:00
video.Genres.Clear();
foreach (var genre in data.Genres)
{
video.AddGenre(genre);
}
}
}
2015-04-04 19:35:29 +00:00
if (!video.LockedFields.Contains(MetadataFields.Studios))
{
2015-04-20 18:04:02 +00:00
if (video.Studios.Count == 0 || isFullRefresh)
{
2015-04-20 18:04:02 +00:00
video.Studios.Clear();
foreach (var studio in data.Studios)
{
video.AddStudio(studio);
}
2015-03-05 06:34:36 +00:00
}
}
2015-04-04 19:35:29 +00:00
if (data.ProductionYear.HasValue)
2015-03-05 06:34:36 +00:00
{
2015-04-20 18:04:02 +00:00
if (!video.ProductionYear.HasValue || isFullRefresh)
{
video.ProductionYear = data.ProductionYear;
}
2015-04-04 19:35:29 +00:00
}
if (data.PremiereDate.HasValue)
{
2015-04-20 18:04:02 +00:00
if (!video.PremiereDate.HasValue || isFullRefresh)
{
video.PremiereDate = data.PremiereDate;
}
2015-04-04 19:35:29 +00:00
}
if (data.IndexNumber.HasValue)
{
2015-04-20 18:04:02 +00:00
if (!video.IndexNumber.HasValue || isFullRefresh)
{
video.IndexNumber = data.IndexNumber;
}
2015-04-04 19:35:29 +00:00
}
if (data.ParentIndexNumber.HasValue)
{
2015-04-20 18:04:02 +00:00
if (!video.ParentIndexNumber.HasValue || isFullRefresh)
{
video.ParentIndexNumber = data.ParentIndexNumber;
}
2015-04-04 19:35:29 +00:00
}
2016-02-18 02:55:15 +00:00
if (!string.IsNullOrWhiteSpace(data.Name))
{
if (string.IsNullOrWhiteSpace(video.Name) || (string.Equals(video.Name, Path.GetFileNameWithoutExtension(video.Path), StringComparison.OrdinalIgnoreCase) && !video.ProviderIds.Any()))
2016-02-18 02:55:15 +00:00
{
2016-05-01 20:56:26 +00:00
// Don't use the embedded name for extras because it will often be the same name as the movie
if (!video.ExtraType.HasValue && !video.IsOwnedItem)
{
video.Name = data.Name;
}
2016-02-18 02:55:15 +00:00
}
}
2015-03-05 06:34:36 +00:00
2015-04-04 19:35:29 +00:00
// If we don't have a ProductionYear try and get it from PremiereDate
if (video.PremiereDate.HasValue && !video.ProductionYear.HasValue)
{
video.ProductionYear = video.PremiereDate.Value.ToLocalTime().Year;
}
2015-03-05 06:34:36 +00:00
if (!video.LockedFields.Contains(MetadataFields.Overview))
{
2015-04-20 18:04:02 +00:00
if (string.IsNullOrWhiteSpace(video.Overview) || isFullRefresh)
2015-03-05 06:34:36 +00:00
{
2015-04-04 19:35:29 +00:00
video.Overview = data.Overview;
2015-03-05 06:34:36 +00:00
}
}
}
2015-06-28 17:00:36 +00:00
private async Task FetchPeople(Video video, Model.MediaInfo.MediaInfo data, MetadataRefreshOptions options)
{
var isFullRefresh = options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
if (!video.LockedFields.Contains(MetadataFields.Cast))
{
if (isFullRefresh || _libraryManager.GetPeople(video).Count == 0)
{
var people = new List<PersonInfo>();
foreach (var person in data.People)
{
PeopleHelper.AddPerson(people, new PersonInfo
{
Name = person.Name,
Type = person.Type,
Role = person.Role
});
}
await _libraryManager.UpdatePeople(video, people);
}
}
}
2014-08-10 22:13:17 +00:00
private SubtitleOptions GetOptions()
{
return _config.GetConfiguration<SubtitleOptions>("subtitles");
}
/// <summary>
/// Adds the external subtitles.
/// </summary>
/// <param name="video">The video.</param>
/// <param name="currentStreams">The current streams.</param>
2014-06-09 19:16:14 +00:00
/// <param name="options">The options.</param>
2014-05-17 04:24:10 +00:00
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
2014-06-09 19:16:14 +00:00
private async Task AddExternalSubtitles(Video video,
List<MediaStream> currentStreams,
MetadataRefreshOptions options,
CancellationToken cancellationToken)
2014-05-07 02:28:19 +00:00
{
2014-07-26 17:30:15 +00:00
var subtitleResolver = new SubtitleResolver(_localization, _fileSystem);
2014-05-16 19:16:29 +00:00
2015-09-23 04:00:30 +00:00
var startIndex = currentStreams.Count == 0 ? 0 : (currentStreams.Select(i => i.Index).Max() + 1);
var externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, false).ToList();
2014-06-09 19:16:14 +00:00
var enableSubtitleDownloading = options.MetadataRefreshMode == MetadataRefreshMode.Default ||
2014-06-09 19:16:14 +00:00
options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh;
2014-05-07 02:28:19 +00:00
2014-08-10 22:13:17 +00:00
var subtitleOptions = GetOptions();
if (enableSubtitleDownloading && (subtitleOptions.DownloadEpisodeSubtitles &&
2014-05-07 02:28:19 +00:00
video is Episode) ||
2014-08-10 22:13:17 +00:00
(subtitleOptions.DownloadMovieSubtitles &&
2014-05-07 02:28:19 +00:00
video is Movie))
{
var downloadedLanguages = await new SubtitleDownloader(_logger,
_subtitleManager)
.DownloadSubtitles(video,
currentStreams.Concat(externalSubtitleStreams).ToList(),
2016-03-19 22:31:00 +00:00
subtitleOptions.SkipIfEmbeddedSubtitlesPresent,
2014-08-10 22:13:17 +00:00
subtitleOptions.SkipIfAudioTrackMatches,
subtitleOptions.RequirePerfectMatch,
2014-08-10 22:13:17 +00:00
subtitleOptions.DownloadLanguages,
2014-05-07 02:28:19 +00:00
cancellationToken).ConfigureAwait(false);
// Rescan
if (downloadedLanguages.Count > 0)
{
2015-09-23 04:00:30 +00:00
externalSubtitleStreams = subtitleResolver.GetExternalSubtitleStreams(video, startIndex, options.DirectoryService, true).ToList();
2014-05-07 02:28:19 +00:00
}
}
video.SubtitleFiles = externalSubtitleStreams.Select(i => i.Path).OrderBy(i => i).ToList();
currentStreams.AddRange(externalSubtitleStreams);
}
/// <summary>
/// The dummy chapter duration
/// </summary>
private readonly long _dummyChapterDuration = TimeSpan.FromMinutes(5).Ticks;
/// <summary>
/// Adds the dummy chapters.
/// </summary>
/// <param name="video">The video.</param>
/// <param name="chapters">The chapters.</param>
private void AddDummyChapters(Video video, List<ChapterInfo> chapters)
{
var runtime = video.RunTimeTicks ?? 0;
if (runtime < 0)
{
throw new ArgumentException(string.Format("{0} has invalid runtime of {1}", video.Name, runtime));
}
if (runtime < _dummyChapterDuration)
{
return;
}
long currentChapterTicks = 0;
var index = 1;
// Limit to 100 chapters just in case there's some incorrect metadata here
while (currentChapterTicks < runtime && index < 100)
{
chapters.Add(new ChapterInfo
{
StartPositionTicks = currentChapterTicks
});
index++;
currentChapterTicks += _dummyChapterDuration;
}
}
/// <summary>
/// Called when [pre fetch].
/// </summary>
/// <param name="item">The item.</param>
/// <param name="mount">The mount.</param>
2014-06-09 19:16:14 +00:00
/// <param name="blurayDiscInfo">The bluray disc information.</param>
2014-03-05 02:59:59 +00:00
private void OnPreFetch(Video item, IIsoMount mount, BlurayDiscInfo blurayDiscInfo)
{
if (item.VideoType == VideoType.Iso)
{
item.IsoType = DetermineIsoType(mount);
}
if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
{
FetchFromDvdLib(item, mount);
}
2014-03-05 02:59:59 +00:00
2016-01-29 01:15:59 +00:00
if (blurayDiscInfo != null)
2014-03-05 02:59:59 +00:00
{
item.PlayableStreamFileNames = blurayDiscInfo.Files.ToList();
}
}
private void FetchFromDvdLib(Video item, IIsoMount mount)
{
var path = mount == null ? item.Path : mount.MountedPath;
var dvd = new Dvd(path, _fileSystem);
2014-05-07 02:28:19 +00:00
var primaryTitle = dvd.Titles.OrderByDescending(GetRuntime).FirstOrDefault();
2014-02-22 22:40:44 +00:00
byte? titleNumber = null;
if (primaryTitle != null)
{
2014-02-22 22:40:44 +00:00
titleNumber = primaryTitle.VideoTitleSetNumber;
2014-02-22 20:20:22 +00:00
item.RunTimeTicks = GetRuntime(primaryTitle);
}
item.PlayableStreamFileNames = GetPrimaryPlaylistVobFiles(item, mount, titleNumber)
.Select(Path.GetFileName)
.ToList();
}
private long GetRuntime(Title title)
{
return title.ProgramChains
.Select(i => (TimeSpan)i.PlaybackTime)
.Select(i => i.Ticks)
.Sum();
}
/// <summary>
/// Mounts the iso if needed.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>IsoMount.</returns>
protected Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
{
if (item.VideoType == VideoType.Iso)
{
return _isoManager.Mount(item.Path, cancellationToken);
}
return Task.FromResult<IIsoMount>(null);
}
/// <summary>
/// Determines the type of the iso.
/// </summary>
/// <param name="isoMount">The iso mount.</param>
/// <returns>System.Nullable{IsoType}.</returns>
private IsoType? DetermineIsoType(IIsoMount isoMount)
{
2016-10-27 07:58:33 +00:00
var fileSystemEntries = _fileSystem.GetFileSystemEntryPaths(isoMount.MountedPath).Select(Path.GetFileName).ToList();
2014-12-09 04:57:18 +00:00
if (fileSystemEntries.Contains("video_ts", StringComparer.OrdinalIgnoreCase) ||
fileSystemEntries.Contains("VIDEO_TS.IFO", StringComparer.OrdinalIgnoreCase))
{
return IsoType.Dvd;
}
2014-12-09 04:57:18 +00:00
if (fileSystemEntries.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
{
return IsoType.BluRay;
}
return null;
}
private IEnumerable<string> GetPrimaryPlaylistVobFiles(Video video, IIsoMount isoMount, uint? titleNumber)
{
// min size 300 mb
const long minPlayableSize = 314572800;
var root = isoMount != null ? isoMount.MountedPath : video.Path;
// Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
// Once we reach a file that is at least the minimum, return all subsequent ones
2015-12-03 16:50:26 +00:00
var allVobs = _fileSystem.GetFiles(root, true)
2014-02-24 03:27:13 +00:00
.Where(file => string.Equals(file.Extension, ".vob", StringComparison.OrdinalIgnoreCase))
.OrderBy(i => i.FullName)
.ToList();
// If we didn't find any satisfying the min length, just take them all
if (allVobs.Count == 0)
{
_logger.Error("No vobs found in dvd structure.");
return new List<string>();
}
if (titleNumber.HasValue)
{
var prefix = string.Format("VTS_0{0}_", titleNumber.Value.ToString(_usCulture));
2014-02-24 03:27:13 +00:00
var vobs = allVobs.Where(i => i.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).ToList();
if (vobs.Count > 0)
{
2014-02-24 03:48:27 +00:00
var minSizeVobs = vobs
2014-02-24 03:27:13 +00:00
.SkipWhile(f => f.Length < minPlayableSize)
.ToList();
return minSizeVobs.Count == 0 ? vobs.Select(i => i.FullName) : minSizeVobs.Select(i => i.FullName);
}
2015-10-04 22:04:56 +00:00
_logger.Info("Could not determine vob file list for {0} using DvdLib. Will scan using file sizes.", video.Path);
}
var files = allVobs
2014-02-24 03:27:13 +00:00
.SkipWhile(f => f.Length < minPlayableSize)
.ToList();
// If we didn't find any satisfying the min length, just take them all
if (files.Count == 0)
{
_logger.Warn("Vob size filter resulted in zero matches. Taking all vobs.");
files = allVobs;
}
// Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
if (files.Count > 0)
{
2014-07-26 17:30:15 +00:00
var parts = _fileSystem.GetFileNameWithoutExtension(files[0]).Split('_');
if (parts.Length == 3)
{
var title = parts[1];
files = files.TakeWhile(f =>
{
2014-07-26 17:30:15 +00:00
var fileParts = _fileSystem.GetFileNameWithoutExtension(f).Split('_');
return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
}).ToList();
// If this resulted in not getting any vobs, just take them all
if (files.Count == 0)
{
_logger.Warn("Vob filename filter resulted in zero matches. Taking all vobs.");
files = allVobs;
}
}
}
2014-02-24 03:27:13 +00:00
return files.Select(i => i.FullName);
}
}
2015-09-30 04:19:45 +00:00
}