From cb39f8e7b5f71dcf0de2681d953b016e29adbc54 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 7 Apr 2013 16:55:05 -0400 Subject: extracted a media encoding interface to keep ffmpeg out of nuget packages --- MediaBrowser.Controller/Drawing/ImageManager.cs | 25 +- .../MediaBrowser.Controller.csproj | 12 +- MediaBrowser.Controller/MediaInfo/FFMpegManager.cs | 977 +-------------------- MediaBrowser.Controller/MediaInfo/FFProbeResult.cs | 354 -------- .../MediaInfo/ffmpeg20130405.zip.REMOVED.git-id | 1 - MediaBrowser.Controller/MediaInfo/fonts/fonts.conf | 9 - MediaBrowser.Controller/MediaInfo/readme.txt | 5 - .../Providers/IProviderManager.cs | 7 +- .../Providers/MediaInfo/BaseFFMpegProvider.cs | 8 +- .../Providers/MediaInfo/BaseFFProbeProvider.cs | 99 ++- .../MediaInfo/FFMpegAudioImageProvider.cs | 18 +- .../MediaInfo/FFMpegVideoImageProvider.cs | 45 +- .../MediaInfo/FFProbeAudioInfoProvider.cs | 11 +- .../MediaInfo/FFProbeVideoInfoProvider.cs | 32 +- .../Providers/MediaInfo/MediaEncoderHelpers.cs | 96 ++ 15 files changed, 239 insertions(+), 1460 deletions(-) delete mode 100644 MediaBrowser.Controller/MediaInfo/FFProbeResult.cs delete mode 100644 MediaBrowser.Controller/MediaInfo/ffmpeg20130405.zip.REMOVED.git-id delete mode 100644 MediaBrowser.Controller/MediaInfo/fonts/fonts.conf delete mode 100644 MediaBrowser.Controller/MediaInfo/readme.txt create mode 100644 MediaBrowser.Controller/Providers/MediaInfo/MediaEncoderHelpers.cs (limited to 'MediaBrowser.Controller') diff --git a/MediaBrowser.Controller/Drawing/ImageManager.cs b/MediaBrowser.Controller/Drawing/ImageManager.cs index a5e36da329..b47ae164aa 100644 --- a/MediaBrowser.Controller/Drawing/ImageManager.cs +++ b/MediaBrowser.Controller/Drawing/ImageManager.cs @@ -23,7 +23,7 @@ namespace MediaBrowser.Controller.Drawing /// /// Class ImageManager /// - public class ImageManager : IDisposable + public class ImageManager { /// /// Gets the image size cache. @@ -681,28 +681,5 @@ namespace MediaBrowser.Controller.Drawing { return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1)); } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected void Dispose(bool dispose) - { - if (dispose) - { - ImageSizeCache.Dispose(); - ResizedImageCache.Dispose(); - CroppedImageCache.Dispose(); - EnhancedImageCache.Dispose(); - } - } } } diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 48662fe220..d3a9b0a3fe 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -53,8 +53,7 @@ MinimumRecommendedRules.ruleset - - False + ..\packages\protobuf-net.2.0.0.621\lib\net40\protobuf-net.dll @@ -111,6 +110,7 @@ + @@ -134,7 +134,6 @@ - @@ -201,15 +200,8 @@ - - - - - - - if $(ConfigurationName) == Release ( diff --git a/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs b/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs index 9bfebccde8..f262c6c68d 100644 --- a/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs +++ b/MediaBrowser.Controller/MediaInfo/FFMpegManager.cs @@ -1,19 +1,11 @@ -using System.Text; -using MediaBrowser.Common.IO; +using MediaBrowser.Common.IO; +using MediaBrowser.Common.MediaInfo; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Providers.MediaInfo; using MediaBrowser.Model.Entities; -using MediaBrowser.Model.IO; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; using System.IO; using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; @@ -22,7 +14,7 @@ namespace MediaBrowser.Controller.MediaInfo /// /// Class FFMpegManager /// - public class FFMpegManager : IDisposable + public class FFMpegManager { /// /// Gets or sets the video image cache. @@ -42,170 +34,35 @@ namespace MediaBrowser.Controller.MediaInfo /// The subtitle cache. internal FileSystemRepository SubtitleCache { get; set; } - /// - /// Gets or sets the zip client. - /// - /// The zip client. - private readonly IZipClient _zipClient; - /// /// The _logger /// private readonly Kernel _kernel; - /// - /// The _logger - /// - private readonly ILogger _logger; - - /// - /// Gets the json serializer. - /// - /// The json serializer. - private readonly IJsonSerializer _jsonSerializer; - - /// - /// The _protobuf serializer - /// - private readonly IProtobufSerializer _protobufSerializer; private readonly IServerApplicationPaths _appPaths; + private readonly IMediaEncoder _encoder; /// /// Initializes a new instance of the class. /// /// The kernel. - /// The zip client. - /// The json serializer. - /// The protobuf serializer. - /// The logger. + /// The app paths. + /// The encoder. /// zipClient - public FFMpegManager(Kernel kernel, IZipClient zipClient, IJsonSerializer jsonSerializer, IProtobufSerializer protobufSerializer, ILogManager logManager, IServerApplicationPaths appPaths) + public FFMpegManager(Kernel kernel, IServerApplicationPaths appPaths, IMediaEncoder encoder) { if (kernel == null) { throw new ArgumentNullException("kernel"); } - if (zipClient == null) - { - throw new ArgumentNullException("zipClient"); - } - if (jsonSerializer == null) - { - throw new ArgumentNullException("jsonSerializer"); - } - if (protobufSerializer == null) - { - throw new ArgumentNullException("protobufSerializer"); - } _kernel = kernel; - _zipClient = zipClient; - _jsonSerializer = jsonSerializer; - _protobufSerializer = protobufSerializer; _appPaths = appPaths; - _logger = logManager.GetLogger("FFMpegManager"); - - // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes - SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX); + _encoder = encoder; VideoImageCache = new FileSystemRepository(VideoImagesDataPath); AudioImageCache = new FileSystemRepository(AudioImagesDataPath); SubtitleCache = new FileSystemRepository(SubtitleCachePath); - - Task.Run(() => VersionedDirectoryPath = GetVersionedDirectoryPath()); - } - - public void Dispose() - { - Dispose(true); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected void Dispose(bool dispose) - { - if (dispose) - { - SetErrorMode(ErrorModes.SYSTEM_DEFAULT); - - AudioImageCache.Dispose(); - VideoImageCache.Dispose(); - } - } - - /// - /// The FF probe resource pool count - /// - private const int FFProbeResourcePoolCount = 3; - /// - /// The audio image resource pool count - /// - private const int AudioImageResourcePoolCount = 3; - /// - /// The video image resource pool count - /// - private const int VideoImageResourcePoolCount = 2; - - /// - /// The FF probe resource pool - /// - private readonly SemaphoreSlim FFProbeResourcePool = new SemaphoreSlim(FFProbeResourcePoolCount, FFProbeResourcePoolCount); - /// - /// The audio image resource pool - /// - private readonly SemaphoreSlim AudioImageResourcePool = new SemaphoreSlim(AudioImageResourcePoolCount, AudioImageResourcePoolCount); - /// - /// The video image resource pool - /// - private readonly SemaphoreSlim VideoImageResourcePool = new SemaphoreSlim(VideoImageResourcePoolCount, VideoImageResourcePoolCount); - - /// - /// Gets or sets the versioned directory path. - /// - /// The versioned directory path. - private string VersionedDirectoryPath { get; set; } - - /// - /// Gets the FFMPEG version. - /// - /// The FFMPEG version. - public string FFMpegVersion - { - get { return Path.GetFileNameWithoutExtension(VersionedDirectoryPath); } - } - - /// - /// The _ FF MPEG path - /// - private string _FFMpegPath; - /// - /// Gets the path to ffmpeg.exe - /// - /// The FF MPEG path. - public string FFMpegPath - { - get - { - return _FFMpegPath ?? (_FFMpegPath = Path.Combine(VersionedDirectoryPath, "ffmpeg.exe")); - } - } - - /// - /// The _ FF probe path - /// - private string _FFProbePath; - /// - /// Gets the path to ffprobe.exe - /// - /// The FF probe path. - public string FFProbePath - { - get - { - return _FFProbePath ?? (_FFProbePath = Path.Combine(VersionedDirectoryPath, "ffprobe.exe")); - } } /// @@ -222,7 +79,7 @@ namespace MediaBrowser.Controller.MediaInfo { if (_videoImagesDataPath == null) { - _videoImagesDataPath = Path.Combine(_appPaths.DataPath, "ffmpeg-video-images"); + _videoImagesDataPath = Path.Combine(_appPaths.DataPath, "extracted-video-images"); if (!Directory.Exists(_videoImagesDataPath)) { @@ -248,7 +105,7 @@ namespace MediaBrowser.Controller.MediaInfo { if (_audioImagesDataPath == null) { - _audioImagesDataPath = Path.Combine(_appPaths.DataPath, "ffmpeg-audio-images"); + _audioImagesDataPath = Path.Combine(_appPaths.DataPath, "extracted-audio-images"); if (!Directory.Exists(_audioImagesDataPath)) { @@ -274,7 +131,7 @@ namespace MediaBrowser.Controller.MediaInfo { if (_subtitleCachePath == null) { - _subtitleCachePath = Path.Combine(_appPaths.CachePath, "ffmpeg-subtitles"); + _subtitleCachePath = Path.Combine(_appPaths.CachePath, "subtitles"); if (!Directory.Exists(_subtitleCachePath)) { @@ -286,386 +143,10 @@ namespace MediaBrowser.Controller.MediaInfo } } - /// - /// The _media tools path - /// - private string _mediaToolsPath; - /// - /// Gets the folder path to tools - /// - /// The media tools path. - private string MediaToolsPath - { - get - { - if (_mediaToolsPath == null) - { - _mediaToolsPath = Path.Combine(_appPaths.ProgramDataPath, "ffmpeg"); - - if (!Directory.Exists(_mediaToolsPath)) - { - Directory.CreateDirectory(_mediaToolsPath); - } - } - - return _mediaToolsPath; - } - } - - /// - /// Gets the versioned directory path. - /// - /// System.String. - private string GetVersionedDirectoryPath() - { - var assembly = GetType().Assembly; - - const string prefix = "MediaBrowser.Controller.MediaInfo."; - const string srch = prefix + "ffmpeg"; - - var resource = assembly.GetManifestResourceNames().First(r => r.StartsWith(srch)); - - var filename = resource.Substring(resource.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) + prefix.Length); - - var versionedDirectoryPath = Path.Combine(MediaToolsPath, Path.GetFileNameWithoutExtension(filename)); - - if (!Directory.Exists(versionedDirectoryPath)) - { - Directory.CreateDirectory(versionedDirectoryPath); - } - - ExtractTools(assembly, resource, versionedDirectoryPath); - - return versionedDirectoryPath; - } - - /// - /// Extracts the tools. - /// - /// The assembly. - /// The zip file resource path. - /// The target path. - private void ExtractTools(Assembly assembly, string zipFileResourcePath, string targetPath) - { - using (var resourceStream = assembly.GetManifestResourceStream(zipFileResourcePath)) - { - _zipClient.ExtractAll(resourceStream, targetPath, false); - } - - ExtractFonts(assembly, targetPath); - } - - /// - /// Extracts the fonts. - /// - /// The assembly. - /// The target path. - private async void ExtractFonts(Assembly assembly, string targetPath) - { - var fontsDirectory = Path.Combine(targetPath, "fonts"); - - if (!Directory.Exists(fontsDirectory)) - { - Directory.CreateDirectory(fontsDirectory); - } - - const string fontFilename = "ARIALUNI.TTF"; - - var fontFile = Path.Combine(fontsDirectory, fontFilename); - - if (!File.Exists(fontFile)) - { - using (var stream = assembly.GetManifestResourceStream("MediaBrowser.Controller.MediaInfo.fonts." + fontFilename)) - { - using (var fileStream = new FileStream(fontFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous)) - { - await stream.CopyToAsync(fileStream).ConfigureAwait(false); - } - } - } - - await ExtractFontConfigFile(assembly, fontsDirectory).ConfigureAwait(false); - } - - /// - /// Extracts the font config file. - /// - /// The assembly. - /// The fonts directory. - private async Task ExtractFontConfigFile(Assembly assembly, string fontsDirectory) - { - const string fontConfigFilename = "fonts.conf"; - var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename); - - if (!File.Exists(fontConfigFile)) - { - using (var stream = assembly.GetManifestResourceStream("MediaBrowser.Controller.MediaInfo.fonts." + fontConfigFilename)) - { - using (var streamReader = new StreamReader(stream)) - { - var contents = await streamReader.ReadToEndAsync().ConfigureAwait(false); - - contents = contents.Replace("", "" + fontsDirectory + ""); - - var bytes = Encoding.UTF8.GetBytes(contents); - - using (var fileStream = new FileStream(fontConfigFile, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous)) - { - await fileStream.WriteAsync(bytes, 0, bytes.Length); - } - } - } - } - } - - /// - /// Gets the probe size argument. - /// - /// The item. - /// System.String. - public string GetProbeSizeArgument(BaseItem item) - { - var video = item as Video; - - return video != null ? GetProbeSizeArgument(video.VideoType, video.IsoType) : string.Empty; - } - - /// - /// Gets the probe size argument. - /// - /// Type of the video. - /// Type of the iso. - /// System.String. - public string GetProbeSizeArgument(VideoType videoType, IsoType? isoType) - { - if (videoType == VideoType.Dvd || (isoType.HasValue && isoType.Value == IsoType.Dvd)) - { - return "-probesize 1G -analyzeduration 200M"; - } - - return string.Empty; - } - - /// - /// Runs FFProbe against a BaseItem - /// - /// The item. - /// The input path. - /// The last date modified. - /// The cache. - /// The cancellation token. - /// Task{FFProbeResult}. - /// item - public Task RunFFProbe(BaseItem item, string inputPath, DateTime lastDateModified, FileSystemRepository cache, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(inputPath)) - { - throw new ArgumentNullException("inputPath"); - } - - if (cache == null) - { - throw new ArgumentNullException("cache"); - } - - // Put the ffmpeg version into the cache name so that it's unique per-version - // We don't want to try and deserialize data based on an old version, which could potentially fail - var resourceName = item.Id + "_" + lastDateModified.Ticks + "_" + FFMpegVersion; - - // Forumulate the cache file path - var cacheFilePath = cache.GetResourcePath(resourceName, ".pb"); - - cancellationToken.ThrowIfCancellationRequested(); - - // Avoid File.Exists by just trying to deserialize - try - { - return Task.FromResult(_protobufSerializer.DeserializeFromFile(cacheFilePath)); - } - catch (FileNotFoundException) - { - var extractChapters = false; - var video = item as Video; - var probeSizeArgument = string.Empty; - - if (video != null) - { - extractChapters = true; - probeSizeArgument = GetProbeSizeArgument(video.VideoType, video.IsoType); - } - - return RunFFProbeInternal(inputPath, extractChapters, cacheFilePath, probeSizeArgument, cancellationToken); - } - } - - /// - /// Runs FFProbe against a BaseItem - /// - /// The input path. - /// if set to true [extract chapters]. - /// The cache file. - /// The probe size argument. - /// The cancellation token. - /// Task{FFProbeResult}. - /// - private async Task RunFFProbeInternal(string inputPath, bool extractChapters, string cacheFile, string probeSizeArgument, CancellationToken cancellationToken) - { - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - - // Must consume both or ffmpeg may hang due to deadlocks. See comments below. - RedirectStandardOutput = true, - RedirectStandardError = true, - FileName = FFProbePath, - Arguments = string.Format("{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format", probeSizeArgument, inputPath).Trim(), - - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }, - - EnableRaisingEvents = true - }; - - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - - process.Exited += ProcessExited; - - await FFProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - FFProbeResult result; - string standardError = null; - - try - { - process.Start(); - - Task standardErrorReadTask = null; - - // MUST read both stdout and stderr asynchronously or a deadlock may occurr - if (extractChapters) - { - standardErrorReadTask = process.StandardError.ReadToEndAsync(); - } - else - { - process.BeginErrorReadLine(); - } - - result = _jsonSerializer.DeserializeFromStream(process.StandardOutput.BaseStream); - - if (extractChapters) - { - standardError = await standardErrorReadTask.ConfigureAwait(false); - } - } - catch - { - // Hate having to do this - try - { - process.Kill(); - } - catch (InvalidOperationException ex1) - { - _logger.ErrorException("Error killing ffprobe", ex1); - } - catch (Win32Exception ex1) - { - _logger.ErrorException("Error killing ffprobe", ex1); - } - - throw; - } - finally - { - FFProbeResourcePool.Release(); - } - - if (result == null) - { - throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (extractChapters && !string.IsNullOrEmpty(standardError)) - { - AddChapters(result, standardError); - } - - _protobufSerializer.SerializeToFile(result, cacheFile); - - return result; - } - - /// - /// Adds the chapters. - /// - /// The result. - /// The standard error. - private void AddChapters(FFProbeResult result, string standardError) - { - var lines = standardError.Split('\n').Select(l => l.TrimStart()); - - var chapters = new List { }; - - ChapterInfo lastChapter = null; - - foreach (var line in lines) - { - if (line.StartsWith("Chapter", StringComparison.OrdinalIgnoreCase)) - { - // Example: - // Chapter #0.2: start 400.534, end 4565.435 - const string srch = "start "; - var start = line.IndexOf(srch, StringComparison.OrdinalIgnoreCase); - - if (start == -1) - { - continue; - } - - var subString = line.Substring(start + srch.Length); - subString = subString.Substring(0, subString.IndexOf(',')); - - double seconds; - - if (double.TryParse(subString, out seconds)) - { - lastChapter = new ChapterInfo - { - StartPositionTicks = TimeSpan.FromSeconds(seconds).Ticks - }; - - chapters.Add(lastChapter); - } - } - - else if (line.StartsWith("title", StringComparison.OrdinalIgnoreCase)) - { - if (lastChapter != null && string.IsNullOrEmpty(lastChapter.Name)) - { - var index = line.IndexOf(':'); - - if (index != -1) - { - lastChapter.Name = line.Substring(index + 1).Trim().TrimEnd('\r'); - } - } - } - } - - result.Chapters = chapters; - } - /// /// The first chapter ticks /// - private static long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks; + private static readonly long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks; /// /// Extracts the chapter images. @@ -710,14 +191,17 @@ namespace MediaBrowser.Controller.MediaInfo // 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); - var success = await ExtractImage(GetInputArgument(video), time, path, cancellationToken).ConfigureAwait(false); + InputType type; - if (success) + var inputPath = MediaEncoderHelpers.GetInputArgument(video, null, out type); + + try { + await _encoder.ExtractImage(inputPath, type, time, path, cancellationToken).ConfigureAwait(false); chapter.ImagePath = path; changesMade = true; } - else + catch { break; } @@ -736,70 +220,6 @@ namespace MediaBrowser.Controller.MediaInfo } } - /// - /// Extracts an image from an Audio file and returns a Task whose result indicates whether it was successful or not - /// - /// The input path. - /// The output path. - /// The cancellation token. - /// Task{System.Boolean}. - /// input - public async Task ExtractAudioImage(string inputPath, string outputPath, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(inputPath)) - { - throw new ArgumentNullException("inputPath"); - } - - if (string.IsNullOrEmpty(outputPath)) - { - throw new ArgumentNullException("outputPath"); - } - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = FFMpegPath, - Arguments = string.Format("-i {0} -threads 0 -v quiet -f image2 \"{1}\"", GetFileInputArgument(inputPath), outputPath), - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - } - }; - - await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - await RunAsync(process).ConfigureAwait(false); - - AudioImageResourcePool.Release(); - - var exitCode = process.ExitCode; - - process.Dispose(); - - if (exitCode != -1 && File.Exists(outputPath)) - { - return true; - } - - _logger.Error("ffmpeg audio image extraction failed for {0}", inputPath); - return false; - } - - /// - /// Determines whether [is subtitle cached] [the specified input]. - /// - /// The input. - /// Index of the subtitle stream. - /// The output extension. - /// true if [is subtitle cached] [the specified input]; otherwise, false. - public bool IsSubtitleCached(Video input, int subtitleStreamIndex, string outputExtension) - { - return SubtitleCache.ContainsFilePath(GetSubtitleCachePath(input, subtitleStreamIndex, outputExtension)); - } - /// /// Gets the subtitle cache path. /// @@ -811,364 +231,5 @@ namespace MediaBrowser.Controller.MediaInfo { return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks, outputExtension); } - - /// - /// Extracts the text subtitle. - /// - /// The input. - /// Index of the subtitle stream. - /// The output path. - /// The cancellation token. - /// Task{System.Boolean}. - /// input - public async Task ExtractTextSubtitle(Video input, int subtitleStreamIndex, string outputPath, CancellationToken cancellationToken) - { - if (input == null) - { - throw new ArgumentNullException("input"); - } - - if (cancellationToken == null) - { - throw new ArgumentNullException("cancellationToken"); - } - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = FFMpegPath, - Arguments = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", GetInputArgument(input), subtitleStreamIndex, outputPath), - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - } - }; - - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - - await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - await RunAsync(process).ConfigureAwait(false); - - AudioImageResourcePool.Release(); - - var exitCode = process.ExitCode; - - process.Dispose(); - - if (exitCode != -1 && File.Exists(outputPath)) - { - return true; - } - - _logger.Error("ffmpeg subtitle extraction failed for {0}", input.Path); - return false; - } - - /// - /// Converts the text subtitle. - /// - /// The media stream. - /// The output path. - /// The cancellation token. - /// Task{System.Boolean}. - /// mediaStream - /// The given MediaStream is not an external subtitle stream - public async Task ConvertTextSubtitle(MediaStream mediaStream, string outputPath, CancellationToken cancellationToken) - { - if (mediaStream == null) - { - throw new ArgumentNullException("mediaStream"); - } - - if (!mediaStream.IsExternal || string.IsNullOrEmpty(mediaStream.Path)) - { - throw new ArgumentException("The given MediaStream is not an external subtitle stream"); - } - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = FFMpegPath, - Arguments = string.Format("-i \"{0}\" \"{1}\"", mediaStream.Path, outputPath), - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - } - }; - - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - - await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - await RunAsync(process).ConfigureAwait(false); - - AudioImageResourcePool.Release(); - - var exitCode = process.ExitCode; - - process.Dispose(); - - if (exitCode != -1 && File.Exists(outputPath)) - { - return true; - } - - _logger.Error("ffmpeg subtitle conversion failed for {0}", mediaStream.Path); - return false; - } - - /// - /// Extracts an image from a Video and returns a Task whose result indicates whether it was successful or not - /// - /// The input path. - /// The offset. - /// The output path. - /// The cancellation token. - /// Task{System.Boolean}. - /// video - public async Task ExtractImage(string inputPath, TimeSpan offset, string outputPath, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(inputPath)) - { - throw new ArgumentNullException("inputPath"); - } - - if (string.IsNullOrEmpty(outputPath)) - { - throw new ArgumentNullException("outputPath"); - } - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = FFMpegPath, - Arguments = string.Format("-ss {0} -i {1} -threads 0 -v quiet -vframes 1 -filter:v select=\\'eq(pict_type\\,I)\\' -f image2 \"{2}\"", Convert.ToInt32(offset.TotalSeconds), inputPath, outputPath), - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - } - }; - - await VideoImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - process.Start(); - - var ranToCompletion = process.WaitForExit(10000); - - if (!ranToCompletion) - { - try - { - _logger.Info("Killing ffmpeg process"); - - process.Kill(); - process.WaitForExit(1000); - } - catch (Win32Exception ex) - { - _logger.ErrorException("Error killing process", ex); - } - catch (InvalidOperationException ex) - { - _logger.ErrorException("Error killing process", ex); - } - catch (NotSupportedException ex) - { - _logger.ErrorException("Error killing process", ex); - } - } - - VideoImageResourcePool.Release(); - - var exitCode = ranToCompletion ? process.ExitCode : -1; - - process.Dispose(); - - if (exitCode == -1) - { - if (File.Exists(outputPath)) - { - try - { - _logger.Info("Deleting extracted image due to failure: ", outputPath); - File.Delete(outputPath); - } - catch (IOException ex) - { - _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath); - } - } - } - else - { - if (File.Exists(outputPath)) - { - return true; - } - } - - _logger.Error("ffmpeg video image extraction failed for {0}", inputPath); - return false; - } - - /// - /// Gets the input argument. - /// - /// The item. - /// System.String. - public string GetInputArgument(BaseItem item) - { - var video = item as Video; - - if (video != null) - { - if (video.VideoType == VideoType.BluRay) - { - return GetBlurayInputArgument(video.Path); - } - - if (video.VideoType == VideoType.Dvd) - { - return GetDvdInputArgument(video.GetPlayableStreamFiles()); - } - } - - return string.Format("file:\"{0}\"", item.Path); - } - - /// - /// Gets the file input argument. - /// - /// The path. - /// System.String. - private string GetFileInputArgument(string path) - { - return string.Format("file:\"{0}\"", path); - } - - /// - /// Gets the input argument. - /// - /// The item. - /// The mount. - /// System.String. - public string GetInputArgument(Video item, IIsoMount mount) - { - if (item.VideoType == VideoType.Iso && item.IsoType.HasValue) - { - if (item.IsoType.Value == IsoType.BluRay) - { - return GetBlurayInputArgument(mount.MountedPath); - } - if (item.IsoType.Value == IsoType.Dvd) - { - return GetDvdInputArgument(item.GetPlayableStreamFiles(mount.MountedPath)); - } - } - - return GetInputArgument(item); - } - - /// - /// Gets the bluray input argument. - /// - /// The bluray root. - /// System.String. - public string GetBlurayInputArgument(string blurayRoot) - { - return string.Format("bluray:\"{0}\"", blurayRoot); - } - - /// - /// Gets the DVD input argument. - /// - /// The playable stream files. - /// System.String. - public string GetDvdInputArgument(IEnumerable playableStreamFiles) - { - // Get all streams - var streamFilePaths = (playableStreamFiles ?? new string[] { }).ToArray(); - - // If there's more than one we'll need to use the concat command - if (streamFilePaths.Length > 1) - { - var files = string.Join("|", streamFilePaths); - - return string.Format("concat:\"{0}\"", files); - } - - // Determine the input path for video files - return string.Format("file:\"{0}\"", streamFilePaths[0]); - } - - /// - /// Processes the exited. - /// - /// The sender. - /// The instance containing the event data. - void ProcessExited(object sender, EventArgs e) - { - ((Process)sender).Dispose(); - } - - /// - /// Provides a non-blocking method to start a process and wait asynchronously for it to exit - /// - /// The process. - /// Task{System.Boolean}. - private static Task RunAsync(Process process) - { - var tcs = new TaskCompletionSource(); - - process.EnableRaisingEvents = true; - process.Exited += (sender, args) => tcs.SetResult(true); - - process.Start(); - - return tcs.Task; - } - - /// - /// Sets the error mode. - /// - /// The u mode. - /// ErrorModes. - [DllImport("kernel32.dll")] - static extern ErrorModes SetErrorMode(ErrorModes uMode); - - /// - /// Enum ErrorModes - /// - [Flags] - public enum ErrorModes : uint - { - /// - /// The SYSTE m_ DEFAULT - /// - SYSTEM_DEFAULT = 0x0, - /// - /// The SE m_ FAILCRITICALERRORS - /// - SEM_FAILCRITICALERRORS = 0x0001, - /// - /// The SE m_ NOALIGNMENTFAULTEXCEPT - /// - SEM_NOALIGNMENTFAULTEXCEPT = 0x0004, - /// - /// The SE m_ NOGPFAULTERRORBOX - /// - SEM_NOGPFAULTERRORBOX = 0x0002, - /// - /// The SE m_ NOOPENFILEERRORBOX - /// - SEM_NOOPENFILEERRORBOX = 0x8000 - } } } diff --git a/MediaBrowser.Controller/MediaInfo/FFProbeResult.cs b/MediaBrowser.Controller/MediaInfo/FFProbeResult.cs deleted file mode 100644 index 06b4ff87d7..0000000000 --- a/MediaBrowser.Controller/MediaInfo/FFProbeResult.cs +++ /dev/null @@ -1,354 +0,0 @@ -using MediaBrowser.Model.Entities; -using ProtoBuf; -using System.Collections.Generic; - -namespace MediaBrowser.Controller.MediaInfo -{ - /// - /// Provides a class that we can use to deserialize the ffprobe json output - /// Sample output: - /// http://stackoverflow.com/questions/7708373/get-ffmpeg-information-in-friendly-way - /// - [ProtoContract] - public class FFProbeResult - { - /// - /// Gets or sets the streams. - /// - /// The streams. - [ProtoMember(1)] - public FFProbeMediaStreamInfo[] streams { get; set; } - - /// - /// Gets or sets the format. - /// - /// The format. - [ProtoMember(2)] - public FFProbeMediaFormatInfo format { get; set; } - - [ProtoMember(3)] - public List Chapters { get; set; } - } - - /// - /// Represents a stream within the output - /// - [ProtoContract] - public class FFProbeMediaStreamInfo - { - /// - /// Gets or sets the index. - /// - /// The index. - [ProtoMember(1)] - public int index { get; set; } - - /// - /// Gets or sets the profile. - /// - /// The profile. - [ProtoMember(2)] - public string profile { get; set; } - - /// - /// Gets or sets the codec_name. - /// - /// The codec_name. - [ProtoMember(3)] - public string codec_name { get; set; } - - /// - /// Gets or sets the codec_long_name. - /// - /// The codec_long_name. - [ProtoMember(4)] - public string codec_long_name { get; set; } - - /// - /// Gets or sets the codec_type. - /// - /// The codec_type. - [ProtoMember(5)] - public string codec_type { get; set; } - - /// - /// Gets or sets the sample_rate. - /// - /// The sample_rate. - [ProtoMember(6)] - public string sample_rate { get; set; } - - /// - /// Gets or sets the channels. - /// - /// The channels. - [ProtoMember(7)] - public int channels { get; set; } - - /// - /// Gets or sets the avg_frame_rate. - /// - /// The avg_frame_rate. - [ProtoMember(8)] - public string avg_frame_rate { get; set; } - - /// - /// Gets or sets the duration. - /// - /// The duration. - [ProtoMember(9)] - public string duration { get; set; } - - /// - /// Gets or sets the bit_rate. - /// - /// The bit_rate. - [ProtoMember(10)] - public string bit_rate { get; set; } - - /// - /// Gets or sets the width. - /// - /// The width. - [ProtoMember(11)] - public int width { get; set; } - - /// - /// Gets or sets the height. - /// - /// The height. - [ProtoMember(12)] - public int height { get; set; } - - /// - /// Gets or sets the display_aspect_ratio. - /// - /// The display_aspect_ratio. - [ProtoMember(13)] - public string display_aspect_ratio { get; set; } - - /// - /// Gets or sets the tags. - /// - /// The tags. - [ProtoMember(14)] - public Dictionary tags { get; set; } - - /// - /// Gets or sets the bits_per_sample. - /// - /// The bits_per_sample. - [ProtoMember(17)] - public int bits_per_sample { get; set; } - - /// - /// Gets or sets the r_frame_rate. - /// - /// The r_frame_rate. - [ProtoMember(18)] - public string r_frame_rate { get; set; } - - /// - /// Gets or sets the has_b_frames. - /// - /// The has_b_frames. - [ProtoMember(19)] - public int has_b_frames { get; set; } - - /// - /// Gets or sets the sample_aspect_ratio. - /// - /// The sample_aspect_ratio. - [ProtoMember(20)] - public string sample_aspect_ratio { get; set; } - - /// - /// Gets or sets the pix_fmt. - /// - /// The pix_fmt. - [ProtoMember(21)] - public string pix_fmt { get; set; } - - /// - /// Gets or sets the level. - /// - /// The level. - [ProtoMember(22)] - public int level { get; set; } - - /// - /// Gets or sets the time_base. - /// - /// The time_base. - [ProtoMember(23)] - public string time_base { get; set; } - - /// - /// Gets or sets the start_time. - /// - /// The start_time. - [ProtoMember(24)] - public string start_time { get; set; } - - /// - /// Gets or sets the codec_time_base. - /// - /// The codec_time_base. - [ProtoMember(25)] - public string codec_time_base { get; set; } - - /// - /// Gets or sets the codec_tag. - /// - /// The codec_tag. - [ProtoMember(26)] - public string codec_tag { get; set; } - - /// - /// Gets or sets the codec_tag_string. - /// - /// The codec_tag_string. - [ProtoMember(27)] - public string codec_tag_string { get; set; } - - /// - /// Gets or sets the sample_fmt. - /// - /// The sample_fmt. - [ProtoMember(28)] - public string sample_fmt { get; set; } - - /// - /// Gets or sets the dmix_mode. - /// - /// The dmix_mode. - [ProtoMember(29)] - public string dmix_mode { get; set; } - - /// - /// Gets or sets the start_pts. - /// - /// The start_pts. - [ProtoMember(30)] - public string start_pts { get; set; } - - /// - /// Gets or sets the is_avc. - /// - /// The is_avc. - [ProtoMember(31)] - public string is_avc { get; set; } - - /// - /// Gets or sets the nal_length_size. - /// - /// The nal_length_size. - [ProtoMember(32)] - public string nal_length_size { get; set; } - - /// - /// Gets or sets the ltrt_cmixlev. - /// - /// The ltrt_cmixlev. - [ProtoMember(33)] - public string ltrt_cmixlev { get; set; } - - /// - /// Gets or sets the ltrt_surmixlev. - /// - /// The ltrt_surmixlev. - [ProtoMember(34)] - public string ltrt_surmixlev { get; set; } - - /// - /// Gets or sets the loro_cmixlev. - /// - /// The loro_cmixlev. - [ProtoMember(35)] - public string loro_cmixlev { get; set; } - - /// - /// Gets or sets the loro_surmixlev. - /// - /// The loro_surmixlev. - [ProtoMember(36)] - public string loro_surmixlev { get; set; } - - /// - /// Gets or sets the disposition. - /// - /// The disposition. - [ProtoMember(37)] - public Dictionary disposition { get; set; } - } - - /// - /// Class MediaFormat - /// - [ProtoContract] - public class FFProbeMediaFormatInfo - { - /// - /// Gets or sets the filename. - /// - /// The filename. - [ProtoMember(1)] - public string filename { get; set; } - - /// - /// Gets or sets the nb_streams. - /// - /// The nb_streams. - [ProtoMember(2)] - public int nb_streams { get; set; } - - /// - /// Gets or sets the format_name. - /// - /// The format_name. - [ProtoMember(3)] - public string format_name { get; set; } - - /// - /// Gets or sets the format_long_name. - /// - /// The format_long_name. - [ProtoMember(4)] - public string format_long_name { get; set; } - - /// - /// Gets or sets the start_time. - /// - /// The start_time. - [ProtoMember(5)] - public string start_time { get; set; } - - /// - /// Gets or sets the duration. - /// - /// The duration. - [ProtoMember(6)] - public string duration { get; set; } - - /// - /// Gets or sets the size. - /// - /// The size. - [ProtoMember(7)] - public string size { get; set; } - - /// - /// Gets or sets the bit_rate. - /// - /// The bit_rate. - [ProtoMember(8)] - public string bit_rate { get; set; } - - /// - /// Gets or sets the tags. - /// - /// The tags. - [ProtoMember(9)] - public Dictionary tags { get; set; } - } -} diff --git a/MediaBrowser.Controller/MediaInfo/ffmpeg20130405.zip.REMOVED.git-id b/MediaBrowser.Controller/MediaInfo/ffmpeg20130405.zip.REMOVED.git-id deleted file mode 100644 index 363d8552f8..0000000000 --- a/MediaBrowser.Controller/MediaInfo/ffmpeg20130405.zip.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -33054d71c54e6c262d24d16153c05d45718aeb26 \ No newline at end of file diff --git a/MediaBrowser.Controller/MediaInfo/fonts/fonts.conf b/MediaBrowser.Controller/MediaInfo/fonts/fonts.conf deleted file mode 100644 index 648bdb7b28..0000000000 --- a/MediaBrowser.Controller/MediaInfo/fonts/fonts.conf +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - Arial - Arial Unicode MS - - \ No newline at end of file diff --git a/MediaBrowser.Controller/MediaInfo/readme.txt b/MediaBrowser.Controller/MediaInfo/readme.txt deleted file mode 100644 index b32dd9aec0..0000000000 --- a/MediaBrowser.Controller/MediaInfo/readme.txt +++ /dev/null @@ -1,5 +0,0 @@ -This is the 32-bit static build of ffmpeg, located at: - -http://ffmpeg.zeranoe.com/builds/ - -The zip file contains both ffmpeg and ffprobe, and is suffixed with the date of the build. \ No newline at end of file diff --git a/MediaBrowser.Controller/Providers/IProviderManager.cs b/MediaBrowser.Controller/Providers/IProviderManager.cs index 902ed21bcd..cb7237a9df 100644 --- a/MediaBrowser.Controller/Providers/IProviderManager.cs +++ b/MediaBrowser.Controller/Providers/IProviderManager.cs @@ -1,13 +1,12 @@ -using System.Collections.Generic; -using MediaBrowser.Controller.Entities; -using System; +using MediaBrowser.Controller.Entities; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; namespace MediaBrowser.Controller.Providers { - public interface IProviderManager : IDisposable + public interface IProviderManager { /// /// Downloads the and save image. diff --git a/MediaBrowser.Controller/Providers/MediaInfo/BaseFFMpegProvider.cs b/MediaBrowser.Controller/Providers/MediaInfo/BaseFFMpegProvider.cs index 6edd28b245..9fa6363a83 100644 --- a/MediaBrowser.Controller/Providers/MediaInfo/BaseFFMpegProvider.cs +++ b/MediaBrowser.Controller/Providers/MediaInfo/BaseFFMpegProvider.cs @@ -1,4 +1,5 @@ using MediaBrowser.Common.IO; +using MediaBrowser.Common.MediaInfo; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Entities; @@ -15,8 +16,11 @@ namespace MediaBrowser.Controller.Providers.MediaInfo public abstract class BaseFFMpegProvider : BaseMetadataProvider where T : BaseItem { - protected BaseFFMpegProvider(ILogManager logManager, IServerConfigurationManager configurationManager) : base(logManager, configurationManager) + protected readonly IMediaEncoder MediaEncoder; + + protected BaseFFMpegProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder) : base(logManager, configurationManager) { + MediaEncoder = mediaEncoder; } /// @@ -53,7 +57,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo { get { - return Kernel.Instance.FFMpegManager.FFMpegVersion; + return MediaEncoder.Version; } } diff --git a/MediaBrowser.Controller/Providers/MediaInfo/BaseFFProbeProvider.cs b/MediaBrowser.Controller/Providers/MediaInfo/BaseFFProbeProvider.cs index 7c977d02f7..eac10d5221 100644 --- a/MediaBrowser.Controller/Providers/MediaInfo/BaseFFProbeProvider.cs +++ b/MediaBrowser.Controller/Providers/MediaInfo/BaseFFProbeProvider.cs @@ -1,12 +1,13 @@ -using System.Globalization; -using MediaBrowser.Common.IO; +using MediaBrowser.Common.IO; +using MediaBrowser.Common.MediaInfo; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.MediaInfo; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -17,13 +18,17 @@ namespace MediaBrowser.Controller.Providers.MediaInfo /// Provides a base class for extracting media information through ffprobe /// /// - public abstract class BaseFFProbeProvider : BaseFFMpegProvider, IDisposable + public abstract class BaseFFProbeProvider : BaseFFMpegProvider where T : BaseItem { - protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager) : base(logManager, configurationManager) + protected BaseFFProbeProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder, IProtobufSerializer protobufSerializer) + : base(logManager, configurationManager, mediaEncoder) { + ProtobufSerializer = protobufSerializer; } + protected readonly IProtobufSerializer ProtobufSerializer; + /// /// Gets or sets the FF probe cache. /// @@ -81,11 +86,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo { OnPreFetch(myItem, isoMount); - var inputPath = isoMount == null ? - Kernel.Instance.FFMpegManager.GetInputArgument(myItem) : - Kernel.Instance.FFMpegManager.GetInputArgument((Video)item, isoMount); - - var result = await Kernel.Instance.FFMpegManager.RunFFProbe(item, inputPath, item.DateModified, FFProbeCache, cancellationToken).ConfigureAwait(false); + var result = await GetMediaInfo(item, isoMount, item.DateModified, FFProbeCache, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); @@ -110,6 +111,61 @@ namespace MediaBrowser.Controller.Providers.MediaInfo return true; } + /// + /// Gets the media info. + /// + /// The item. + /// The iso mount. + /// The last date modified. + /// The cache. + /// The cancellation token. + /// Task{MediaInfoResult}. + /// inputPath + /// or + /// cache + private async Task GetMediaInfo(BaseItem item, IIsoMount isoMount, DateTime lastDateModified, FileSystemRepository cache, CancellationToken cancellationToken) + { + if (cache == null) + { + throw new ArgumentNullException("cache"); + } + + // Put the ffmpeg version into the cache name so that it's unique per-version + // We don't want to try and deserialize data based on an old version, which could potentially fail + var resourceName = item.Id + "_" + lastDateModified.Ticks + "_" + MediaEncoder.Version; + + // Forumulate the cache file path + var cacheFilePath = cache.GetResourcePath(resourceName, ".pb"); + + cancellationToken.ThrowIfCancellationRequested(); + + // Avoid File.Exists by just trying to deserialize + try + { + return ProtobufSerializer.DeserializeFromFile(cacheFilePath); + } + catch (FileNotFoundException) + { + // Cache file doesn't exist + } + + var type = InputType.AudioFile; + var inputPath = isoMount == null ? new[] { item.Path } : new[] { isoMount.MountedPath }; + + var video = item as Video; + + if (video != null) + { + inputPath = MediaEncoderHelpers.GetInputArgument(video, isoMount, out type); + } + + var info = await MediaEncoder.GetMediaInfo(inputPath, type, cancellationToken).ConfigureAwait(false); + + ProtobufSerializer.SerializeToFile(info, cacheFilePath); + + return info; + } + /// /// Gets a value indicating whether [refresh on version change]. /// @@ -147,7 +203,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo /// Normalizes the FF probe result. /// /// The result. - private void NormalizeFFProbeResult(FFProbeResult result) + private void NormalizeFFProbeResult(MediaInfoResult result) { if (result.format != null && result.format.tags != null) { @@ -180,7 +236,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo /// The result. /// The iso mount. /// Task. - protected abstract void Fetch(T item, CancellationToken cancellationToken, FFProbeResult result, IIsoMount isoMount); + protected abstract void Fetch(T item, CancellationToken cancellationToken, MediaInfoResult result, IIsoMount isoMount); /// /// Converts ffprobe stream info to our MediaStream class @@ -188,7 +244,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo /// The stream info. /// The format info. /// MediaStream. - protected MediaStream GetMediaStream(FFProbeMediaStreamInfo streamInfo, FFProbeMediaFormatInfo formatInfo) + protected MediaStream GetMediaStream(MediaStreamInfo streamInfo, MediaFormatInfo formatInfo) { var stream = new MediaStream { @@ -360,22 +416,5 @@ namespace MediaBrowser.Controller.Providers.MediaInfo { return new Dictionary(dict, StringComparer.OrdinalIgnoreCase); } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - FFProbeCache.Dispose(); - } - } - - public void Dispose() - { - Dispose(true); - } } } diff --git a/MediaBrowser.Controller/Providers/MediaInfo/FFMpegAudioImageProvider.cs b/MediaBrowser.Controller/Providers/MediaInfo/FFMpegAudioImageProvider.cs index 68e552d3c4..421b0522da 100644 --- a/MediaBrowser.Controller/Providers/MediaInfo/FFMpegAudioImageProvider.cs +++ b/MediaBrowser.Controller/Providers/MediaInfo/FFMpegAudioImageProvider.cs @@ -1,10 +1,11 @@ -using System.Collections.Concurrent; +using MediaBrowser.Common.MediaInfo; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; using System; +using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -16,8 +17,8 @@ namespace MediaBrowser.Controller.Providers.MediaInfo /// public class FFMpegAudioImageProvider : BaseFFMpegProvider public class FFProbeAudioInfoProvider : BaseFFProbeProvider public class FFProbeVideoInfoProvider : BaseFFProbeProvider private readonly IIsoManager _isoManager; - /// - /// The _protobuf serializer - /// - private readonly IProtobufSerializer _protobufSerializer; - /// /// Returns true or false indicating if the provider should refresh when the contents of it's directory changes /// @@ -187,7 +181,7 @@ namespace MediaBrowser.Controller.Providers.MediaInfo /// The data. /// The iso mount. /// Task. - protected override void Fetch(Video video, CancellationToken cancellationToken, FFProbeResult data, IIsoMount isoMount) + protected override void Fetch(Video video, CancellationToken cancellationToken, MediaInfoResult data, IIsoMount isoMount) { if (data.format != null) { @@ -335,13 +329,13 @@ namespace MediaBrowser.Controller.Providers.MediaInfo try { - result = _protobufSerializer.DeserializeFromFile(cacheFile); + result = ProtobufSerializer.DeserializeFromFile(cacheFile); } catch (FileNotFoundException) { result = GetBDInfo(inputPath); - _protobufSerializer.SerializeToFile(result, cacheFile); + ProtobufSerializer.SerializeToFile(result, cacheFile); } cancellationToken.ThrowIfCancellationRequested(); @@ -422,19 +416,5 @@ namespace MediaBrowser.Controller.Providers.MediaInfo { return _blurayExaminer.GetDiscInfo(path); } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected override void Dispose(bool dispose) - { - if (dispose) - { - BdInfoCache.Dispose(); - } - - base.Dispose(dispose); - } } } diff --git a/MediaBrowser.Controller/Providers/MediaInfo/MediaEncoderHelpers.cs b/MediaBrowser.Controller/Providers/MediaInfo/MediaEncoderHelpers.cs new file mode 100644 index 0000000000..14372553b4 --- /dev/null +++ b/MediaBrowser.Controller/Providers/MediaInfo/MediaEncoderHelpers.cs @@ -0,0 +1,96 @@ +using MediaBrowser.Common.IO; +using MediaBrowser.Common.MediaInfo; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Entities; + +namespace MediaBrowser.Controller.Providers.MediaInfo +{ + /// + /// Class MediaEncoderHelpers + /// + public static class MediaEncoderHelpers + { + /// + /// Gets the input argument. + /// + /// The video. + /// The iso mount. + /// The type. + /// System.String[][]. + public static string[] GetInputArgument(Video video, IIsoMount isoMount, out InputType type) + { + var inputPath = isoMount == null ? new[] { video.Path } : new[] { isoMount.MountedPath }; + + type = InputType.VideoFile; + + switch (video.VideoType) + { + case VideoType.BluRay: + type = InputType.Bluray; + break; + case VideoType.Dvd: + type = InputType.Dvd; + inputPath = video.GetPlayableStreamFiles(inputPath[0]).ToArray(); + break; + case VideoType.Iso: + if (video.IsoType.HasValue) + { + switch (video.IsoType.Value) + { + case IsoType.BluRay: + type = InputType.Bluray; + break; + case IsoType.Dvd: + type = InputType.Dvd; + inputPath = video.GetPlayableStreamFiles(inputPath[0]).ToArray(); + break; + } + } + break; + } + + return inputPath; + } + + /// + /// Gets the type of the input. + /// + /// The item. + /// InputType. + public static InputType GetInputType(BaseItem item) + { + var type = InputType.AudioFile; + + var video = item as Video; + + if (video != null) + { + switch (video.VideoType) + { + case VideoType.BluRay: + type = InputType.Bluray; + break; + case VideoType.Dvd: + type = InputType.Dvd; + break; + case VideoType.Iso: + if (video.IsoType.HasValue) + { + switch (video.IsoType.Value) + { + case IsoType.BluRay: + type = InputType.Bluray; + break; + case IsoType.Dvd: + type = InputType.Dvd; + break; + } + } + break; + } + } + + return type; + } + } +} -- cgit v1.2.3