jellyfin/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs

236 lines
7.5 KiB
C#
Raw Normal View History

2014-03-28 04:24:11 +00:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
2014-03-28 03:32:43 +00:00
using MediaBrowser.Controller.MediaEncoding;
2014-03-27 23:01:42 +00:00
using MediaBrowser.Model.Logging;
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
2014-03-28 04:24:11 +00:00
using System.Linq;
using System.Text;
2014-03-27 23:01:42 +00:00
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.MediaEncoding.Encoder
{
public class ImageEncoder
{
private readonly string _ffmpegPath;
private readonly ILogger _logger;
2014-03-28 03:32:43 +00:00
private readonly IFileSystem _fileSystem;
2014-03-28 04:24:11 +00:00
private readonly IApplicationPaths _appPaths;
2014-03-28 03:32:43 +00:00
2014-03-27 23:01:42 +00:00
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
2014-03-28 03:32:43 +00:00
private static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(10, 10);
2014-03-27 23:01:42 +00:00
2014-03-28 04:24:11 +00:00
public ImageEncoder(string ffmpegPath, ILogger logger, IFileSystem fileSystem, IApplicationPaths appPaths)
2014-03-27 23:01:42 +00:00
{
_ffmpegPath = ffmpegPath;
_logger = logger;
2014-03-28 03:32:43 +00:00
_fileSystem = fileSystem;
2014-03-28 04:24:11 +00:00
_appPaths = appPaths;
2014-03-27 23:01:42 +00:00
}
public async Task<Stream> EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken)
{
ValidateInput(options);
2014-03-28 03:32:43 +00:00
await ResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
return await EncodeImageInternal(options, cancellationToken).ConfigureAwait(false);
}
finally
{
ResourcePool.Release();
}
}
private async Task<Stream> EncodeImageInternal(ImageEncodingOptions options, CancellationToken cancellationToken)
{
ValidateInput(options);
2014-03-28 04:24:11 +00:00
var inputPath = options.InputPath;
var filename = Path.GetFileName(inputPath);
if (HasDiacritics(filename))
{
inputPath = GetTempFile(inputPath);
filename = Path.GetFileName(inputPath);
}
2014-03-27 23:01:42 +00:00
var process = new Process
{
StartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
FileName = _ffmpegPath,
2014-03-28 04:24:11 +00:00
Arguments = GetArguments(options, filename),
2014-03-27 23:01:42 +00:00
WindowStyle = ProcessWindowStyle.Hidden,
ErrorDialog = false,
RedirectStandardOutput = true,
2014-03-28 03:32:43 +00:00
RedirectStandardError = true,
2014-03-28 04:24:11 +00:00
WorkingDirectory = Path.GetDirectoryName(inputPath)
2014-03-27 23:01:42 +00:00
}
};
2014-03-28 03:32:43 +00:00
_logger.Debug("ffmpeg " + process.StartInfo.Arguments);
2014-03-27 23:01:42 +00:00
process.Start();
var memoryStream = new MemoryStream();
#pragma warning disable 4014
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
#pragma warning restore 4014
// MUST read both stdout and stderr asynchronously or a deadlock may occurr
process.BeginErrorReadLine();
var ranToCompletion = process.WaitForExit(5000);
if (!ranToCompletion)
{
try
{
_logger.Info("Killing ffmpeg process");
process.Kill();
process.WaitForExit(1000);
}
catch (Exception ex)
{
_logger.ErrorException("Error killing process", ex);
}
}
var exitCode = ranToCompletion ? process.ExitCode : -1;
process.Dispose();
if (exitCode == -1 || memoryStream.Length == 0)
{
memoryStream.Dispose();
var msg = string.Format("ffmpeg image encoding failed for {0}", options.InputPath);
_logger.Error(msg);
throw new ApplicationException(msg);
}
memoryStream.Position = 0;
return memoryStream;
}
2014-03-28 04:24:11 +00:00
private string GetTempFile(string path)
{
var extension = Path.GetExtension(path) ?? string.Empty;
var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N") + extension);
File.Copy(path, tempPath);
return tempPath;
}
2014-03-28 03:32:43 +00:00
2014-03-28 04:24:11 +00:00
private string GetArguments(ImageEncodingOptions options, string inputFilename)
2014-03-27 23:01:42 +00:00
{
var vfScale = GetFilterGraph(options);
2014-03-28 03:32:43 +00:00
var outputFormat = GetOutputFormat(options.Format);
var quality = (options.Quality ?? 100) * .3;
quality = 31 - quality;
var qualityValue = Convert.ToInt32(Math.Max(quality, 1));
2014-03-27 23:01:42 +00:00
2014-03-28 03:32:43 +00:00
return string.Format("-f image2 -i file:\"{3}\" -q:v {0} {1} -f image2pipe -vcodec {2} -",
qualityValue.ToString(_usCulture),
2014-03-27 23:01:42 +00:00
vfScale,
2014-03-28 03:32:43 +00:00
outputFormat,
2014-03-28 04:24:11 +00:00
inputFilename);
2014-03-27 23:01:42 +00:00
}
private string GetFilterGraph(ImageEncodingOptions options)
{
if (!options.Width.HasValue &&
!options.Height.HasValue &&
!options.MaxHeight.HasValue &&
!options.MaxWidth.HasValue)
{
return string.Empty;
}
var widthScale = "-1";
var heightScale = "-1";
if (options.MaxWidth.HasValue)
{
2014-03-28 03:32:43 +00:00
widthScale = "min(iw\\," + options.MaxWidth.Value.ToString(_usCulture) + ")";
2014-03-27 23:01:42 +00:00
}
else if (options.Width.HasValue)
{
widthScale = options.Width.Value.ToString(_usCulture);
}
if (options.MaxHeight.HasValue)
{
2014-03-28 03:32:43 +00:00
heightScale = "min(ih\\," + options.MaxHeight.Value.ToString(_usCulture) + ")";
2014-03-27 23:01:42 +00:00
}
else if (options.Height.HasValue)
{
heightScale = options.Height.Value.ToString(_usCulture);
}
var scaleMethod = "lanczos";
2014-03-28 04:24:11 +00:00
return string.Format("-vf scale=\"{0}:{1}\"",
2014-03-28 03:32:43 +00:00
widthScale,
2014-03-28 04:24:11 +00:00
heightScale);
2014-03-27 23:01:42 +00:00
}
2014-03-28 03:32:43 +00:00
private string GetOutputFormat(string format)
2014-03-27 23:01:42 +00:00
{
2014-03-28 03:32:43 +00:00
if (string.Equals(format, "jpeg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(format, "jpg", StringComparison.OrdinalIgnoreCase))
{
return "mjpeg";
}
return format;
2014-03-27 23:01:42 +00:00
}
private void ValidateInput(ImageEncodingOptions options)
{
}
2014-03-28 04:24:11 +00:00
/// <summary>
/// Determines whether the specified text has diacritics.
/// </summary>
/// <param name="text">The text.</param>
/// <returns><c>true</c> if the specified text has diacritics; otherwise, <c>false</c>.</returns>
private bool HasDiacritics(string text)
{
return !String.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal);
}
/// <summary>
/// Removes the diacritics.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>System.String.</returns>
private string RemoveDiacritics(string text)
{
return String.Concat(
text.Normalize(NormalizationForm.FormD)
.Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
UnicodeCategory.NonSpacingMark)
).Normalize(NormalizationForm.FormC);
}
2014-03-27 23:01:42 +00:00
}
}