From 888b8d619aec031f57cfd03410ccda52edcca958 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 20 Feb 2014 11:37:41 -0500 Subject: added encoding manager interface --- .../MediaBrowser.Controller.csproj | 9 +- .../MediaEncoding/ChapterImageRefreshOptions.cs | 17 + .../MediaEncoding/IEncodingManager.cs | 33 ++ .../MediaEncoding/IMediaEncoder.cs | 108 ++++++ .../MediaEncoding/InternalMediaInfoResult.cs | 311 ++++++++++++++++++ .../MediaEncoding/MediaEncoderHelpers.cs | 365 +++++++++++++++++++++ MediaBrowser.Controller/MediaInfo/FFMpegManager.cs | 297 ----------------- MediaBrowser.Controller/MediaInfo/IMediaEncoder.cs | 108 ------ .../MediaInfo/InternalMediaInfoResult.cs | 311 ------------------ .../MediaInfo/MediaEncoderHelpers.cs | 365 --------------------- 10 files changed, 839 insertions(+), 1085 deletions(-) create mode 100644 MediaBrowser.Controller/MediaEncoding/ChapterImageRefreshOptions.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/InternalMediaInfoResult.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs delete mode 100644 MediaBrowser.Controller/MediaInfo/FFMpegManager.cs delete mode 100644 MediaBrowser.Controller/MediaInfo/IMediaEncoder.cs delete mode 100644 MediaBrowser.Controller/MediaInfo/InternalMediaInfoResult.cs delete mode 100644 MediaBrowser.Controller/MediaInfo/MediaEncoderHelpers.cs (limited to 'MediaBrowser.Controller') diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index c88164897..ab1c012a8 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -135,8 +135,10 @@ - - + + + + @@ -198,7 +200,7 @@ - + @@ -209,7 +211,6 @@ - diff --git a/MediaBrowser.Controller/MediaEncoding/ChapterImageRefreshOptions.cs b/MediaBrowser.Controller/MediaEncoding/ChapterImageRefreshOptions.cs new file mode 100644 index 000000000..e11bd6cdf --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/ChapterImageRefreshOptions.cs @@ -0,0 +1,17 @@ +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Entities; +using System.Collections.Generic; + +namespace MediaBrowser.Controller.MediaEncoding +{ + public class ChapterImageRefreshOptions + { + public Video Video { get; set; } + + public List Chapters { get; set; } + + public bool SaveChapters { get; set; } + + public bool ExtractImages { get; set; } + } +} diff --git a/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs new file mode 100644 index 000000000..d1e40e3f0 --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/IEncodingManager.cs @@ -0,0 +1,33 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.MediaEncoding +{ + public interface IEncodingManager + { + /// + /// Gets the subtitle cache path. + /// + /// The original subtitle path. + /// The output subtitle extension. + /// System.String. + string GetSubtitleCachePath(string originalSubtitlePath, string outputSubtitleExtension); + + /// + /// Gets the subtitle cache path. + /// + /// The media path. + /// Index of the subtitle stream. + /// The output subtitle extension. + /// System.String. + string GetSubtitleCachePath(string mediaPath, int subtitleStreamIndex, string outputSubtitleExtension); + + /// + /// Refreshes the chapter images. + /// + /// The options. + /// The cancellation token. + /// Task{System.Boolean}. + Task RefreshChapterImages(ChapterImageRefreshOptions options, CancellationToken cancellationToken); + } +} diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs new file mode 100644 index 000000000..119688fa7 --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -0,0 +1,108 @@ +using MediaBrowser.Model.Entities; +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.MediaEncoding +{ + /// + /// Interface IMediaEncoder + /// + public interface IMediaEncoder + { + /// + /// Gets the encoder path. + /// + /// The encoder path. + string EncoderPath { get; } + + /// + /// Gets the version. + /// + /// The version. + string Version { get; } + + /// + /// Extracts the image. + /// + /// The input files. + /// The type. + /// if set to true [is audio]. + /// The threed format. + /// The offset. + /// The cancellation token. + /// Task{Stream}. + Task ExtractImage(string[] inputFiles, InputType type, bool isAudio, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); + + /// + /// Extracts the text subtitle. + /// + /// The input files. + /// The type. + /// Index of the subtitle stream. + /// if set to true, copy stream instead of converting. + /// The output path. + /// The cancellation token. + /// Task. + Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, bool copySubtitleStream, string outputPath, CancellationToken cancellationToken); + + /// + /// Converts the text subtitle to ass. + /// + /// The input path. + /// The output path. + /// The language. + /// The cancellation token. + /// Task. + Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language, CancellationToken cancellationToken); + + /// + /// Gets the media info. + /// + /// The input files. + /// The type. + /// if set to true [is audio]. + /// The cancellation token. + /// Task. + Task GetMediaInfo(string[] inputFiles, InputType type, bool isAudio, CancellationToken cancellationToken); + + /// + /// Gets the probe size argument. + /// + /// The type. + /// System.String. + string GetProbeSizeArgument(InputType type); + + /// + /// Gets the input argument. + /// + /// The input files. + /// The type. + /// System.String. + string GetInputArgument(string[] inputFiles, InputType type); + } + + /// + /// Enum InputType + /// + public enum InputType + { + /// + /// The file + /// + File, + /// + /// The bluray + /// + Bluray, + /// + /// The DVD + /// + Dvd, + /// + /// The URL + /// + Url + } +} diff --git a/MediaBrowser.Controller/MediaEncoding/InternalMediaInfoResult.cs b/MediaBrowser.Controller/MediaEncoding/InternalMediaInfoResult.cs new file mode 100644 index 000000000..e113521ec --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/InternalMediaInfoResult.cs @@ -0,0 +1,311 @@ +using MediaBrowser.Model.Entities; +using System.Collections.Generic; + +namespace MediaBrowser.Controller.MediaEncoding +{ + /// + /// Class MediaInfoResult + /// + public class InternalMediaInfoResult + { + /// + /// Gets or sets the streams. + /// + /// The streams. + public MediaStreamInfo[] streams { get; set; } + + /// + /// Gets or sets the format. + /// + /// The format. + public MediaFormatInfo format { get; set; } + + /// + /// Gets or sets the chapters. + /// + /// The chapters. + public List Chapters { get; set; } + } + + /// + /// Represents a stream within the output + /// + public class MediaStreamInfo + { + /// + /// Gets or sets the index. + /// + /// The index. + public int index { get; set; } + + /// + /// Gets or sets the profile. + /// + /// The profile. + public string profile { get; set; } + + /// + /// Gets or sets the codec_name. + /// + /// The codec_name. + public string codec_name { get; set; } + + /// + /// Gets or sets the codec_long_name. + /// + /// The codec_long_name. + public string codec_long_name { get; set; } + + /// + /// Gets or sets the codec_type. + /// + /// The codec_type. + public string codec_type { get; set; } + + /// + /// Gets or sets the sample_rate. + /// + /// The sample_rate. + public string sample_rate { get; set; } + + /// + /// Gets or sets the channels. + /// + /// The channels. + public int channels { get; set; } + + /// + /// Gets or sets the channel_layout. + /// + /// The channel_layout. + public string channel_layout { get; set; } + + /// + /// Gets or sets the avg_frame_rate. + /// + /// The avg_frame_rate. + public string avg_frame_rate { get; set; } + + /// + /// Gets or sets the duration. + /// + /// The duration. + public string duration { get; set; } + + /// + /// Gets or sets the bit_rate. + /// + /// The bit_rate. + public string bit_rate { get; set; } + + /// + /// Gets or sets the width. + /// + /// The width. + public int width { get; set; } + + /// + /// Gets or sets the height. + /// + /// The height. + public int height { get; set; } + + /// + /// Gets or sets the display_aspect_ratio. + /// + /// The display_aspect_ratio. + public string display_aspect_ratio { get; set; } + + /// + /// Gets or sets the tags. + /// + /// The tags. + public Dictionary tags { get; set; } + + /// + /// Gets or sets the bits_per_sample. + /// + /// The bits_per_sample. + public int bits_per_sample { get; set; } + + /// + /// Gets or sets the r_frame_rate. + /// + /// The r_frame_rate. + public string r_frame_rate { get; set; } + + /// + /// Gets or sets the has_b_frames. + /// + /// The has_b_frames. + public int has_b_frames { get; set; } + + /// + /// Gets or sets the sample_aspect_ratio. + /// + /// The sample_aspect_ratio. + public string sample_aspect_ratio { get; set; } + + /// + /// Gets or sets the pix_fmt. + /// + /// The pix_fmt. + public string pix_fmt { get; set; } + + /// + /// Gets or sets the level. + /// + /// The level. + public int level { get; set; } + + /// + /// Gets or sets the time_base. + /// + /// The time_base. + public string time_base { get; set; } + + /// + /// Gets or sets the start_time. + /// + /// The start_time. + public string start_time { get; set; } + + /// + /// Gets or sets the codec_time_base. + /// + /// The codec_time_base. + public string codec_time_base { get; set; } + + /// + /// Gets or sets the codec_tag. + /// + /// The codec_tag. + public string codec_tag { get; set; } + + /// + /// Gets or sets the codec_tag_string. + /// + /// The codec_tag_string. + public string codec_tag_string { get; set; } + + /// + /// Gets or sets the sample_fmt. + /// + /// The sample_fmt. + public string sample_fmt { get; set; } + + /// + /// Gets or sets the dmix_mode. + /// + /// The dmix_mode. + public string dmix_mode { get; set; } + + /// + /// Gets or sets the start_pts. + /// + /// The start_pts. + public string start_pts { get; set; } + + /// + /// Gets or sets the is_avc. + /// + /// The is_avc. + public string is_avc { get; set; } + + /// + /// Gets or sets the nal_length_size. + /// + /// The nal_length_size. + public string nal_length_size { get; set; } + + /// + /// Gets or sets the ltrt_cmixlev. + /// + /// The ltrt_cmixlev. + public string ltrt_cmixlev { get; set; } + + /// + /// Gets or sets the ltrt_surmixlev. + /// + /// The ltrt_surmixlev. + public string ltrt_surmixlev { get; set; } + + /// + /// Gets or sets the loro_cmixlev. + /// + /// The loro_cmixlev. + public string loro_cmixlev { get; set; } + + /// + /// Gets or sets the loro_surmixlev. + /// + /// The loro_surmixlev. + public string loro_surmixlev { get; set; } + + /// + /// Gets or sets the disposition. + /// + /// The disposition. + public Dictionary disposition { get; set; } + } + + /// + /// Class MediaFormat + /// + public class MediaFormatInfo + { + /// + /// Gets or sets the filename. + /// + /// The filename. + public string filename { get; set; } + + /// + /// Gets or sets the nb_streams. + /// + /// The nb_streams. + public int nb_streams { get; set; } + + /// + /// Gets or sets the format_name. + /// + /// The format_name. + public string format_name { get; set; } + + /// + /// Gets or sets the format_long_name. + /// + /// The format_long_name. + public string format_long_name { get; set; } + + /// + /// Gets or sets the start_time. + /// + /// The start_time. + public string start_time { get; set; } + + /// + /// Gets or sets the duration. + /// + /// The duration. + public string duration { get; set; } + + /// + /// Gets or sets the size. + /// + /// The size. + public string size { get; set; } + + /// + /// Gets or sets the bit_rate. + /// + /// The bit_rate. + public string bit_rate { get; set; } + + /// + /// Gets or sets the tags. + /// + /// The tags. + public Dictionary tags { get; set; } + } +} diff --git a/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs new file mode 100644 index 000000000..b2b9e2af3 --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/MediaEncoderHelpers.cs @@ -0,0 +1,365 @@ +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; + +namespace MediaBrowser.Controller.MediaEncoding +{ + /// + /// Class MediaEncoderHelpers + /// + public static class MediaEncoderHelpers + { + /// + /// Gets the input argument. + /// + /// The video path. + /// if set to true [is remote]. + /// Type of the video. + /// Type of the iso. + /// The iso mount. + /// The playable stream file names. + /// The type. + /// System.String[][]. + public static string[] GetInputArgument(string videoPath, bool isRemote, VideoType videoType, IsoType? isoType, IIsoMount isoMount, IEnumerable playableStreamFileNames, out InputType type) + { + var inputPath = isoMount == null ? new[] { videoPath } : new[] { isoMount.MountedPath }; + + type = InputType.File; + + switch (videoType) + { + case VideoType.BluRay: + type = InputType.Bluray; + break; + case VideoType.Dvd: + type = InputType.Dvd; + inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray(); + break; + case VideoType.Iso: + if (isoType.HasValue) + { + switch (isoType.Value) + { + case IsoType.BluRay: + type = InputType.Bluray; + break; + case IsoType.Dvd: + type = InputType.Dvd; + inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray(); + break; + } + } + break; + case VideoType.VideoFile: + { + if (isRemote) + { + type = InputType.Url; + } + break; + } + } + + return inputPath; + } + + public static List GetPlayableStreamFiles(string rootPath, IEnumerable filenames) + { + var allFiles = Directory + .EnumerateFiles(rootPath, "*", SearchOption.AllDirectories) + .ToList(); + + return filenames.Select(name => allFiles.FirstOrDefault(f => string.Equals(Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase))) + .Where(f => !string.IsNullOrEmpty(f)) + .ToList(); + } + + /// + /// Gets the type of the input. + /// + /// Type of the video. + /// Type of the iso. + /// InputType. + public static InputType GetInputType(VideoType? videoType, IsoType? isoType) + { + var type = InputType.File; + + if (videoType.HasValue) + { + switch (videoType.Value) + { + case VideoType.BluRay: + type = InputType.Bluray; + break; + case VideoType.Dvd: + type = InputType.Dvd; + break; + case VideoType.Iso: + if (isoType.HasValue) + { + switch (isoType.Value) + { + case IsoType.BluRay: + type = InputType.Bluray; + break; + case IsoType.Dvd: + type = InputType.Dvd; + break; + } + } + break; + } + } + + return type; + } + + public static Model.Entities.MediaInfo GetMediaInfo(InternalMediaInfoResult data) + { + var internalStreams = data.streams ?? new MediaStreamInfo[] { }; + + var info = new Model.Entities.MediaInfo(); + + info.MediaStreams = internalStreams.Select(s => GetMediaStream(s, data.format)) + .Where(i => i != null) + .ToList(); + + if (data.format != null) + { + info.Format = data.format.format_name; + } + + return info; + } + + private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); + + /// + /// Converts ffprobe stream info to our MediaStream class + /// + /// The stream info. + /// The format info. + /// MediaStream. + private static MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo) + { + var stream = new MediaStream + { + Codec = streamInfo.codec_name, + Profile = streamInfo.profile, + Level = streamInfo.level, + Index = streamInfo.index + }; + + if (streamInfo.tags != null) + { + stream.Language = GetDictionaryValue(streamInfo.tags, "language"); + } + + if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase)) + { + stream.Type = MediaStreamType.Audio; + + stream.Channels = streamInfo.channels; + + if (!string.IsNullOrEmpty(streamInfo.sample_rate)) + { + stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture); + } + + stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout); + } + else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase)) + { + stream.Type = MediaStreamType.Subtitle; + } + else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase)) + { + stream.Type = MediaStreamType.Video; + + stream.Width = streamInfo.width; + stream.Height = streamInfo.height; + stream.AspectRatio = GetAspectRatio(streamInfo); + + stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate); + stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate); + } + else + { + return null; + } + + // Get stream bitrate + if (stream.Type != MediaStreamType.Subtitle) + { + var bitrate = 0; + + if (!string.IsNullOrEmpty(streamInfo.bit_rate)) + { + bitrate = int.Parse(streamInfo.bit_rate, UsCulture); + } + else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate)) + { + // If the stream info doesn't have a bitrate get the value from the media format info + bitrate = int.Parse(formatInfo.bit_rate, UsCulture); + } + + if (bitrate > 0) + { + stream.BitRate = bitrate; + } + } + + if (streamInfo.disposition != null) + { + var isDefault = GetDictionaryValue(streamInfo.disposition, "default"); + var isForced = GetDictionaryValue(streamInfo.disposition, "forced"); + + stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase); + + stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase); + } + + return stream; + } + + /// + /// Gets a string from an FFProbeResult tags dictionary + /// + /// The tags. + /// The key. + /// System.String. + private static string GetDictionaryValue(Dictionary tags, string key) + { + if (tags == null) + { + return null; + } + + string val; + + tags.TryGetValue(key, out val); + return val; + } + + private static string ParseChannelLayout(string input) + { + if (string.IsNullOrEmpty(input)) + { + return input; + } + + return input.Split('(').FirstOrDefault(); + } + + private static string GetAspectRatio(MediaStreamInfo info) + { + var original = info.display_aspect_ratio; + + int height; + int width; + + var parts = (original ?? string.Empty).Split(':'); + if (!(parts.Length == 2 && + int.TryParse(parts[0], NumberStyles.Any, UsCulture, out width) && + int.TryParse(parts[1], NumberStyles.Any, UsCulture, out height) && + width > 0 && + height > 0)) + { + width = info.width; + height = info.height; + } + + if (width > 0 && height > 0) + { + double ratio = width; + ratio /= height; + + if (IsClose(ratio, 1.777777778, .03)) + { + return "16:9"; + } + + if (IsClose(ratio, 1.3333333333, .05)) + { + return "4:3"; + } + + if (IsClose(ratio, 1.41)) + { + return "1.41:1"; + } + + if (IsClose(ratio, 1.5)) + { + return "1.5:1"; + } + + if (IsClose(ratio, 1.6)) + { + return "1.6:1"; + } + + if (IsClose(ratio, 1.66666666667)) + { + return "5:3"; + } + + if (IsClose(ratio, 1.85, .02)) + { + return "1.85:1"; + } + + if (IsClose(ratio, 2.35, .025)) + { + return "2.35:1"; + } + + if (IsClose(ratio, 2.4, .025)) + { + return "2.40:1"; + } + } + + return original; + } + + private static bool IsClose(double d1, double d2, double variance = .005) + { + return Math.Abs(d1 - d2) <= variance; + } + + /// + /// Gets a frame rate from a string value in ffprobe output + /// This could be a number or in the format of 2997/125. + /// + /// The value. + /// System.Nullable{System.Single}. + private static float? GetFrameRate(string value) + { + if (!string.IsNullOrEmpty(value)) + { + var parts = value.Split('/'); + + float result; + + if (parts.Length == 2) + { + result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture); + } + else + { + result = float.Parse(parts[0], UsCulture); + } + + return float.IsNaN(result) ? (float?)null : result; + } + + return null; + } + + } +} diff --git a/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs b/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs deleted file mode 100644 index e3604eb0e..000000000 --- a/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs +++ /dev/null @@ -1,297 +0,0 @@ -using MediaBrowser.Common.Extensions; -using MediaBrowser.Common.IO; -using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Movies; -using MediaBrowser.Controller.Entities.TV; -using MediaBrowser.Controller.Persistence; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Controller.MediaInfo -{ - /// - /// Class FFMpegManager - /// - public class FFMpegManager - { - private readonly IServerConfigurationManager _config; - private readonly IMediaEncoder _encoder; - private readonly ILogger _logger; - private readonly IItemRepository _itemRepo; - - private readonly IFileSystem _fileSystem; - - public static FFMpegManager Instance { get; private set; } - - /// - /// Initializes a new instance of the class. - /// - /// The encoder. - /// The logger. - /// The item repo. - /// zipClient - public FFMpegManager(IMediaEncoder encoder, ILogger logger, IItemRepository itemRepo, IFileSystem fileSystem, IServerConfigurationManager config) - { - _encoder = encoder; - _logger = logger; - _itemRepo = itemRepo; - _fileSystem = fileSystem; - _config = config; - - // TODO: Remove this static instance - Instance = this; - } - - /// - /// Gets the chapter images data path. - /// - /// The chapter images data path. - public string ChapterImagesPath - { - get - { - return Path.Combine(_config.ApplicationPaths.DataPath, "chapter-images"); - } - } - - /// - /// Gets the subtitle cache path. - /// - /// The subtitle cache path. - private string SubtitleCachePath - { - get - { - return Path.Combine(_config.ApplicationPaths.CachePath, "subtitles"); - } - } - - /// - /// Determines whether [is eligible for chapter image extraction] [the specified video]. - /// - /// The video. - /// true if [is eligible for chapter image extraction] [the specified video]; otherwise, false. - private bool IsEligibleForChapterImageExtraction(Video video) - { - if (video is Movie) - { - if (!_config.Configuration.EnableMovieChapterImageExtraction) - { - return false; - } - } - else if (video is Episode) - { - if (!_config.Configuration.EnableEpisodeChapterImageExtraction) - { - return false; - } - } - else - { - if (!_config.Configuration.EnableOtherVideoChapterImageExtraction) - { - return false; - } - } - - // Can't extract images if there are no video streams - return video.DefaultVideoStreamIndex.HasValue; - } - - /// - /// The first chapter ticks - /// - private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks; - - /// - /// Extracts the chapter images. - /// - /// The video. - /// The chapters. - /// if set to true [extract images]. - /// if set to true [save chapters]. - /// The cancellation token. - /// Task. - /// - public async Task PopulateChapterImages(Video video, List chapters, bool extractImages, bool saveChapters, CancellationToken cancellationToken) - { - if (!IsEligibleForChapterImageExtraction(video)) - { - extractImages = false; - } - - var success = true; - var changesMade = false; - - var runtimeTicks = video.RunTimeTicks ?? 0; - - var currentImages = GetSavedChapterImages(video); - - foreach (var chapter in chapters) - { - if (chapter.StartPositionTicks >= runtimeTicks) - { - _logger.Info("Stopping chapter extraction for {0} because a chapter was found with a position greater than the runtime.", video.Name); - break; - } - - var path = GetChapterImagePath(video, chapter.StartPositionTicks); - - if (!currentImages.Contains(path, StringComparer.OrdinalIgnoreCase)) - { - if (extractImages) - { - if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso) - { - continue; - } - - if (video.VideoType == VideoType.BluRay) - { - // Can only extract reliably on single file blurays - if (video.PlayableStreamFileNames == null || video.PlayableStreamFileNames.Count != 1) - { - continue; - } - } - - // Add some time for the first chapter to make sure we don't end up with a black image - var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks); - - InputType type; - - var inputPath = MediaEncoderHelpers.GetInputArgument(video.Path, false, video.VideoType, video.IsoType, null, video.PlayableStreamFileNames, out type); - - try - { - var parentPath = Path.GetDirectoryName(path); - - Directory.CreateDirectory(parentPath); - - using (var stream = await _encoder.ExtractImage(inputPath, type, false, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false)) - { - using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true)) - { - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - } - } - - chapter.ImagePath = path; - changesMade = true; - } - catch - { - success = false; - break; - } - } - else if (!string.IsNullOrEmpty(chapter.ImagePath)) - { - chapter.ImagePath = null; - changesMade = true; - } - } - else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase)) - { - chapter.ImagePath = path; - changesMade = true; - } - } - - if (saveChapters && changesMade) - { - await _itemRepo.SaveChapters(video.Id, chapters, cancellationToken).ConfigureAwait(false); - } - - DeleteDeadImages(currentImages, chapters); - - return success; - } - - private void DeleteDeadImages(IEnumerable images, IEnumerable chapters) - { - var deadImages = images - .Except(chapters.Select(i => i.ImagePath).Where(i => !string.IsNullOrEmpty(i)), StringComparer.OrdinalIgnoreCase) - .Where(i => BaseItem.SupportedImageExtensions.Contains(Path.GetExtension(i), StringComparer.OrdinalIgnoreCase)) - .ToList(); - - foreach (var image in deadImages) - { - _logger.Debug("Deleting dead chapter image {0}", image); - - try - { - File.Delete(image); - } - catch (IOException ex) - { - _logger.ErrorException("Error deleting {0}.", ex, image); - } - } - } - - private readonly CultureInfo _usCulture = new CultureInfo("en-US"); - - /// - /// Gets the subtitle cache path. - /// - /// The media path. - /// The subtitle stream. - /// The output extension. - /// System.String. - public string GetSubtitleCachePath(string mediaPath, MediaStream subtitleStream, string outputExtension) - { - var ticksParam = string.Empty; - - if (subtitleStream.IsExternal) - { - ticksParam += _fileSystem.GetLastWriteTimeUtc(subtitleStream.Path).Ticks; - } - - var date = _fileSystem.GetLastWriteTimeUtc(mediaPath); - - var filename = (mediaPath + "_" + subtitleStream.Index.ToString(_usCulture) + "_" + date.Ticks.ToString(_usCulture) + ticksParam).GetMD5() + outputExtension; - - var prefix = filename.Substring(0, 1); - - return Path.Combine(SubtitleCachePath, prefix, filename); - } - - public string GetChapterImagePath(Video video, long chapterPositionTicks) - { - var filename = video.DateModified.Ticks.ToString(_usCulture) + "_" + chapterPositionTicks.ToString(_usCulture) + ".jpg"; - - var videoId = video.Id.ToString(); - var prefix = videoId.Substring(0, 1); - - return Path.Combine(ChapterImagesPath, prefix, videoId, filename); - } - - public List GetSavedChapterImages(Video video) - { - var videoId = video.Id.ToString(); - var prefix = videoId.Substring(0, 1); - - var path = Path.Combine(ChapterImagesPath, prefix, videoId); - - try - { - return Directory.EnumerateFiles(path) - .ToList(); - } - catch (DirectoryNotFoundException) - { - return new List(); - } - } - } -} diff --git a/MediaBrowser.Controller/MediaInfo/IMediaEncoder.cs b/MediaBrowser.Controller/MediaInfo/IMediaEncoder.cs deleted file mode 100644 index d8cad48b3..000000000 --- a/MediaBrowser.Controller/MediaInfo/IMediaEncoder.cs +++ /dev/null @@ -1,108 +0,0 @@ -using MediaBrowser.Model.Entities; -using System; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Controller.MediaInfo -{ - /// - /// Interface IMediaEncoder - /// - public interface IMediaEncoder - { - /// - /// Gets the encoder path. - /// - /// The encoder path. - string EncoderPath { get; } - - /// - /// Gets the version. - /// - /// The version. - string Version { get; } - - /// - /// Extracts the image. - /// - /// The input files. - /// The type. - /// if set to true [is audio]. - /// The threed format. - /// The offset. - /// The cancellation token. - /// Task{Stream}. - Task ExtractImage(string[] inputFiles, InputType type, bool isAudio, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); - - /// - /// Extracts the text subtitle. - /// - /// The input files. - /// The type. - /// Index of the subtitle stream. - /// if set to true, copy stream instead of converting. - /// The output path. - /// The cancellation token. - /// Task. - Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, bool copySubtitleStream, string outputPath, CancellationToken cancellationToken); - - /// - /// Converts the text subtitle to ass. - /// - /// The input path. - /// The output path. - /// The language. - /// The cancellation token. - /// Task. - Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language, CancellationToken cancellationToken); - - /// - /// Gets the media info. - /// - /// The input files. - /// The type. - /// if set to true [is audio]. - /// The cancellation token. - /// Task. - Task GetMediaInfo(string[] inputFiles, InputType type, bool isAudio, CancellationToken cancellationToken); - - /// - /// Gets the probe size argument. - /// - /// The type. - /// System.String. - string GetProbeSizeArgument(InputType type); - - /// - /// Gets the input argument. - /// - /// The input files. - /// The type. - /// System.String. - string GetInputArgument(string[] inputFiles, InputType type); - } - - /// - /// Enum InputType - /// - public enum InputType - { - /// - /// The file - /// - File, - /// - /// The bluray - /// - Bluray, - /// - /// The DVD - /// - Dvd, - /// - /// The URL - /// - Url - } -} diff --git a/MediaBrowser.Controller/MediaInfo/InternalMediaInfoResult.cs b/MediaBrowser.Controller/MediaInfo/InternalMediaInfoResult.cs deleted file mode 100644 index 3ceec1b90..000000000 --- a/MediaBrowser.Controller/MediaInfo/InternalMediaInfoResult.cs +++ /dev/null @@ -1,311 +0,0 @@ -using System.Collections.Generic; -using MediaBrowser.Model.Entities; - -namespace MediaBrowser.Controller.MediaInfo -{ - /// - /// Class MediaInfoResult - /// - public class InternalMediaInfoResult - { - /// - /// Gets or sets the streams. - /// - /// The streams. - public MediaStreamInfo[] streams { get; set; } - - /// - /// Gets or sets the format. - /// - /// The format. - public MediaFormatInfo format { get; set; } - - /// - /// Gets or sets the chapters. - /// - /// The chapters. - public List Chapters { get; set; } - } - - /// - /// Represents a stream within the output - /// - public class MediaStreamInfo - { - /// - /// Gets or sets the index. - /// - /// The index. - public int index { get; set; } - - /// - /// Gets or sets the profile. - /// - /// The profile. - public string profile { get; set; } - - /// - /// Gets or sets the codec_name. - /// - /// The codec_name. - public string codec_name { get; set; } - - /// - /// Gets or sets the codec_long_name. - /// - /// The codec_long_name. - public string codec_long_name { get; set; } - - /// - /// Gets or sets the codec_type. - /// - /// The codec_type. - public string codec_type { get; set; } - - /// - /// Gets or sets the sample_rate. - /// - /// The sample_rate. - public string sample_rate { get; set; } - - /// - /// Gets or sets the channels. - /// - /// The channels. - public int channels { get; set; } - - /// - /// Gets or sets the channel_layout. - /// - /// The channel_layout. - public string channel_layout { get; set; } - - /// - /// Gets or sets the avg_frame_rate. - /// - /// The avg_frame_rate. - public string avg_frame_rate { get; set; } - - /// - /// Gets or sets the duration. - /// - /// The duration. - public string duration { get; set; } - - /// - /// Gets or sets the bit_rate. - /// - /// The bit_rate. - public string bit_rate { get; set; } - - /// - /// Gets or sets the width. - /// - /// The width. - public int width { get; set; } - - /// - /// Gets or sets the height. - /// - /// The height. - public int height { get; set; } - - /// - /// Gets or sets the display_aspect_ratio. - /// - /// The display_aspect_ratio. - public string display_aspect_ratio { get; set; } - - /// - /// Gets or sets the tags. - /// - /// The tags. - public Dictionary tags { get; set; } - - /// - /// Gets or sets the bits_per_sample. - /// - /// The bits_per_sample. - public int bits_per_sample { get; set; } - - /// - /// Gets or sets the r_frame_rate. - /// - /// The r_frame_rate. - public string r_frame_rate { get; set; } - - /// - /// Gets or sets the has_b_frames. - /// - /// The has_b_frames. - public int has_b_frames { get; set; } - - /// - /// Gets or sets the sample_aspect_ratio. - /// - /// The sample_aspect_ratio. - public string sample_aspect_ratio { get; set; } - - /// - /// Gets or sets the pix_fmt. - /// - /// The pix_fmt. - public string pix_fmt { get; set; } - - /// - /// Gets or sets the level. - /// - /// The level. - public int level { get; set; } - - /// - /// Gets or sets the time_base. - /// - /// The time_base. - public string time_base { get; set; } - - /// - /// Gets or sets the start_time. - /// - /// The start_time. - public string start_time { get; set; } - - /// - /// Gets or sets the codec_time_base. - /// - /// The codec_time_base. - public string codec_time_base { get; set; } - - /// - /// Gets or sets the codec_tag. - /// - /// The codec_tag. - public string codec_tag { get; set; } - - /// - /// Gets or sets the codec_tag_string. - /// - /// The codec_tag_string. - public string codec_tag_string { get; set; } - - /// - /// Gets or sets the sample_fmt. - /// - /// The sample_fmt. - public string sample_fmt { get; set; } - - /// - /// Gets or sets the dmix_mode. - /// - /// The dmix_mode. - public string dmix_mode { get; set; } - - /// - /// Gets or sets the start_pts. - /// - /// The start_pts. - public string start_pts { get; set; } - - /// - /// Gets or sets the is_avc. - /// - /// The is_avc. - public string is_avc { get; set; } - - /// - /// Gets or sets the nal_length_size. - /// - /// The nal_length_size. - public string nal_length_size { get; set; } - - /// - /// Gets or sets the ltrt_cmixlev. - /// - /// The ltrt_cmixlev. - public string ltrt_cmixlev { get; set; } - - /// - /// Gets or sets the ltrt_surmixlev. - /// - /// The ltrt_surmixlev. - public string ltrt_surmixlev { get; set; } - - /// - /// Gets or sets the loro_cmixlev. - /// - /// The loro_cmixlev. - public string loro_cmixlev { get; set; } - - /// - /// Gets or sets the loro_surmixlev. - /// - /// The loro_surmixlev. - public string loro_surmixlev { get; set; } - - /// - /// Gets or sets the disposition. - /// - /// The disposition. - public Dictionary disposition { get; set; } - } - - /// - /// Class MediaFormat - /// - public class MediaFormatInfo - { - /// - /// Gets or sets the filename. - /// - /// The filename. - public string filename { get; set; } - - /// - /// Gets or sets the nb_streams. - /// - /// The nb_streams. - public int nb_streams { get; set; } - - /// - /// Gets or sets the format_name. - /// - /// The format_name. - public string format_name { get; set; } - - /// - /// Gets or sets the format_long_name. - /// - /// The format_long_name. - public string format_long_name { get; set; } - - /// - /// Gets or sets the start_time. - /// - /// The start_time. - public string start_time { get; set; } - - /// - /// Gets or sets the duration. - /// - /// The duration. - public string duration { get; set; } - - /// - /// Gets or sets the size. - /// - /// The size. - public string size { get; set; } - - /// - /// Gets or sets the bit_rate. - /// - /// The bit_rate. - public string bit_rate { get; set; } - - /// - /// Gets or sets the tags. - /// - /// The tags. - public Dictionary tags { get; set; } - } -} diff --git a/MediaBrowser.Controller/MediaInfo/MediaEncoderHelpers.cs b/MediaBrowser.Controller/MediaInfo/MediaEncoderHelpers.cs deleted file mode 100644 index 300071b7b..000000000 --- a/MediaBrowser.Controller/MediaInfo/MediaEncoderHelpers.cs +++ /dev/null @@ -1,365 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; - -namespace MediaBrowser.Controller.MediaInfo -{ - /// - /// Class MediaEncoderHelpers - /// - public static class MediaEncoderHelpers - { - /// - /// Gets the input argument. - /// - /// The video path. - /// if set to true [is remote]. - /// Type of the video. - /// Type of the iso. - /// The iso mount. - /// The playable stream file names. - /// The type. - /// System.String[][]. - public static string[] GetInputArgument(string videoPath, bool isRemote, VideoType videoType, IsoType? isoType, IIsoMount isoMount, IEnumerable playableStreamFileNames, out InputType type) - { - var inputPath = isoMount == null ? new[] { videoPath } : new[] { isoMount.MountedPath }; - - type = InputType.File; - - switch (videoType) - { - case VideoType.BluRay: - type = InputType.Bluray; - break; - case VideoType.Dvd: - type = InputType.Dvd; - inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray(); - break; - case VideoType.Iso: - if (isoType.HasValue) - { - switch (isoType.Value) - { - case IsoType.BluRay: - type = InputType.Bluray; - break; - case IsoType.Dvd: - type = InputType.Dvd; - inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray(); - break; - } - } - break; - case VideoType.VideoFile: - { - if (isRemote) - { - type = InputType.Url; - } - break; - } - } - - return inputPath; - } - - public static List GetPlayableStreamFiles(string rootPath, IEnumerable filenames) - { - var allFiles = Directory - .EnumerateFiles(rootPath, "*", SearchOption.AllDirectories) - .ToList(); - - return filenames.Select(name => allFiles.FirstOrDefault(f => string.Equals(Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase))) - .Where(f => !string.IsNullOrEmpty(f)) - .ToList(); - } - - /// - /// Gets the type of the input. - /// - /// Type of the video. - /// Type of the iso. - /// InputType. - public static InputType GetInputType(VideoType? videoType, IsoType? isoType) - { - var type = InputType.File; - - if (videoType.HasValue) - { - switch (videoType.Value) - { - case VideoType.BluRay: - type = InputType.Bluray; - break; - case VideoType.Dvd: - type = InputType.Dvd; - break; - case VideoType.Iso: - if (isoType.HasValue) - { - switch (isoType.Value) - { - case IsoType.BluRay: - type = InputType.Bluray; - break; - case IsoType.Dvd: - type = InputType.Dvd; - break; - } - } - break; - } - } - - return type; - } - - public static Model.Entities.MediaInfo GetMediaInfo(InternalMediaInfoResult data) - { - var internalStreams = data.streams ?? new MediaStreamInfo[] { }; - - var info = new Model.Entities.MediaInfo(); - - info.MediaStreams = internalStreams.Select(s => GetMediaStream(s, data.format)) - .Where(i => i != null) - .ToList(); - - if (data.format != null) - { - info.Format = data.format.format_name; - } - - return info; - } - - private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - - /// - /// Converts ffprobe stream info to our MediaStream class - /// - /// The stream info. - /// The format info. - /// MediaStream. - private static MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo) - { - var stream = new MediaStream - { - Codec = streamInfo.codec_name, - Profile = streamInfo.profile, - Level = streamInfo.level, - Index = streamInfo.index - }; - - if (streamInfo.tags != null) - { - stream.Language = GetDictionaryValue(streamInfo.tags, "language"); - } - - if (string.Equals(streamInfo.codec_type, "audio", StringComparison.OrdinalIgnoreCase)) - { - stream.Type = MediaStreamType.Audio; - - stream.Channels = streamInfo.channels; - - if (!string.IsNullOrEmpty(streamInfo.sample_rate)) - { - stream.SampleRate = int.Parse(streamInfo.sample_rate, UsCulture); - } - - stream.ChannelLayout = ParseChannelLayout(streamInfo.channel_layout); - } - else if (string.Equals(streamInfo.codec_type, "subtitle", StringComparison.OrdinalIgnoreCase)) - { - stream.Type = MediaStreamType.Subtitle; - } - else if (string.Equals(streamInfo.codec_type, "video", StringComparison.OrdinalIgnoreCase)) - { - stream.Type = MediaStreamType.Video; - - stream.Width = streamInfo.width; - stream.Height = streamInfo.height; - stream.AspectRatio = GetAspectRatio(streamInfo); - - stream.AverageFrameRate = GetFrameRate(streamInfo.avg_frame_rate); - stream.RealFrameRate = GetFrameRate(streamInfo.r_frame_rate); - } - else - { - return null; - } - - // Get stream bitrate - if (stream.Type != MediaStreamType.Subtitle) - { - var bitrate = 0; - - if (!string.IsNullOrEmpty(streamInfo.bit_rate)) - { - bitrate = int.Parse(streamInfo.bit_rate, UsCulture); - } - else if (formatInfo != null && !string.IsNullOrEmpty(formatInfo.bit_rate)) - { - // If the stream info doesn't have a bitrate get the value from the media format info - bitrate = int.Parse(formatInfo.bit_rate, UsCulture); - } - - if (bitrate > 0) - { - stream.BitRate = bitrate; - } - } - - if (streamInfo.disposition != null) - { - var isDefault = GetDictionaryValue(streamInfo.disposition, "default"); - var isForced = GetDictionaryValue(streamInfo.disposition, "forced"); - - stream.IsDefault = string.Equals(isDefault, "1", StringComparison.OrdinalIgnoreCase); - - stream.IsForced = string.Equals(isForced, "1", StringComparison.OrdinalIgnoreCase); - } - - return stream; - } - - /// - /// Gets a string from an FFProbeResult tags dictionary - /// - /// The tags. - /// The key. - /// System.String. - private static string GetDictionaryValue(Dictionary tags, string key) - { - if (tags == null) - { - return null; - } - - string val; - - tags.TryGetValue(key, out val); - return val; - } - - private static string ParseChannelLayout(string input) - { - if (string.IsNullOrEmpty(input)) - { - return input; - } - - return input.Split('(').FirstOrDefault(); - } - - private static string GetAspectRatio(MediaStreamInfo info) - { - var original = info.display_aspect_ratio; - - int height; - int width; - - var parts = (original ?? string.Empty).Split(':'); - if (!(parts.Length == 2 && - int.TryParse(parts[0], NumberStyles.Any, UsCulture, out width) && - int.TryParse(parts[1], NumberStyles.Any, UsCulture, out height) && - width > 0 && - height > 0)) - { - width = info.width; - height = info.height; - } - - if (width > 0 && height > 0) - { - double ratio = width; - ratio /= height; - - if (IsClose(ratio, 1.777777778, .03)) - { - return "16:9"; - } - - if (IsClose(ratio, 1.3333333333, .05)) - { - return "4:3"; - } - - if (IsClose(ratio, 1.41)) - { - return "1.41:1"; - } - - if (IsClose(ratio, 1.5)) - { - return "1.5:1"; - } - - if (IsClose(ratio, 1.6)) - { - return "1.6:1"; - } - - if (IsClose(ratio, 1.66666666667)) - { - return "5:3"; - } - - if (IsClose(ratio, 1.85, .02)) - { - return "1.85:1"; - } - - if (IsClose(ratio, 2.35, .025)) - { - return "2.35:1"; - } - - if (IsClose(ratio, 2.4, .025)) - { - return "2.40:1"; - } - } - - return original; - } - - private static bool IsClose(double d1, double d2, double variance = .005) - { - return Math.Abs(d1 - d2) <= variance; - } - - /// - /// Gets a frame rate from a string value in ffprobe output - /// This could be a number or in the format of 2997/125. - /// - /// The value. - /// System.Nullable{System.Single}. - private static float? GetFrameRate(string value) - { - if (!string.IsNullOrEmpty(value)) - { - var parts = value.Split('/'); - - float result; - - if (parts.Length == 2) - { - result = float.Parse(parts[0], UsCulture) / float.Parse(parts[1], UsCulture); - } - else - { - result = float.Parse(parts[0], UsCulture); - } - - return float.IsNaN(result) ? (float?)null : result; - } - - return null; - } - - } -} -- cgit v1.2.3