diff --git a/MediaBrowser.Server.Implementations/Drawing/ImageHeader.cs b/Emby.Drawing/Common/ImageHeader.cs
similarity index 99%
rename from MediaBrowser.Server.Implementations/Drawing/ImageHeader.cs
rename to Emby.Drawing/Common/ImageHeader.cs
index 7117482c8a..b66bd71ea5 100644
--- a/MediaBrowser.Server.Implementations/Drawing/ImageHeader.cs
+++ b/Emby.Drawing/Common/ImageHeader.cs
@@ -6,7 +6,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
-namespace MediaBrowser.Server.Implementations.Drawing
+namespace Emby.Drawing.Common
{
///
/// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349
diff --git a/Emby.Drawing/Emby.Drawing.csproj b/Emby.Drawing/Emby.Drawing.csproj
new file mode 100644
index 0000000000..dbb976f036
--- /dev/null
+++ b/Emby.Drawing/Emby.Drawing.csproj
@@ -0,0 +1,98 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {08FFF49B-F175-4807-A2B5-73B0EBD9F716}
+ Library
+ Properties
+ Emby.Drawing
+ Emby.Drawing
+ v4.5
+ 512
+ ..\
+ true
+
+
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+
+
+
+ False
+ ..\packages\ImageMagickSharp.1.0.0.14\lib\net45\ImageMagickSharp.dll
+
+
+
+
+
+
+
+
+
+
+
+
+ Properties\SharedVersion.cs
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {9142eefa-7570-41e1-bfcc-468bb571af2f}
+ MediaBrowser.Common
+
+
+ {17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2}
+ MediaBrowser.Controller
+
+
+ {7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b}
+ MediaBrowser.Model
+
+
+
+
+
\ No newline at end of file
diff --git a/Emby.Drawing/GDI/DynamicImageHelpers.cs b/Emby.Drawing/GDI/DynamicImageHelpers.cs
new file mode 100644
index 0000000000..c49007c5fd
--- /dev/null
+++ b/Emby.Drawing/GDI/DynamicImageHelpers.cs
@@ -0,0 +1,138 @@
+using Emby.Drawing.ImageMagick;
+using MediaBrowser.Common.IO;
+using System.Collections.Generic;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Linq;
+
+namespace Emby.Drawing.GDI
+{
+ public static class DynamicImageHelpers
+ {
+ public static void CreateThumbCollage(List files,
+ IFileSystem fileSystem,
+ string file,
+ int width,
+ int height)
+ {
+ const int numStrips = 4;
+ files = StripCollageBuilder.ProjectPaths(files, numStrips).ToList();
+
+ const int rows = 1;
+ int cols = numStrips;
+
+ int cellWidth = 2 * (width / 3);
+ int cellHeight = height;
+ var index = 0;
+
+ using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
+ {
+ using (var graphics = Graphics.FromImage(img))
+ {
+ graphics.CompositingQuality = CompositingQuality.HighQuality;
+ graphics.SmoothingMode = SmoothingMode.HighQuality;
+ graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ graphics.CompositingMode = CompositingMode.SourceCopy;
+
+ for (var row = 0; row < rows; row++)
+ {
+ for (var col = 0; col < cols; col++)
+ {
+ var x = col * (cellWidth / 2);
+ var y = row * cellHeight;
+
+ if (files.Count > index)
+ {
+ using (var fileStream = fileSystem.GetFileStream(files[index], FileMode.Open, FileAccess.Read, FileShare.Read, true))
+ {
+ using (var memoryStream = new MemoryStream())
+ {
+ fileStream.CopyTo(memoryStream);
+
+ memoryStream.Position = 0;
+
+ using (var imgtemp = Image.FromStream(memoryStream, true, false))
+ {
+ graphics.DrawImage(imgtemp, x, y, cellWidth, cellHeight);
+ }
+ }
+ }
+ }
+
+ index++;
+ }
+ }
+ img.Save(file);
+ }
+ }
+ }
+
+ public static void CreateSquareCollage(List files,
+ IFileSystem fileSystem,
+ string file,
+ int width,
+ int height)
+ {
+ files = StripCollageBuilder.ProjectPaths(files, 4).ToList();
+
+ const int rows = 2;
+ const int cols = 2;
+
+ int singleSize = width / 2;
+ var index = 0;
+
+ using (var img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
+ {
+ using (var graphics = Graphics.FromImage(img))
+ {
+ graphics.CompositingQuality = CompositingQuality.HighQuality;
+ graphics.SmoothingMode = SmoothingMode.HighQuality;
+ graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ graphics.CompositingMode = CompositingMode.SourceCopy;
+
+ for (var row = 0; row < rows; row++)
+ {
+ for (var col = 0; col < cols; col++)
+ {
+ var x = col * singleSize;
+ var y = row * singleSize;
+
+ using (var fileStream = fileSystem.GetFileStream(files[index], FileMode.Open, FileAccess.Read, FileShare.Read, true))
+ {
+ using (var memoryStream = new MemoryStream())
+ {
+ fileStream.CopyTo(memoryStream);
+
+ memoryStream.Position = 0;
+
+ using (var imgtemp = Image.FromStream(memoryStream, true, false))
+ {
+ graphics.DrawImage(imgtemp, x, y, singleSize, singleSize);
+ }
+ }
+ }
+
+ index++;
+ }
+ }
+ img.Save(file);
+ }
+ }
+ }
+
+ private static Stream GetStream(Image image)
+ {
+ var ms = new MemoryStream();
+
+ image.Save(ms, ImageFormat.Png);
+
+ ms.Position = 0;
+
+ return ms;
+ }
+ }
+}
diff --git a/Emby.Drawing/GDI/GDIImageEncoder.cs b/Emby.Drawing/GDI/GDIImageEncoder.cs
new file mode 100644
index 0000000000..d968b8b5fe
--- /dev/null
+++ b/Emby.Drawing/GDI/GDIImageEncoder.cs
@@ -0,0 +1,254 @@
+using MediaBrowser.Common.IO;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Logging;
+using System;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Linq;
+using ImageFormat = MediaBrowser.Model.Drawing.ImageFormat;
+
+namespace Emby.Drawing.GDI
+{
+ public class GDIImageEncoder : IImageEncoder
+ {
+ private readonly IFileSystem _fileSystem;
+ private readonly ILogger _logger;
+
+ public GDIImageEncoder(IFileSystem fileSystem, ILogger logger)
+ {
+ _fileSystem = fileSystem;
+ _logger = logger;
+ }
+
+ public string[] SupportedInputFormats
+ {
+ get
+ {
+ return new[]
+ {
+ "png",
+ "jpeg",
+ "jpg",
+ "gif",
+ "bmp"
+ };
+ }
+ }
+
+ public ImageFormat[] SupportedOutputFormats
+ {
+ get
+ {
+ return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
+ }
+ }
+
+ public ImageSize GetImageSize(string path)
+ {
+ using (var image = Image.FromFile(path))
+ {
+ return new ImageSize
+ {
+ Width = image.Width,
+ Height = image.Height
+ };
+ }
+ }
+
+ public void CropWhiteSpace(string inputPath, string outputPath)
+ {
+ using (var image = (Bitmap)Image.FromFile(inputPath))
+ {
+ using (var croppedImage = image.CropWhitespace())
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
+
+ using (var outputStream = _fileSystem.GetFileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
+ {
+ croppedImage.Save(System.Drawing.Imaging.ImageFormat.Png, outputStream, 100);
+ }
+ }
+ }
+ }
+
+ public void EncodeImage(string inputPath, string cacheFilePath, int width, int height, int quality, ImageProcessingOptions options)
+ {
+ var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed > 0;
+
+ using (var originalImage = Image.FromFile(inputPath))
+ {
+ var newWidth = Convert.ToInt32(width);
+ var newHeight = Convert.ToInt32(height);
+
+ var selectedOutputFormat = options.OutputFormat;
+
+ // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
+ // Also, Webp only supports Format32bppArgb and Format32bppRgb
+ var pixelFormat = selectedOutputFormat == ImageFormat.Webp
+ ? PixelFormat.Format32bppArgb
+ : PixelFormat.Format32bppPArgb;
+
+ using (var thumbnail = new Bitmap(newWidth, newHeight, pixelFormat))
+ {
+ // Mono throw an exeception if assign 0 to SetResolution
+ if (originalImage.HorizontalResolution > 0 && originalImage.VerticalResolution > 0)
+ {
+ // Preserve the original resolution
+ thumbnail.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
+ }
+
+ using (var thumbnailGraph = Graphics.FromImage(thumbnail))
+ {
+ thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
+ thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
+ thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ thumbnailGraph.CompositingMode = !hasPostProcessing ?
+ CompositingMode.SourceCopy :
+ CompositingMode.SourceOver;
+
+ SetBackgroundColor(thumbnailGraph, options);
+
+ thumbnailGraph.DrawImage(originalImage, 0, 0, newWidth, newHeight);
+
+ DrawIndicator(thumbnailGraph, newWidth, newHeight, options);
+
+ var outputFormat = GetOutputFormat(originalImage, selectedOutputFormat);
+
+ Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
+
+ // Save to the cache location
+ using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, false))
+ {
+ // Save to the memory stream
+ thumbnail.Save(outputFormat, cacheFileStream, quality);
+ }
+ }
+ }
+
+ }
+ }
+
+ ///
+ /// Sets the color of the background.
+ ///
+ /// The graphics.
+ /// The options.
+ private void SetBackgroundColor(Graphics graphics, ImageProcessingOptions options)
+ {
+ var color = options.BackgroundColor;
+
+ if (!string.IsNullOrEmpty(color))
+ {
+ Color drawingColor;
+
+ try
+ {
+ drawingColor = ColorTranslator.FromHtml(color);
+ }
+ catch
+ {
+ drawingColor = ColorTranslator.FromHtml("#" + color);
+ }
+
+ graphics.Clear(drawingColor);
+ }
+ }
+
+ ///
+ /// Draws the indicator.
+ ///
+ /// The graphics.
+ /// Width of the image.
+ /// Height of the image.
+ /// The options.
+ private void DrawIndicator(Graphics graphics, int imageWidth, int imageHeight, ImageProcessingOptions options)
+ {
+ if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
+ {
+ return;
+ }
+
+ try
+ {
+ if (options.AddPlayedIndicator)
+ {
+ var currentImageSize = new Size(imageWidth, imageHeight);
+
+ new PlayedIndicatorDrawer().DrawPlayedIndicator(graphics, currentImageSize);
+ }
+ else if (options.UnplayedCount.HasValue)
+ {
+ var currentImageSize = new Size(imageWidth, imageHeight);
+
+ new UnplayedCountIndicator().DrawUnplayedCountIndicator(graphics, currentImageSize, options.UnplayedCount.Value);
+ }
+
+ if (options.PercentPlayed > 0)
+ {
+ var currentImageSize = new Size(imageWidth, imageHeight);
+
+ new PercentPlayedDrawer().Process(graphics, currentImageSize, options.PercentPlayed);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error drawing indicator overlay", ex);
+ }
+ }
+
+ ///
+ /// Gets the output format.
+ ///
+ /// The image.
+ /// The output format.
+ /// ImageFormat.
+ private System.Drawing.Imaging.ImageFormat GetOutputFormat(Image image, ImageFormat outputFormat)
+ {
+ switch (outputFormat)
+ {
+ case ImageFormat.Bmp:
+ return System.Drawing.Imaging.ImageFormat.Bmp;
+ case ImageFormat.Gif:
+ return System.Drawing.Imaging.ImageFormat.Gif;
+ case ImageFormat.Jpg:
+ return System.Drawing.Imaging.ImageFormat.Jpeg;
+ case ImageFormat.Png:
+ return System.Drawing.Imaging.ImageFormat.Png;
+ default:
+ return image.RawFormat;
+ }
+ }
+
+ public void CreateImageCollage(ImageCollageOptions options)
+ {
+ double ratio = options.Width;
+ ratio /= options.Height;
+
+ if (ratio >= 1.4)
+ {
+ DynamicImageHelpers.CreateThumbCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
+ }
+ else if (ratio >= .9)
+ {
+ DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Height);
+ }
+ else
+ {
+ DynamicImageHelpers.CreateSquareCollage(options.InputPaths.ToList(), _fileSystem, options.OutputPath, options.Width, options.Width);
+ }
+ }
+
+ public void Dispose()
+ {
+ }
+
+ public string Name
+ {
+ get { return "GDI"; }
+ }
+ }
+}
diff --git a/Emby.Drawing/GDI/ImageExtensions.cs b/Emby.Drawing/GDI/ImageExtensions.cs
new file mode 100644
index 0000000000..6af5a8688f
--- /dev/null
+++ b/Emby.Drawing/GDI/ImageExtensions.cs
@@ -0,0 +1,217 @@
+using System;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+
+namespace Emby.Drawing.GDI
+{
+ public static class ImageExtensions
+ {
+ ///
+ /// Saves the image.
+ ///
+ /// The output format.
+ /// The image.
+ /// To stream.
+ /// The quality.
+ public static void Save(this Image image, ImageFormat outputFormat, Stream toStream, int quality)
+ {
+ // Use special save methods for jpeg and png that will result in a much higher quality image
+ // All other formats use the generic Image.Save
+ if (ImageFormat.Jpeg.Equals(outputFormat))
+ {
+ SaveAsJpeg(image, toStream, quality);
+ }
+ else if (ImageFormat.Png.Equals(outputFormat))
+ {
+ image.Save(toStream, ImageFormat.Png);
+ }
+ else
+ {
+ image.Save(toStream, outputFormat);
+ }
+ }
+
+ ///
+ /// Saves the JPEG.
+ ///
+ /// The image.
+ /// The target.
+ /// The quality.
+ public static void SaveAsJpeg(this Image image, Stream target, int quality)
+ {
+ using (var encoderParameters = new EncoderParameters(1))
+ {
+ encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
+ image.Save(target, GetImageCodecInfo("image/jpeg"), encoderParameters);
+ }
+ }
+
+ private static readonly ImageCodecInfo[] Encoders = ImageCodecInfo.GetImageEncoders();
+
+ ///
+ /// Gets the image codec info.
+ ///
+ /// Type of the MIME.
+ /// ImageCodecInfo.
+ private static ImageCodecInfo GetImageCodecInfo(string mimeType)
+ {
+ foreach (var encoder in Encoders)
+ {
+ if (string.Equals(encoder.MimeType, mimeType, StringComparison.OrdinalIgnoreCase))
+ {
+ return encoder;
+ }
+ }
+
+ return Encoders.Length == 0 ? null : Encoders[0];
+ }
+
+ ///
+ /// Crops an image by removing whitespace and transparency from the edges
+ ///
+ /// The BMP.
+ /// Bitmap.
+ ///
+ public static Bitmap CropWhitespace(this Bitmap bmp)
+ {
+ var width = bmp.Width;
+ var height = bmp.Height;
+
+ var topmost = 0;
+ for (int row = 0; row < height; ++row)
+ {
+ if (IsAllWhiteRow(bmp, row, width))
+ topmost = row;
+ else break;
+ }
+
+ int bottommost = 0;
+ for (int row = height - 1; row >= 0; --row)
+ {
+ if (IsAllWhiteRow(bmp, row, width))
+ bottommost = row;
+ else break;
+ }
+
+ int leftmost = 0, rightmost = 0;
+ for (int col = 0; col < width; ++col)
+ {
+ if (IsAllWhiteColumn(bmp, col, height))
+ leftmost = col;
+ else
+ break;
+ }
+
+ for (int col = width - 1; col >= 0; --col)
+ {
+ if (IsAllWhiteColumn(bmp, col, height))
+ rightmost = col;
+ else
+ break;
+ }
+
+ if (rightmost == 0) rightmost = width; // As reached left
+ if (bottommost == 0) bottommost = height; // As reached top.
+
+ var croppedWidth = rightmost - leftmost;
+ var croppedHeight = bottommost - topmost;
+
+ if (croppedWidth == 0) // No border on left or right
+ {
+ leftmost = 0;
+ croppedWidth = width;
+ }
+
+ if (croppedHeight == 0) // No border on top or bottom
+ {
+ topmost = 0;
+ croppedHeight = height;
+ }
+
+ // Graphics.FromImage will throw an exception if the PixelFormat is Indexed, so we need to handle that here
+ var thumbnail = new Bitmap(croppedWidth, croppedHeight, PixelFormat.Format32bppPArgb);
+
+ // Preserve the original resolution
+ TrySetResolution(thumbnail, bmp.HorizontalResolution, bmp.VerticalResolution);
+
+ using (var thumbnailGraph = Graphics.FromImage(thumbnail))
+ {
+ thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
+ thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
+ thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ thumbnailGraph.CompositingMode = CompositingMode.SourceCopy;
+
+ thumbnailGraph.DrawImage(bmp,
+ new RectangleF(0, 0, croppedWidth, croppedHeight),
+ new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),
+ GraphicsUnit.Pixel);
+ }
+ return thumbnail;
+ }
+
+ ///
+ /// Tries the set resolution.
+ ///
+ /// The BMP.
+ /// The x.
+ /// The y.
+ private static void TrySetResolution(Bitmap bmp, float x, float y)
+ {
+ if (x > 0 && y > 0)
+ {
+ bmp.SetResolution(x, y);
+ }
+ }
+
+ ///
+ /// Determines whether or not a row of pixels is all whitespace
+ ///
+ /// The BMP.
+ /// The row.
+ /// The width.
+ /// true if [is all white row] [the specified BMP]; otherwise, false.
+ private static bool IsAllWhiteRow(Bitmap bmp, int row, int width)
+ {
+ for (var i = 0; i < width; ++i)
+ {
+ if (!IsWhiteSpace(bmp.GetPixel(i, row)))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ ///
+ /// Determines whether or not a column of pixels is all whitespace
+ ///
+ /// The BMP.
+ /// The col.
+ /// The height.
+ /// true if [is all white column] [the specified BMP]; otherwise, false.
+ private static bool IsAllWhiteColumn(Bitmap bmp, int col, int height)
+ {
+ for (var i = 0; i < height; ++i)
+ {
+ if (!IsWhiteSpace(bmp.GetPixel(col, i)))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ ///
+ /// Determines if a color is whitespace
+ ///
+ /// The color.
+ /// true if [is white space] [the specified color]; otherwise, false.
+ private static bool IsWhiteSpace(Color color)
+ {
+ return (color.R == 255 && color.G == 255 && color.B == 255) || color.A == 0;
+ }
+ }
+}
diff --git a/Emby.Drawing/GDI/PercentPlayedDrawer.cs b/Emby.Drawing/GDI/PercentPlayedDrawer.cs
new file mode 100644
index 0000000000..c7afda60e4
--- /dev/null
+++ b/Emby.Drawing/GDI/PercentPlayedDrawer.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Drawing;
+
+namespace Emby.Drawing.GDI
+{
+ public class PercentPlayedDrawer
+ {
+ private const int IndicatorHeight = 8;
+
+ public void Process(Graphics graphics, Size imageSize, double percent)
+ {
+ var y = imageSize.Height - IndicatorHeight;
+
+ using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 0, 0, 0)))
+ {
+ const int innerX = 0;
+ var innerY = y;
+ var innerWidth = imageSize.Width;
+ var innerHeight = imageSize.Height;
+
+ graphics.FillRectangle(backdroundBrush, innerX, innerY, innerWidth, innerHeight);
+
+ using (var foregroundBrush = new SolidBrush(Color.FromArgb(82, 181, 75)))
+ {
+ double foregroundWidth = innerWidth;
+ foregroundWidth *= percent;
+ foregroundWidth /= 100;
+
+ graphics.FillRectangle(foregroundBrush, innerX, innerY, Convert.ToInt32(Math.Round(foregroundWidth)), innerHeight);
+ }
+ }
+ }
+ }
+}
diff --git a/Emby.Drawing/GDI/PlayedIndicatorDrawer.cs b/Emby.Drawing/GDI/PlayedIndicatorDrawer.cs
new file mode 100644
index 0000000000..4428e4cbac
--- /dev/null
+++ b/Emby.Drawing/GDI/PlayedIndicatorDrawer.cs
@@ -0,0 +1,32 @@
+using System.Drawing;
+
+namespace Emby.Drawing.GDI
+{
+ public class PlayedIndicatorDrawer
+ {
+ private const int IndicatorHeight = 40;
+ public const int IndicatorWidth = 40;
+ private const int FontSize = 40;
+ private const int OffsetFromTopRightCorner = 10;
+
+ public void DrawPlayedIndicator(Graphics graphics, Size imageSize)
+ {
+ var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
+
+ using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75)))
+ {
+ graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight);
+
+ x = imageSize.Width - 45 - OffsetFromTopRightCorner;
+
+ using (var font = new Font("Webdings", FontSize, FontStyle.Regular, GraphicsUnit.Pixel))
+ {
+ using (var fontBrush = new SolidBrush(Color.White))
+ {
+ graphics.DrawString("a", font, fontBrush, x, OffsetFromTopRightCorner - 2);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/Emby.Drawing/GDI/UnplayedCountIndicator.cs b/Emby.Drawing/GDI/UnplayedCountIndicator.cs
new file mode 100644
index 0000000000..6420abb27f
--- /dev/null
+++ b/Emby.Drawing/GDI/UnplayedCountIndicator.cs
@@ -0,0 +1,50 @@
+using System.Drawing;
+
+namespace Emby.Drawing.GDI
+{
+ public class UnplayedCountIndicator
+ {
+ private const int IndicatorHeight = 41;
+ public const int IndicatorWidth = 41;
+ private const int OffsetFromTopRightCorner = 10;
+
+ public void DrawUnplayedCountIndicator(Graphics graphics, Size imageSize, int count)
+ {
+ var x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
+
+ using (var backdroundBrush = new SolidBrush(Color.FromArgb(225, 82, 181, 75)))
+ {
+ graphics.FillEllipse(backdroundBrush, x, OffsetFromTopRightCorner, IndicatorWidth, IndicatorHeight);
+
+ var text = count.ToString();
+
+ x = imageSize.Width - IndicatorWidth - OffsetFromTopRightCorner;
+ var y = OffsetFromTopRightCorner + 6;
+ var fontSize = 24;
+
+ if (text.Length == 1)
+ {
+ x += 10;
+ }
+ else if (text.Length == 2)
+ {
+ x += 3;
+ }
+ else if (text.Length == 3)
+ {
+ x += 1;
+ y += 1;
+ fontSize = 20;
+ }
+
+ using (var font = new Font("Sans-Serif", fontSize, FontStyle.Regular, GraphicsUnit.Pixel))
+ {
+ using (var fontBrush = new SolidBrush(Color.White))
+ {
+ graphics.DrawString(text, font, fontBrush, x, y);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/Emby.Drawing/IImageEncoder.cs b/Emby.Drawing/IImageEncoder.cs
new file mode 100644
index 0000000000..29261dbdb3
--- /dev/null
+++ b/Emby.Drawing/IImageEncoder.cs
@@ -0,0 +1,53 @@
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Model.Drawing;
+using System;
+
+namespace Emby.Drawing
+{
+ public interface IImageEncoder : IDisposable
+ {
+ ///
+ /// Gets the supported input formats.
+ ///
+ /// The supported input formats.
+ string[] SupportedInputFormats { get; }
+ ///
+ /// Gets the supported output formats.
+ ///
+ /// The supported output formats.
+ ImageFormat[] SupportedOutputFormats { get; }
+ ///
+ /// Gets the size of the image.
+ ///
+ /// The path.
+ /// ImageSize.
+ ImageSize GetImageSize(string path);
+ ///
+ /// Crops the white space.
+ ///
+ /// The input path.
+ /// The output path.
+ void CropWhiteSpace(string inputPath, string outputPath);
+ ///
+ /// Encodes the image.
+ ///
+ /// The input path.
+ /// The output path.
+ /// The width.
+ /// The height.
+ /// The quality.
+ /// The options.
+ void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options);
+
+ ///
+ /// Creates the image collage.
+ ///
+ /// The options.
+ void CreateImageCollage(ImageCollageOptions options);
+ ///
+ /// Gets the name.
+ ///
+ /// The name.
+ string Name { get; }
+ }
+}
diff --git a/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs
new file mode 100644
index 0000000000..3d6cdd03dd
--- /dev/null
+++ b/Emby.Drawing/ImageMagick/ImageMagickEncoder.cs
@@ -0,0 +1,229 @@
+using ImageMagickSharp;
+using MediaBrowser.Common.Configuration;
+using MediaBrowser.Controller.Drawing;
+using MediaBrowser.Model.Drawing;
+using MediaBrowser.Model.Logging;
+using System;
+using System.IO;
+
+namespace Emby.Drawing.ImageMagick
+{
+ public class ImageMagickEncoder : IImageEncoder
+ {
+ private readonly ILogger _logger;
+ private readonly IApplicationPaths _appPaths;
+
+ public ImageMagickEncoder(ILogger logger, IApplicationPaths appPaths)
+ {
+ _logger = logger;
+ _appPaths = appPaths;
+
+ LogImageMagickVersion();
+ }
+
+ public string[] SupportedInputFormats
+ {
+ get
+ {
+ // Some common file name extensions for RAW picture files include: .cr2, .crw, .dng, .nef, .orf, .rw2, .pef, .arw, .sr2, .srf, and .tif.
+ return new[]
+ {
+ "tiff",
+ "jpeg",
+ "jpg",
+ "png",
+ "aiff",
+ "cr2",
+ "crw",
+ "dng",
+ "nef",
+ "orf",
+ "pef",
+ "arw",
+ "webp",
+ "gif",
+ "bmp"
+ };
+ }
+ }
+
+ public ImageFormat[] SupportedOutputFormats
+ {
+ get
+ {
+ if (_webpAvailable)
+ {
+ return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
+ }
+ return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
+ }
+ }
+
+ private void LogImageMagickVersion()
+ {
+ _logger.Info("ImageMagick version: " + Wand.VersionString);
+ TestWebp();
+ }
+
+ private bool _webpAvailable = true;
+ private void TestWebp()
+ {
+ try
+ {
+ var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
+ Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
+
+ using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
+ {
+ wand.SaveImage(tmpPath);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error loading webp: ", ex);
+ _webpAvailable = false;
+ }
+ }
+
+ public void CropWhiteSpace(string inputPath, string outputPath)
+ {
+ CheckDisposed();
+
+ using (var wand = new MagickWand(inputPath))
+ {
+ wand.CurrentImage.TrimImage(10);
+ wand.SaveImage(outputPath);
+ }
+ }
+
+ public ImageSize GetImageSize(string path)
+ {
+ CheckDisposed();
+
+ using (var wand = new MagickWand())
+ {
+ wand.PingImage(path);
+ var img = wand.CurrentImage;
+
+ return new ImageSize
+ {
+ Width = img.Width,
+ Height = img.Height
+ };
+ }
+ }
+
+ public void EncodeImage(string inputPath, string outputPath, int width, int height, int quality, ImageProcessingOptions options)
+ {
+ if (string.IsNullOrWhiteSpace(options.BackgroundColor))
+ {
+ using (var originalImage = new MagickWand(inputPath))
+ {
+ originalImage.CurrentImage.ResizeImage(width, height);
+
+ DrawIndicator(originalImage, width, height, options);
+
+ originalImage.CurrentImage.CompressionQuality = quality;
+
+ originalImage.SaveImage(outputPath);
+ }
+ }
+ else
+ {
+ using (var wand = new MagickWand(width, height, options.BackgroundColor))
+ {
+ using (var originalImage = new MagickWand(inputPath))
+ {
+ originalImage.CurrentImage.ResizeImage(width, height);
+
+ wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
+ DrawIndicator(wand, width, height, options);
+
+ wand.CurrentImage.CompressionQuality = quality;
+
+ wand.SaveImage(outputPath);
+ }
+ }
+ }
+ }
+
+ ///
+ /// Draws the indicator.
+ ///
+ /// The wand.
+ /// Width of the image.
+ /// Height of the image.
+ /// The options.
+ private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
+ {
+ if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
+ {
+ return;
+ }
+
+ try
+ {
+ if (options.AddPlayedIndicator)
+ {
+ var currentImageSize = new ImageSize(imageWidth, imageHeight);
+
+ new PlayedIndicatorDrawer(_appPaths).DrawPlayedIndicator(wand, currentImageSize);
+ }
+ else if (options.UnplayedCount.HasValue)
+ {
+ var currentImageSize = new ImageSize(imageWidth, imageHeight);
+
+ new UnplayedCountIndicator(_appPaths).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
+ }
+
+ if (options.PercentPlayed > 0)
+ {
+ new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.ErrorException("Error drawing indicator overlay", ex);
+ }
+ }
+
+ public void CreateImageCollage(ImageCollageOptions options)
+ {
+ double ratio = options.Width;
+ ratio /= options.Height;
+
+ if (ratio >= 1.4)
+ {
+ new StripCollageBuilder(_appPaths).BuildThumbCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, options.Text);
+ }
+ else if (ratio >= .9)
+ {
+ new StripCollageBuilder(_appPaths).BuildSquareCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, options.Text);
+ }
+ else
+ {
+ new StripCollageBuilder(_appPaths).BuildPosterCollage(options.InputPaths, options.OutputPath, options.Width, options.Height, options.Text);
+ }
+ }
+
+ public string Name
+ {
+ get { return "ImageMagick"; }
+ }
+
+ private bool _disposed;
+ public void Dispose()
+ {
+ _disposed = true;
+ Wand.CloseEnvironment();
+ }
+
+ private void CheckDisposed()
+ {
+ if (_disposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Server.Implementations/Drawing/PercentPlayedDrawer.cs b/Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs
similarity index 95%
rename from MediaBrowser.Server.Implementations/Drawing/PercentPlayedDrawer.cs
rename to Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs
index 20c2ab93be..90f9d56095 100644
--- a/MediaBrowser.Server.Implementations/Drawing/PercentPlayedDrawer.cs
+++ b/Emby.Drawing/ImageMagick/PercentPlayedDrawer.cs
@@ -1,7 +1,7 @@
using ImageMagickSharp;
using System;
-namespace MediaBrowser.Server.Implementations.Drawing
+namespace Emby.Drawing.ImageMagick
{
public class PercentPlayedDrawer
{
diff --git a/MediaBrowser.Server.Implementations/Drawing/PlayedIndicatorDrawer.cs b/Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs
similarity index 98%
rename from MediaBrowser.Server.Implementations/Drawing/PlayedIndicatorDrawer.cs
rename to Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs
index 359065cc2e..5eeb157715 100644
--- a/MediaBrowser.Server.Implementations/Drawing/PlayedIndicatorDrawer.cs
+++ b/Emby.Drawing/ImageMagick/PlayedIndicatorDrawer.cs
@@ -4,7 +4,7 @@ using MediaBrowser.Model.Drawing;
using System;
using System.IO;
-namespace MediaBrowser.Server.Implementations.Drawing
+namespace Emby.Drawing.ImageMagick
{
public class PlayedIndicatorDrawer
{
diff --git a/Emby.Drawing/ImageMagick/StripCollageBuilder.cs b/Emby.Drawing/ImageMagick/StripCollageBuilder.cs
new file mode 100644
index 0000000000..7cdd0077de
--- /dev/null
+++ b/Emby.Drawing/ImageMagick/StripCollageBuilder.cs
@@ -0,0 +1,518 @@
+using ImageMagickSharp;
+using MediaBrowser.Common.Configuration;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Emby.Drawing.ImageMagick
+{
+ public class StripCollageBuilder
+ {
+ private readonly IApplicationPaths _appPaths;
+
+ public StripCollageBuilder(IApplicationPaths appPaths)
+ {
+ _appPaths = appPaths;
+ }
+
+ public void BuildPosterCollage(IEnumerable paths, string outputPath, int width, int height, string text)
+ {
+ if (!string.IsNullOrWhiteSpace(text))
+ {
+ using (var wand = BuildPosterCollageWandWithText(paths, text, width, height))
+ {
+ wand.SaveImage(outputPath);
+ }
+ }
+ else
+ {
+ using (var wand = BuildPosterCollageWand(paths, width, height))
+ {
+ wand.SaveImage(outputPath);
+ }
+ }
+ }
+
+ public void BuildSquareCollage(IEnumerable paths, string outputPath, int width, int height, string text)
+ {
+ if (!string.IsNullOrWhiteSpace(text))
+ {
+ using (var wand = BuildSquareCollageWandWithText(paths, text, width, height))
+ {
+ wand.SaveImage(outputPath);
+ }
+ }
+ else
+ {
+ using (var wand = BuildSquareCollageWand(paths, width, height))
+ {
+ wand.SaveImage(outputPath);
+ }
+ }
+ }
+
+ public void BuildThumbCollage(IEnumerable paths, string outputPath, int width, int height, string text)
+ {
+ if (!string.IsNullOrWhiteSpace(text))
+ {
+ using (var wand = BuildThumbCollageWandWithText(paths, text, width, height))
+ {
+ wand.SaveImage(outputPath);
+ }
+ }
+ else
+ {
+ using (var wand = BuildThumbCollageWand(paths, width, height))
+ {
+ wand.SaveImage(outputPath);
+ }
+ }
+ }
+
+ internal static string[] ProjectPaths(IEnumerable paths, int count)
+ {
+ var clone = paths.ToList();
+ var list = new List();
+
+ while (list.Count < count)
+ {
+ foreach (var path in clone)
+ {
+ list.Add(path);
+
+ if (list.Count >= count)
+ {
+ break;
+ }
+ }
+ }
+
+ return list.Take(count).ToArray();
+ }
+
+ private MagickWand BuildThumbCollageWandWithText(IEnumerable paths, string text, int width, int height)
+ {
+ var inputPaths = ProjectPaths(paths, 8);
+ using (var wandImages = new MagickWand(inputPaths))
+ {
+ var wand = new MagickWand(width, height);
+ wand.OpenImage("gradient:#111111-#111111");
+ using (var draw = new DrawingWand())
+ {
+ using (var fcolor = new PixelWand(ColorName.White))
+ {
+ draw.FillColor = fcolor;
+ draw.Font = MontserratLightFont;
+ draw.FontSize = 60;
+ draw.FontWeight = FontWeightType.LightStyle;
+ draw.TextAntialias = true;
+ }
+
+ var fontMetrics = wand.QueryFontMetrics(draw, text);
+ var textContainerY = Convert.ToInt32(height * .165);
+ wand.CurrentImage.AnnotateImage(draw, (width - fontMetrics.TextWidth) / 2, textContainerY, 0.0, text);
+
+ var iSlice = Convert.ToInt32(width * .1166666667);
+ int iTrans = Convert.ToInt32(height * 0.2);
+ int iHeight = Convert.ToInt32(height * 0.46296296296296296296296296296296);
+ var horizontalImagePadding = Convert.ToInt32(width * 0.0125);
+
+ foreach (var element in wandImages.ImageList)
+ {
+ int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
+ element.Gravity = GravityType.CenterGravity;
+ element.BackgroundColor = new PixelWand("none", 1);
+ element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
+ int ix = (int)Math.Abs((iWidth - iSlice) / 2);
+ element.CropImage(iSlice, iHeight, ix, 0);
+
+ element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
+ }
+
+ wandImages.SetFirstIterator();
+ using (var wandList = wandImages.AppendImages())
+ {
+ wandList.CurrentImage.TrimImage(1);
+ using (var mwr = wandList.CloneMagickWand())
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ using (var greyPixelWand = new PixelWand(ColorName.Grey70))
+ {
+ mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
+ mwr.CurrentImage.FlipImage();
+
+ mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
+ mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
+
+ using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
+ {
+ mwg.OpenImage("gradient:black-none");
+ var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
+ mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.DstInCompositeOp, 0, verticalSpacing);
+
+ wandList.AddImage(mwr);
+ int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
+ wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * 0.26851851851851851851851851851852));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return wand;
+ }
+ }
+
+ private MagickWand BuildPosterCollageWand(IEnumerable paths, int width, int height)
+ {
+ var inputPaths = ProjectPaths(paths, 4);
+ using (var wandImages = new MagickWand(inputPaths))
+ {
+ var wand = new MagickWand(width, height);
+ wand.OpenImage("gradient:#111111-#111111");
+ using (var draw = new DrawingWand())
+ {
+ var iSlice = Convert.ToInt32(width * 0.225);
+ int iTrans = Convert.ToInt32(height * .25);
+ int iHeight = Convert.ToInt32(height * .65);
+ var horizontalImagePadding = Convert.ToInt32(width * 0.0275);
+
+ foreach (var element in wandImages.ImageList)
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
+ element.Gravity = GravityType.CenterGravity;
+ element.BackgroundColor = blackPixelWand;
+ element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
+ int ix = (int)Math.Abs((iWidth - iSlice) / 2);
+ element.CropImage(iSlice, iHeight, ix, 0);
+
+ element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
+ }
+ }
+
+ wandImages.SetFirstIterator();
+ using (var wandList = wandImages.AppendImages())
+ {
+ wandList.CurrentImage.TrimImage(1);
+ using (var mwr = wandList.CloneMagickWand())
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ using (var greyPixelWand = new PixelWand(ColorName.Grey70))
+ {
+ mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
+ mwr.CurrentImage.FlipImage();
+
+ mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
+ mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
+
+ using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
+ {
+ mwg.OpenImage("gradient:black-none");
+ var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
+ mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
+
+ wandList.AddImage(mwr);
+ int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
+ wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .05));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return wand;
+ }
+ }
+
+ private MagickWand BuildPosterCollageWandWithText(IEnumerable paths, string label, int width, int height)
+ {
+ var inputPaths = ProjectPaths(paths, 4);
+ using (var wandImages = new MagickWand(inputPaths))
+ {
+ var wand = new MagickWand(width, height);
+ wand.OpenImage("gradient:#111111-#111111");
+ using (var draw = new DrawingWand())
+ {
+ using (var fcolor = new PixelWand(ColorName.White))
+ {
+ draw.FillColor = fcolor;
+ draw.Font = MontserratLightFont;
+ draw.FontSize = 60;
+ draw.FontWeight = FontWeightType.LightStyle;
+ draw.TextAntialias = true;
+ }
+
+ var fontMetrics = wand.QueryFontMetrics(draw, label);
+ var textContainerY = Convert.ToInt32(height * .165);
+ wand.CurrentImage.AnnotateImage(draw, (width - fontMetrics.TextWidth) / 2, textContainerY, 0.0, label);
+
+ var iSlice = Convert.ToInt32(width * 0.225);
+ int iTrans = Convert.ToInt32(height * 0.2);
+ int iHeight = Convert.ToInt32(height * 0.46296296296296296296296296296296);
+ var horizontalImagePadding = Convert.ToInt32(width * 0.0275);
+
+ foreach (var element in wandImages.ImageList)
+ {
+ int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
+ element.Gravity = GravityType.CenterGravity;
+ element.BackgroundColor = new PixelWand("none", 1);
+ element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
+ int ix = (int)Math.Abs((iWidth - iSlice) / 2);
+ element.CropImage(iSlice, iHeight, ix, 0);
+
+ element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
+ }
+
+ wandImages.SetFirstIterator();
+ using (var wandList = wandImages.AppendImages())
+ {
+ wandList.CurrentImage.TrimImage(1);
+ using (var mwr = wandList.CloneMagickWand())
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ using (var greyPixelWand = new PixelWand(ColorName.Grey70))
+ {
+ mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
+ mwr.CurrentImage.FlipImage();
+
+ mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
+ mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
+
+ using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
+ {
+ mwg.OpenImage("gradient:black-none");
+ var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
+ mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.DstInCompositeOp, 0, verticalSpacing);
+
+ wandList.AddImage(mwr);
+ int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
+ wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * 0.26851851851851851851851851851852));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return wand;
+ }
+ }
+
+ private MagickWand BuildThumbCollageWand(IEnumerable paths, int width, int height)
+ {
+ var inputPaths = ProjectPaths(paths, 8);
+ using (var wandImages = new MagickWand(inputPaths))
+ {
+ var wand = new MagickWand(width, height);
+ wand.OpenImage("gradient:#111111-#111111");
+ using (var draw = new DrawingWand())
+ {
+ var iSlice = Convert.ToInt32(width * .1166666667);
+ int iTrans = Convert.ToInt32(height * .25);
+ int iHeight = Convert.ToInt32(height * .62);
+ var horizontalImagePadding = Convert.ToInt32(width * 0.0125);
+
+ foreach (var element in wandImages.ImageList)
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
+ element.Gravity = GravityType.CenterGravity;
+ element.BackgroundColor = blackPixelWand;
+ element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
+ int ix = (int)Math.Abs((iWidth - iSlice) / 2);
+ element.CropImage(iSlice, iHeight, ix, 0);
+
+ element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
+ }
+ }
+
+ wandImages.SetFirstIterator();
+ using (var wandList = wandImages.AppendImages())
+ {
+ wandList.CurrentImage.TrimImage(1);
+ using (var mwr = wandList.CloneMagickWand())
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ using (var greyPixelWand = new PixelWand(ColorName.Grey70))
+ {
+ mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
+ mwr.CurrentImage.FlipImage();
+
+ mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
+ mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
+
+ using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
+ {
+ mwg.OpenImage("gradient:black-none");
+ var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
+ mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
+
+ wandList.AddImage(mwr);
+ int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
+ wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .085));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return wand;
+ }
+ }
+
+ private MagickWand BuildSquareCollageWand(IEnumerable paths, int width, int height)
+ {
+ var inputPaths = ProjectPaths(paths, 4);
+ using (var wandImages = new MagickWand(inputPaths))
+ {
+ var wand = new MagickWand(width, height);
+ wand.OpenImage("gradient:#111111-#111111");
+ using (var draw = new DrawingWand())
+ {
+ var iSlice = Convert.ToInt32(width * .225);
+ int iTrans = Convert.ToInt32(height * .25);
+ int iHeight = Convert.ToInt32(height * .63);
+ var horizontalImagePadding = Convert.ToInt32(width * 0.02);
+
+ foreach (var element in wandImages.ImageList)
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
+ element.Gravity = GravityType.CenterGravity;
+ element.BackgroundColor = blackPixelWand;
+ element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
+ int ix = (int)Math.Abs((iWidth - iSlice) / 2);
+ element.CropImage(iSlice, iHeight, ix, 0);
+
+ element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
+ }
+ }
+
+ wandImages.SetFirstIterator();
+ using (var wandList = wandImages.AppendImages())
+ {
+ wandList.CurrentImage.TrimImage(1);
+ using (var mwr = wandList.CloneMagickWand())
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ using (var greyPixelWand = new PixelWand(ColorName.Grey70))
+ {
+ mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
+ mwr.CurrentImage.FlipImage();
+
+ mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
+ mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
+
+ using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
+ {
+ mwg.OpenImage("gradient:black-none");
+ var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
+ mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.CopyOpacityCompositeOp, 0, verticalSpacing);
+
+ wandList.AddImage(mwr);
+ int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
+ wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * .07));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return wand;
+ }
+ }
+
+ private MagickWand BuildSquareCollageWandWithText(IEnumerable paths, string label, int width, int height)
+ {
+ var inputPaths = ProjectPaths(paths, 4);
+ using (var wandImages = new MagickWand(inputPaths))
+ {
+ var wand = new MagickWand(width, height);
+ wand.OpenImage("gradient:#111111-#111111");
+ using (var draw = new DrawingWand())
+ {
+ using (var fcolor = new PixelWand(ColorName.White))
+ {
+ draw.FillColor = fcolor;
+ draw.Font = MontserratLightFont;
+ draw.FontSize = 60;
+ draw.FontWeight = FontWeightType.LightStyle;
+ draw.TextAntialias = true;
+ }
+
+ var fontMetrics = wand.QueryFontMetrics(draw, label);
+ var textContainerY = Convert.ToInt32(height * .165);
+ wand.CurrentImage.AnnotateImage(draw, (width - fontMetrics.TextWidth) / 2, textContainerY, 0.0, label);
+
+ var iSlice = Convert.ToInt32(width * .225);
+ int iTrans = Convert.ToInt32(height * 0.2);
+ int iHeight = Convert.ToInt32(height * 0.46296296296296296296296296296296);
+ var horizontalImagePadding = Convert.ToInt32(width * 0.02);
+
+ foreach (var element in wandImages.ImageList)
+ {
+ int iWidth = (int)Math.Abs(iHeight * element.Width / element.Height);
+ element.Gravity = GravityType.CenterGravity;
+ element.BackgroundColor = new PixelWand("none", 1);
+ element.ResizeImage(iWidth, iHeight, FilterTypes.LanczosFilter);
+ int ix = (int)Math.Abs((iWidth - iSlice) / 2);
+ element.CropImage(iSlice, iHeight, ix, 0);
+
+ element.ExtentImage(iSlice, iHeight, 0 - horizontalImagePadding, 0);
+ }
+
+ wandImages.SetFirstIterator();
+ using (var wandList = wandImages.AppendImages())
+ {
+ wandList.CurrentImage.TrimImage(1);
+ using (var mwr = wandList.CloneMagickWand())
+ {
+ using (var blackPixelWand = new PixelWand(ColorName.Black))
+ {
+ using (var greyPixelWand = new PixelWand(ColorName.Grey70))
+ {
+ mwr.CurrentImage.ResizeImage(wandList.CurrentImage.Width, (wandList.CurrentImage.Height / 2), FilterTypes.LanczosFilter, 1);
+ mwr.CurrentImage.FlipImage();
+
+ mwr.CurrentImage.AlphaChannel = AlphaChannelType.DeactivateAlphaChannel;
+ mwr.CurrentImage.ColorizeImage(blackPixelWand, greyPixelWand);
+
+ using (var mwg = new MagickWand(wandList.CurrentImage.Width, iTrans))
+ {
+ mwg.OpenImage("gradient:black-none");
+ var verticalSpacing = Convert.ToInt32(height * 0.01111111111111111111111111111111);
+ mwr.CurrentImage.CompositeImage(mwg, CompositeOperator.DstInCompositeOp, 0, verticalSpacing);
+
+ wandList.AddImage(mwr);
+ int ex = (int)(wand.CurrentImage.Width - mwg.CurrentImage.Width) / 2;
+ wand.CurrentImage.CompositeImage(wandList.AppendImages(true), CompositeOperator.AtopCompositeOp, ex, Convert.ToInt32(height * 0.26851851851851851851851851851852));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return wand;
+ }
+ }
+
+ private string MontserratLightFont
+ {
+ get { return PlayedIndicatorDrawer.ExtractFont("MontserratLight.otf", _appPaths); }
+ }
+ }
+}
diff --git a/MediaBrowser.Server.Implementations/Drawing/UnplayedCountIndicator.cs b/Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs
similarity index 97%
rename from MediaBrowser.Server.Implementations/Drawing/UnplayedCountIndicator.cs
rename to Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs
index 71cced0416..dd25004d66 100644
--- a/MediaBrowser.Server.Implementations/Drawing/UnplayedCountIndicator.cs
+++ b/Emby.Drawing/ImageMagick/UnplayedCountIndicator.cs
@@ -3,7 +3,7 @@ using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Drawing;
using System.Globalization;
-namespace MediaBrowser.Server.Implementations.Drawing
+namespace Emby.Drawing.ImageMagick
{
public class UnplayedCountIndicator
{
diff --git a/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs b/Emby.Drawing/ImageProcessor.cs
similarity index 83%
rename from MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs
rename to Emby.Drawing/ImageProcessor.cs
index d78d5e8ea1..c7d06559ac 100644
--- a/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs
+++ b/Emby.Drawing/ImageProcessor.cs
@@ -1,4 +1,4 @@
-using ImageMagickSharp;
+using Emby.Drawing.Common;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller;
@@ -18,7 +18,7 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-namespace MediaBrowser.Server.Implementations.Drawing
+namespace Emby.Drawing
{
///
/// Class ImageProcessor
@@ -50,12 +50,14 @@ namespace MediaBrowser.Server.Implementations.Drawing
private readonly IFileSystem _fileSystem;
private readonly IJsonSerializer _jsonSerializer;
private readonly IServerApplicationPaths _appPaths;
+ private readonly IImageEncoder _imageEncoder;
- public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
+ public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IImageEncoder imageEncoder)
{
_logger = logger;
_fileSystem = fileSystem;
_jsonSerializer = jsonSerializer;
+ _imageEncoder = imageEncoder;
_appPaths = appPaths;
_saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
@@ -85,8 +87,14 @@ namespace MediaBrowser.Server.Implementations.Drawing
}
_cachedImagedSizes = new ConcurrentDictionary(sizeDictionary);
+ }
- LogImageMagickVersionVersion();
+ public string[] SupportedInputFormats
+ {
+ get
+ {
+ return _imageEncoder.SupportedInputFormats;
+ }
}
private string ResizedImageCachePath
@@ -130,44 +138,7 @@ namespace MediaBrowser.Server.Implementations.Drawing
public ImageFormat[] GetSupportedImageOutputFormats()
{
- if (_webpAvailable)
- {
- return new[] { ImageFormat.Webp, ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
- }
- return new[] { ImageFormat.Gif, ImageFormat.Jpg, ImageFormat.Png };
- }
-
- private bool _webpAvailable = true;
- private void TestWebp()
- {
- try
- {
- var tmpPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".webp");
- Directory.CreateDirectory(Path.GetDirectoryName(tmpPath));
-
- using (var wand = new MagickWand(1, 1, new PixelWand("none", 1)))
- {
- wand.SaveImage(tmpPath);
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error loading webp: ", ex);
- _webpAvailable = false;
- }
- }
-
- private void LogImageMagickVersionVersion()
- {
- try
- {
- _logger.Info("ImageMagick version: " + Wand.VersionString);
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error loading ImageMagick: ", ex);
- }
- TestWebp();
+ return _imageEncoder.SupportedOutputFormats;
}
public async Task ProcessImage(ImageProcessingOptions options)
@@ -244,36 +215,7 @@ namespace MediaBrowser.Server.Implementations.Drawing
Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
- if (string.IsNullOrWhiteSpace(options.BackgroundColor))
- {
- using (var originalImage = new MagickWand(originalImagePath))
- {
- originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
-
- DrawIndicator(originalImage, newWidth, newHeight, options);
-
- originalImage.CurrentImage.CompressionQuality = quality;
-
- originalImage.SaveImage(cacheFilePath);
- }
- }
- else
- {
- using (var wand = new MagickWand(newWidth, newHeight, options.BackgroundColor))
- {
- using (var originalImage = new MagickWand(originalImagePath))
- {
- originalImage.CurrentImage.ResizeImage(newWidth, newHeight);
-
- wand.CurrentImage.CompositeImage(originalImage, CompositeOperator.OverCompositeOp, 0, 0);
- DrawIndicator(wand, newWidth, newHeight, options);
-
- wand.CurrentImage.CompressionQuality = quality;
-
- wand.SaveImage(cacheFilePath);
- }
- }
- }
+ _imageEncoder.EncodeImage(originalImagePath, cacheFilePath, newWidth, newHeight, quality, options);
}
}
finally
@@ -286,7 +228,7 @@ namespace MediaBrowser.Server.Implementations.Drawing
private ImageFormat GetOutputFormat(ImageFormat requestedFormat)
{
- if (requestedFormat == ImageFormat.Webp && !_webpAvailable)
+ if (requestedFormat == ImageFormat.Webp && !_imageEncoder.SupportedOutputFormats.Contains(ImageFormat.Webp))
{
return ImageFormat.Png;
}
@@ -294,46 +236,6 @@ namespace MediaBrowser.Server.Implementations.Drawing
return requestedFormat;
}
- ///
- /// Draws the indicator.
- ///
- /// The wand.
- /// Width of the image.
- /// Height of the image.
- /// The options.
- private void DrawIndicator(MagickWand wand, int imageWidth, int imageHeight, ImageProcessingOptions options)
- {
- if (!options.AddPlayedIndicator && !options.UnplayedCount.HasValue && options.PercentPlayed.Equals(0))
- {
- return;
- }
-
- try
- {
- if (options.AddPlayedIndicator)
- {
- var currentImageSize = new ImageSize(imageWidth, imageHeight);
-
- new PlayedIndicatorDrawer(_appPaths).DrawPlayedIndicator(wand, currentImageSize);
- }
- else if (options.UnplayedCount.HasValue)
- {
- var currentImageSize = new ImageSize(imageWidth, imageHeight);
-
- new UnplayedCountIndicator(_appPaths).DrawUnplayedCountIndicator(wand, currentImageSize, options.UnplayedCount.Value);
- }
-
- if (options.PercentPlayed > 0)
- {
- new PercentPlayedDrawer().Process(wand, options.PercentPlayed);
- }
- }
- catch (Exception ex)
- {
- _logger.ErrorException("Error drawing indicator overlay", ex);
- }
- }
-
///
/// Crops whitespace from an image, caches the result, and returns the cached path
///
@@ -360,11 +262,7 @@ namespace MediaBrowser.Server.Implementations.Drawing
{
Directory.CreateDirectory(Path.GetDirectoryName(croppedImagePath));
- using (var wand = new MagickWand(originalImagePath))
- {
- wand.CurrentImage.TrimImage(10);
- wand.SaveImage(croppedImagePath);
- }
+ _imageEncoder.CropWhiteSpace(originalImagePath, croppedImagePath);
}
catch (Exception ex)
{
@@ -500,17 +398,7 @@ namespace MediaBrowser.Server.Implementations.Drawing
CheckDisposed();
- using (var wand = new MagickWand())
- {
- wand.PingImage(path);
- var img = wand.CurrentImage;
-
- size = new ImageSize
- {
- Width = img.Width,
- Height = img.Height
- };
- }
+ size = _imageEncoder.GetImageSize(path);
}
StartSaveImageSizeTimer();
@@ -838,6 +726,11 @@ namespace MediaBrowser.Server.Implementations.Drawing
return Path.Combine(path, filename);
}
+ public void CreateImageCollage(ImageCollageOptions options)
+ {
+ _imageEncoder.CreateImageCollage(options);
+ }
+
public IEnumerable GetSupportedEnhancers(IHasImages item, ImageType imageType)
{
return ImageEnhancers.Where(i =>
@@ -860,7 +753,7 @@ namespace MediaBrowser.Server.Implementations.Drawing
public void Dispose()
{
_disposed = true;
- Wand.CloseEnvironment();
+ _imageEncoder.Dispose();
_saveImageSizeTimer.Dispose();
}
diff --git a/Emby.Drawing/Properties/AssemblyInfo.cs b/Emby.Drawing/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000000..fba168d034
--- /dev/null
+++ b/Emby.Drawing/Properties/AssemblyInfo.cs
@@ -0,0 +1,31 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Emby.Drawing")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("Emby.Drawing")]
+[assembly: AssemblyCopyright("Copyright © 2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("87b6f14e-16d8-4a58-a553-fd9945e47458")]
+
+// Version information for an assembly consists of the following four values:
+//
+// Major Version
+// Minor Version
+// Build Number
+// Revision
+//
\ No newline at end of file
diff --git a/Emby.Drawing/packages.config b/Emby.Drawing/packages.config
new file mode 100644
index 0000000000..a331f20b3a
--- /dev/null
+++ b/Emby.Drawing/packages.config
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs
index 08ac5671d5..e91dd1a9b0 100644
--- a/MediaBrowser.Api/ApiEntryPoint.cs
+++ b/MediaBrowser.Api/ApiEntryPoint.cs
@@ -151,7 +151,7 @@ namespace MediaBrowser.Api
{
lock (_activeTranscodingJobs)
{
- var job = new TranscodingJob
+ var job = new TranscodingJob(Logger)
{
Type = type,
Path = path,
@@ -284,28 +284,72 @@ namespace MediaBrowser.Api
{
job.ActiveRequestCount++;
- job.DisposeKillTimer();
+ if (string.IsNullOrWhiteSpace(job.PlaySessionId) || job.Type == TranscodingJobType.Progressive)
+ {
+ job.StopKillTimer();
+ }
}
-
+
public void OnTranscodeEndRequest(TranscodingJob job)
{
job.ActiveRequestCount--;
+ Logger.Debug("OnTranscodeEndRequest job.ActiveRequestCount={0}", job.ActiveRequestCount);
+ if (job.ActiveRequestCount <= 0)
+ {
+ PingTimer(job, false);
+ }
+ }
+ internal void PingTranscodingJob(string playSessionId)
+ {
+ if (string.IsNullOrEmpty(playSessionId))
+ {
+ throw new ArgumentNullException("playSessionId");
+ }
+
+ Logger.Debug("PingTranscodingJob PlaySessionId={0}", playSessionId);
+
+ var jobs = new List();
- if (job.ActiveRequestCount == 0)
+ lock (_activeTranscodingJobs)
{
- // TODO: Lower this hls timeout
- var timerDuration = job.Type == TranscodingJobType.Progressive ?
- 1000 :
- 7200000;
+ // This is really only needed for HLS.
+ // Progressive streams can stop on their own reliably
+ jobs = jobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
+ }
- if (job.KillTimer == null)
- {
- job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
- }
- else
- {
- job.KillTimer.Change(timerDuration, Timeout.Infinite);
- }
+ foreach (var job in jobs)
+ {
+ PingTimer(job, true);
+ }
+ }
+
+ private void PingTimer(TranscodingJob job, bool isProgressCheckIn)
+ {
+ if (job.HasExited)
+ {
+ job.StopKillTimer();
+ return;
+ }
+
+ // TODO: Lower this hls timeout
+ var timerDuration = job.Type == TranscodingJobType.Progressive ?
+ 1000 :
+ 1800000;
+
+ // We can really reduce the timeout for apps that are using the newer api
+ if (!string.IsNullOrWhiteSpace(job.PlaySessionId) && job.Type != TranscodingJobType.Progressive)
+ {
+ timerDuration = 20000;
+ }
+
+ // Don't start the timer for playback checkins with progressive streaming
+ if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
+ {
+ job.StartKillTimer(timerDuration, OnTranscodeKillTimerStopped);
+ }
+ else
+ {
+ job.ChangeKillTimerIfStarted(timerDuration);
}
}
@@ -317,6 +361,8 @@ namespace MediaBrowser.Api
{
var job = (TranscodingJob)state;
+ Logger.Debug("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+
KillTranscodingJob(job, path => true);
}
@@ -329,19 +375,14 @@ namespace MediaBrowser.Api
/// Task.
internal void KillTranscodingJobs(string deviceId, string playSessionId, Func deleteFiles)
{
- if (string.IsNullOrEmpty(deviceId))
- {
- throw new ArgumentNullException("deviceId");
- }
-
KillTranscodingJobs(j =>
{
- if (string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase))
+ if (!string.IsNullOrWhiteSpace(playSessionId))
{
- return string.IsNullOrWhiteSpace(playSessionId) || string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase);
+ return string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase);
}
- return false;
+ return string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase);
}, deleteFiles);
}
@@ -381,6 +422,10 @@ namespace MediaBrowser.Api
/// The delete.
private void KillTranscodingJob(TranscodingJob job, Func delete)
{
+ job.DisposeKillTimer();
+
+ Logger.Debug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+
lock (_activeTranscodingJobs)
{
_activeTranscodingJobs.Remove(job);
@@ -389,34 +434,23 @@ namespace MediaBrowser.Api
{
job.CancellationTokenSource.Cancel();
}
-
- job.DisposeKillTimer();
}
lock (job.ProcessLock)
{
- var process = job.Process;
-
- var hasExited = true;
-
- try
+ if (job.TranscodingThrottler != null)
{
- hasExited = process.HasExited;
- }
- catch (Exception ex)
- {
- Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
+ job.TranscodingThrottler.Stop();
}
+ var process = job.Process;
+
+ var hasExited = job.HasExited;
+
if (!hasExited)
{
try
{
- if (job.TranscodingThrottler != null)
- {
- job.TranscodingThrottler.Stop();
- }
-
Logger.Info("Killing ffmpeg process for {0}", job.Path);
//process.Kill();
@@ -558,6 +592,7 @@ namespace MediaBrowser.Api
///
/// The process.
public Process Process { get; set; }
+ public ILogger Logger { get; private set; }
///
/// Gets or sets the active request count.
///
@@ -567,7 +602,7 @@ namespace MediaBrowser.Api
/// Gets or sets the kill timer.
///
/// The kill timer.
- public Timer KillTimer { get; set; }
+ private Timer KillTimer { get; set; }
public string DeviceId { get; set; }
@@ -590,12 +625,74 @@ namespace MediaBrowser.Api
public TranscodingThrottler TranscodingThrottler { get; set; }
+ private readonly object _timerLock = new object();
+
+ public TranscodingJob(ILogger logger)
+ {
+ Logger = logger;
+ }
+
+ public void StopKillTimer()
+ {
+ lock (_timerLock)
+ {
+ if (KillTimer != null)
+ {
+ KillTimer.Change(Timeout.Infinite, Timeout.Infinite);
+ }
+ }
+ }
+
public void DisposeKillTimer()
{
- if (KillTimer != null)
+ lock (_timerLock)
+ {
+ if (KillTimer != null)
+ {
+ KillTimer.Dispose();
+ KillTimer = null;
+ }
+ }
+ }
+
+ public void StartKillTimer(int intervalMs, TimerCallback callback)
+ {
+ CheckHasExited();
+
+ lock (_timerLock)
+ {
+ if (KillTimer == null)
+ {
+ Logger.Debug("Starting kill timer at {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ KillTimer = new Timer(callback, this, intervalMs, Timeout.Infinite);
+ }
+ else
+ {
+ Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ KillTimer.Change(intervalMs, Timeout.Infinite);
+ }
+ }
+ }
+
+ public void ChangeKillTimerIfStarted(int intervalMs)
+ {
+ CheckHasExited();
+
+ lock (_timerLock)
+ {
+ if (KillTimer != null)
+ {
+ Logger.Debug("Changing kill timer to {0}ms. JobId {1} PlaySessionId {2}", intervalMs, Id, PlaySessionId);
+ KillTimer.Change(intervalMs, Timeout.Infinite);
+ }
+ }
+ }
+
+ private void CheckHasExited()
+ {
+ if (HasExited)
{
- KillTimer.Dispose();
- KillTimer = null;
+ throw new ObjectDisposedException("Job");
}
}
}
diff --git a/MediaBrowser.Api/BaseApiService.cs b/MediaBrowser.Api/BaseApiService.cs
index 4465be97a2..66b2a314e4 100644
--- a/MediaBrowser.Api/BaseApiService.cs
+++ b/MediaBrowser.Api/BaseApiService.cs
@@ -259,7 +259,7 @@ namespace MediaBrowser.Api
.GetRecursiveChildren(i => i is IHasArtist)
.Cast()
.SelectMany(i => i.AllArtists)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .DistinctNames()
.FirstOrDefault(i =>
{
i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
@@ -281,7 +281,7 @@ namespace MediaBrowser.Api
return libraryManager.RootFolder.GetRecursiveChildren()
.SelectMany(i => i.Genres)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .DistinctNames()
.FirstOrDefault(i =>
{
i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
@@ -301,7 +301,7 @@ namespace MediaBrowser.Api
return libraryManager.RootFolder
.GetRecursiveChildren(i => i is Game)
.SelectMany(i => i.Genres)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .DistinctNames()
.FirstOrDefault(i =>
{
i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
@@ -324,7 +324,7 @@ namespace MediaBrowser.Api
return libraryManager.RootFolder
.GetRecursiveChildren()
.SelectMany(i => i.Studios)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .DistinctNames()
.FirstOrDefault(i =>
{
i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
@@ -348,7 +348,7 @@ namespace MediaBrowser.Api
.GetRecursiveChildren()
.SelectMany(i => i.People)
.Select(i => i.Name)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .DistinctNames()
.FirstOrDefault(i =>
{
i = _dashReplaceChars.Aggregate(i, (current, c) => current.Replace(c, SlugChar));
diff --git a/MediaBrowser.Api/ConfigurationService.cs b/MediaBrowser.Api/ConfigurationService.cs
index d0abd18c28..9f6c07dd21 100644
--- a/MediaBrowser.Api/ConfigurationService.cs
+++ b/MediaBrowser.Api/ConfigurationService.cs
@@ -123,7 +123,7 @@ namespace MediaBrowser.Api
public void Post(AutoSetMetadataOptions request)
{
- _configurationManager.DisableMetadataService("Media Browser Xml");
+ _configurationManager.DisableMetadataService("Emby Xml");
_configurationManager.SaveConfiguration();
}
diff --git a/MediaBrowser.Api/FilterService.cs b/MediaBrowser.Api/FilterService.cs
index fb51b2bdd4..6d1c5d868d 100644
--- a/MediaBrowser.Api/FilterService.cs
+++ b/MediaBrowser.Api/FilterService.cs
@@ -76,7 +76,7 @@ namespace MediaBrowser.Api
.ToArray();
result.Genres = items.SelectMany(i => i.Genres)
- .Distinct(StringComparer.OrdinalIgnoreCase)
+ .DistinctNames()
.OrderBy(i => i)
.ToArray();
diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs
index 24c91e172f..b8b74369ce 100644
--- a/MediaBrowser.Api/LiveTv/LiveTvService.cs
+++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs
@@ -1,4 +1,5 @@
-using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Dto;
+using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Dto;
@@ -186,6 +187,9 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
public bool? IsMovie { get; set; }
+ [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSports { get; set; }
+
[ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? StartIndex { get; set; }
@@ -218,6 +222,9 @@ namespace MediaBrowser.Api.LiveTv
[ApiMember(Name = "HasAired", Description = "Optional. Filter by programs that have completed airing, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool? HasAired { get; set; }
+ [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
+ public bool? IsSports { get; set; }
+
[ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool? IsMovie { get; set; }
}
@@ -422,11 +429,12 @@ namespace MediaBrowser.Api.LiveTv
query.SortBy = (request.SortBy ?? String.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
query.SortOrder = request.SortOrder;
query.IsMovie = request.IsMovie;
+ query.IsSports = request.IsSports;
query.Genres = (request.Genres ?? String.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var result = await _liveTvManager.GetPrograms(query, CancellationToken.None).ConfigureAwait(false);
- return ToOptimizedSerializedResultUsingCache(result);
+ return ToOptimizedResult(result);
}
public async Task