moved image manager to an interface

pull/702/head
Luke Pulverenti 11 years ago
parent bcd3e8e0fa
commit d58da2a772

@ -1,4 +1,4 @@
using MediaBrowser.Controller; using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
@ -13,7 +13,6 @@ using ServiceStack.ServiceHost;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace MediaBrowser.Api.DefaultTheme namespace MediaBrowser.Api.DefaultTheme
{ {
@ -68,24 +67,26 @@ namespace MediaBrowser.Api.DefaultTheme
private readonly ILibraryManager _libraryManager; private readonly ILibraryManager _libraryManager;
private readonly ILocalizationManager _localization; private readonly ILocalizationManager _localization;
private readonly IImageProcessor _imageProcessor;
public DefaultThemeService(IUserManager userManager, IDtoService dtoService, ILogger logger, ILibraryManager libraryManager, ILocalizationManager localization) public DefaultThemeService(IUserManager userManager, IDtoService dtoService, ILogger logger, ILibraryManager libraryManager, ILocalizationManager localization, IImageProcessor imageProcessor)
{ {
_userManager = userManager; _userManager = userManager;
_dtoService = dtoService; _dtoService = dtoService;
_logger = logger; _logger = logger;
_libraryManager = libraryManager; _libraryManager = libraryManager;
_localization = localization; _localization = localization;
_imageProcessor = imageProcessor;
} }
public object Get(GetHomeView request) public object Get(GetHomeView request)
{ {
var result = GetHomeView(request).Result; var result = GetHomeView(request);
return ToOptimizedResult(result); return ToOptimizedResult(result);
} }
private async Task<HomeView> GetHomeView(GetHomeView request) private HomeView GetHomeView(GetHomeView request)
{ {
var user = _userManager.GetUserById(request.UserId); var user = _userManager.GetUserById(request.UserId);
@ -113,12 +114,12 @@ namespace MediaBrowser.Api.DefaultTheme
public object Get(GetGamesView request) public object Get(GetGamesView request)
{ {
var result = GetGamesView(request).Result; var result = GetGamesView(request);
return ToOptimizedResult(result); return ToOptimizedResult(result);
} }
private async Task<GamesView> GetGamesView(GetGamesView request) private GamesView GetGamesView(GetGamesView request)
{ {
var user = _userManager.GetUserById(request.UserId); var user = _userManager.GetUserById(request.UserId);
@ -145,19 +146,19 @@ namespace MediaBrowser.Api.DefaultTheme
public object Get(GetMovieView request) public object Get(GetMovieView request)
{ {
var result = GetMovieView(request).Result; var result = GetMovieView(request);
return ToOptimizedResult(result); return ToOptimizedResult(result);
} }
public object Get(GetTvView request) public object Get(GetTvView request)
{ {
var result = GetTvView(request).Result; var result = GetTvView(request);
return ToOptimizedResult(result); return ToOptimizedResult(result);
} }
private async Task<TvView> GetTvView(GetTvView request) private TvView GetTvView(GetTvView request)
{ {
var user = _userManager.GetUserById(request.UserId); var user = _userManager.GetUserById(request.UserId);
@ -210,7 +211,7 @@ namespace MediaBrowser.Api.DefaultTheme
return view; return view;
} }
private async Task<MoviesView> GetMovieView(GetMovieView request) private MoviesView GetMovieView(GetMovieView request)
{ {
var user = _userManager.GetUserById(request.UserId); var user = _userManager.GetUserById(request.UserId);
@ -348,9 +349,9 @@ namespace MediaBrowser.Api.DefaultTheme
{ {
try try
{ {
var date = Kernel.Instance.ImageManager.GetImageDateModified(item, path); var date = item.GetImageDateModified(path);
var size = Kernel.Instance.ImageManager.GetImageSize(path, date); var size = _imageProcessor.GetImageSize(path, date);
return size.Width; return size.Width;
} }
@ -400,13 +401,11 @@ namespace MediaBrowser.Api.DefaultTheme
ImageType = imageType ImageType = imageType
}; };
var imageManager = Kernel.Instance.ImageManager;
try try
{ {
var imagePath = imageManager.GetImagePath(item, imageType, 0); var imagePath = item.GetImagePath(imageType, 0);
stub.ImageTag = imageManager.GetImageCacheTag(item, imageType, imagePath); stub.ImageTag = _imageProcessor.GetImageCacheTag(item, imageType, imagePath);
} }
catch (Exception ex) catch (Exception ex)
{ {

@ -2,6 +2,7 @@
using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
@ -338,11 +339,12 @@ namespace MediaBrowser.Api.Images
private readonly IItemRepository _itemRepo; private readonly IItemRepository _itemRepo;
private readonly IDtoService _dtoService; private readonly IDtoService _dtoService;
private readonly IImageProcessor _imageProcessor;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ImageService" /> class. /// Initializes a new instance of the <see cref="ImageService" /> class.
/// </summary> /// </summary>
public ImageService(IUserManager userManager, ILibraryManager libraryManager, IApplicationPaths appPaths, IProviderManager providerManager, IItemRepository itemRepo, IDtoService dtoService) public ImageService(IUserManager userManager, ILibraryManager libraryManager, IApplicationPaths appPaths, IProviderManager providerManager, IItemRepository itemRepo, IDtoService dtoService, IImageProcessor imageProcessor)
{ {
_userManager = userManager; _userManager = userManager;
_libraryManager = libraryManager; _libraryManager = libraryManager;
@ -350,6 +352,7 @@ namespace MediaBrowser.Api.Images
_providerManager = providerManager; _providerManager = providerManager;
_itemRepo = itemRepo; _itemRepo = itemRepo;
_dtoService = dtoService; _dtoService = dtoService;
_imageProcessor = imageProcessor;
} }
/// <summary> /// <summary>
@ -403,15 +406,13 @@ namespace MediaBrowser.Api.Images
var fileInfo = new FileInfo(path); var fileInfo = new FileInfo(path);
var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, path); var size = _imageProcessor.GetImageSize(path);
var size = Kernel.Instance.ImageManager.GetImageSize(path, dateModified);
list.Add(new ImageInfo list.Add(new ImageInfo
{ {
Path = path, Path = path,
ImageType = image.Key, ImageType = image.Key,
ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, image.Key, path), ImageTag = _imageProcessor.GetImageCacheTag(item, image.Key, path),
Size = fileInfo.Length, Size = fileInfo.Length,
Width = Convert.ToInt32(size.Width), Width = Convert.ToInt32(size.Width),
Height = Convert.ToInt32(size.Height) Height = Convert.ToInt32(size.Height)
@ -424,16 +425,14 @@ namespace MediaBrowser.Api.Images
{ {
var fileInfo = new FileInfo(image); var fileInfo = new FileInfo(image);
var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image); var size = _imageProcessor.GetImageSize(image);
var size = Kernel.Instance.ImageManager.GetImageSize(image, dateModified);
list.Add(new ImageInfo list.Add(new ImageInfo
{ {
Path = image, Path = image,
ImageIndex = index, ImageIndex = index,
ImageType = ImageType.Backdrop, ImageType = ImageType.Backdrop,
ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Backdrop, image), ImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Backdrop, image),
Size = fileInfo.Length, Size = fileInfo.Length,
Width = Convert.ToInt32(size.Width), Width = Convert.ToInt32(size.Width),
Height = Convert.ToInt32(size.Height) Height = Convert.ToInt32(size.Height)
@ -448,16 +447,14 @@ namespace MediaBrowser.Api.Images
{ {
var fileInfo = new FileInfo(image); var fileInfo = new FileInfo(image);
var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image); var size = _imageProcessor.GetImageSize(image);
var size = Kernel.Instance.ImageManager.GetImageSize(image, dateModified);
list.Add(new ImageInfo list.Add(new ImageInfo
{ {
Path = image, Path = image,
ImageIndex = index, ImageIndex = index,
ImageType = ImageType.Screenshot, ImageType = ImageType.Screenshot,
ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Screenshot, image), ImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Screenshot, image),
Size = fileInfo.Length, Size = fileInfo.Length,
Width = Convert.ToInt32(size.Width), Width = Convert.ToInt32(size.Width),
Height = Convert.ToInt32(size.Height) Height = Convert.ToInt32(size.Height)
@ -480,16 +477,14 @@ namespace MediaBrowser.Api.Images
var fileInfo = new FileInfo(image); var fileInfo = new FileInfo(image);
var dateModified = Kernel.Instance.ImageManager.GetImageDateModified(item, image); var size = _imageProcessor.GetImageSize(image);
var size = Kernel.Instance.ImageManager.GetImageSize(image, dateModified);
list.Add(new ImageInfo list.Add(new ImageInfo
{ {
Path = image, Path = image,
ImageIndex = index, ImageIndex = index,
ImageType = ImageType.Chapter, ImageType = ImageType.Chapter,
ImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Chapter, image), ImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Chapter, image),
Size = fileInfo.Length, Size = fileInfo.Length,
Width = Convert.ToInt32(size.Width), Width = Convert.ToInt32(size.Width),
Height = Convert.ToInt32(size.Height) Height = Convert.ToInt32(size.Height)
@ -721,11 +716,7 @@ namespace MediaBrowser.Api.Images
/// </exception> /// </exception>
private object GetImage(ImageRequest request, BaseItem item) private object GetImage(ImageRequest request, BaseItem item)
{ {
var kernel = Kernel.Instance; var imagePath = GetImagePath(request, item);
var index = request.Index ?? 0;
var imagePath = GetImagePath(kernel, request, item);
if (string.IsNullOrEmpty(imagePath)) if (string.IsNullOrEmpty(imagePath))
{ {
@ -733,9 +724,9 @@ namespace MediaBrowser.Api.Images
} }
// See if we can avoid a file system lookup by looking for the file in ResolveArgs // See if we can avoid a file system lookup by looking for the file in ResolveArgs
var originalFileImageDateModified = kernel.ImageManager.GetImageDateModified(item, imagePath); var originalFileImageDateModified = item.GetImageDateModified(imagePath);
var supportedImageEnhancers = request.EnableImageEnhancers ? kernel.ImageManager.ImageEnhancers.Where(i => var supportedImageEnhancers = request.EnableImageEnhancers ? _imageProcessor.ImageEnhancers.Where(i =>
{ {
try try
{ {
@ -759,7 +750,7 @@ namespace MediaBrowser.Api.Images
var contentType = MimeTypes.GetMimeType(imagePath); var contentType = MimeTypes.GetMimeType(imagePath);
var cacheGuid = kernel.ImageManager.GetImageCacheTag(imagePath, originalFileImageDateModified, supportedImageEnhancers, item, request.Type); var cacheGuid = _imageProcessor.GetImageCacheTag(item, request.Type, imagePath, originalFileImageDateModified, supportedImageEnhancers);
TimeSpan? cacheDuration = null; TimeSpan? cacheDuration = null;
@ -778,7 +769,8 @@ namespace MediaBrowser.Api.Images
Request = currentRequest, Request = currentRequest,
OriginalImageDateModified = originalFileImageDateModified, OriginalImageDateModified = originalFileImageDateModified,
Enhancers = supportedImageEnhancers, Enhancers = supportedImageEnhancers,
OriginalImagePath = imagePath OriginalImagePath = imagePath,
ImageProcessor = _imageProcessor
}, contentType); }, contentType);
} }
@ -786,15 +778,14 @@ namespace MediaBrowser.Api.Images
/// <summary> /// <summary>
/// Gets the image path. /// Gets the image path.
/// </summary> /// </summary>
/// <param name="kernel">The kernel.</param>
/// <param name="request">The request.</param> /// <param name="request">The request.</param>
/// <param name="item">The item.</param> /// <param name="item">The item.</param>
/// <returns>System.String.</returns> /// <returns>System.String.</returns>
private string GetImagePath(Kernel kernel, ImageRequest request, BaseItem item) private string GetImagePath(ImageRequest request, BaseItem item)
{ {
var index = request.Index ?? 0; var index = request.Index ?? 0;
return kernel.ImageManager.GetImagePath(item, request.Type, index); return item.GetImagePath(request.Type, index);
} }
/// <summary> /// <summary>

@ -1,4 +1,4 @@
using MediaBrowser.Controller; using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
@ -35,6 +35,8 @@ namespace MediaBrowser.Api.Images
public string OriginalImagePath; public string OriginalImagePath;
public IImageProcessor ImageProcessor { get; set; }
/// <summary> /// <summary>
/// The _options /// The _options
/// </summary> /// </summary>
@ -73,7 +75,7 @@ namespace MediaBrowser.Api.Images
cropwhitespace = Request.CropWhitespace.Value; cropwhitespace = Request.CropWhitespace.Value;
} }
return Kernel.Instance.ImageManager.ProcessImage(Item, Request.Type, Request.Index ?? 0, OriginalImagePath, cropwhitespace, return ImageProcessor.ProcessImage(Item, Request.Type, Request.Index ?? 0, OriginalImagePath, cropwhitespace,
OriginalImageDateModified, responseStream, Request.Width, Request.Height, Request.MaxWidth, OriginalImageDateModified, responseStream, Request.Width, Request.Height, Request.MaxWidth,
Request.MaxHeight, Request.Quality, Enhancers); Request.MaxHeight, Request.Quality, Enhancers);
} }

@ -1,5 +1,6 @@
using MediaBrowser.Common.MediaInfo; using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Persistence;
@ -41,16 +42,8 @@ namespace MediaBrowser.Api.Playback.Progressive
/// </summary> /// </summary>
public class AudioService : BaseProgressiveStreamingService public class AudioService : BaseProgressiveStreamingService
{ {
/// <summary> public AudioService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IDtoService dtoService, IImageProcessor imageProcessor)
/// Initializes a new instance of the <see cref="AudioService"/> class. : base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, itemRepo, dtoService, imageProcessor)
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="isoManager">The iso manager.</param>
/// <param name="mediaEncoder">The media encoder.</param>
public AudioService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IDtoService dtoService)
: base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, itemRepo, dtoService)
{ {
} }

@ -2,6 +2,7 @@
using MediaBrowser.Common.MediaInfo; using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
@ -24,11 +25,13 @@ namespace MediaBrowser.Api.Playback.Progressive
public abstract class BaseProgressiveStreamingService : BaseStreamingService public abstract class BaseProgressiveStreamingService : BaseStreamingService
{ {
protected readonly IItemRepository ItemRepository; protected readonly IItemRepository ItemRepository;
protected readonly IImageProcessor ImageProcessor;
protected BaseProgressiveStreamingService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepository, IDtoService dtoService) : protected BaseProgressiveStreamingService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepository, IDtoService dtoService, IImageProcessor imageProcessor) :
base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, dtoService) base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, dtoService)
{ {
ItemRepository = itemRepository; ItemRepository = itemRepository;
ImageProcessor = imageProcessor;
} }
/// <summary> /// <summary>
@ -303,7 +306,7 @@ namespace MediaBrowser.Api.Playback.Progressive
} }
} }
return new ImageService(UserManager, LibraryManager, ApplicationPaths, null, ItemRepository, DtoService) return new ImageService(UserManager, LibraryManager, ApplicationPaths, null, ItemRepository, DtoService, ImageProcessor)
{ {
Logger = Logger, Logger = Logger,
RequestContext = RequestContext, RequestContext = RequestContext,

@ -1,5 +1,6 @@
using MediaBrowser.Common.MediaInfo; using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
@ -53,16 +54,8 @@ namespace MediaBrowser.Api.Playback.Progressive
/// </summary> /// </summary>
public class VideoService : BaseProgressiveStreamingService public class VideoService : BaseProgressiveStreamingService
{ {
/// <summary> public VideoService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IDtoService dtoService, IImageProcessor imageProcessor)
/// Initializes a new instance of the <see cref="VideoService"/> class. : base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, itemRepo, dtoService, imageProcessor)
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="userManager">The user manager.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="isoManager">The iso manager.</param>
/// <param name="mediaEncoder">The media encoder.</param>
public VideoService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IItemRepository itemRepo, IDtoService dtoService)
: base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, itemRepo, dtoService)
{ {
} }

@ -1,4 +1,5 @@
using MediaBrowser.Controller; using MediaBrowser.Controller;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
@ -66,6 +67,7 @@ namespace MediaBrowser.Api
private readonly ILibrarySearchEngine _searchEngine; private readonly ILibrarySearchEngine _searchEngine;
private readonly ILibraryManager _libraryManager; private readonly ILibraryManager _libraryManager;
private readonly IDtoService _dtoService; private readonly IDtoService _dtoService;
private readonly IImageProcessor _imageProcessor;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SearchService" /> class. /// Initializes a new instance of the <see cref="SearchService" /> class.
@ -73,12 +75,13 @@ namespace MediaBrowser.Api
/// <param name="userManager">The user manager.</param> /// <param name="userManager">The user manager.</param>
/// <param name="searchEngine">The search engine.</param> /// <param name="searchEngine">The search engine.</param>
/// <param name="libraryManager">The library manager.</param> /// <param name="libraryManager">The library manager.</param>
public SearchService(IUserManager userManager, ILibrarySearchEngine searchEngine, ILibraryManager libraryManager, IDtoService dtoService) public SearchService(IUserManager userManager, ILibrarySearchEngine searchEngine, ILibraryManager libraryManager, IDtoService dtoService, IImageProcessor imageProcessor)
{ {
_userManager = userManager; _userManager = userManager;
_searchEngine = searchEngine; _searchEngine = searchEngine;
_libraryManager = libraryManager; _libraryManager = libraryManager;
_dtoService = dtoService; _dtoService = dtoService;
_imageProcessor = imageProcessor;
} }
/// <summary> /// <summary>
@ -161,7 +164,7 @@ namespace MediaBrowser.Api
if (item.HasImage(ImageType.Primary)) if (item.HasImage(ImageType.Primary))
{ {
result.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Primary, item.GetImage(ImageType.Primary)); result.PrimaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary, item.GetImage(ImageType.Primary));
} }
var episode = item as Episode; var episode = item as Episode;

@ -0,0 +1,94 @@
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace MediaBrowser.Controller.Drawing
{
/// <summary>
/// Interface IImageProcessor
/// </summary>
public interface IImageProcessor
{
/// <summary>
/// Gets the image enhancers.
/// </summary>
/// <value>The image enhancers.</value>
IEnumerable<IImageEnhancer> ImageEnhancers { get; }
/// <summary>
/// Gets the size of the image.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>ImageSize.</returns>
ImageSize GetImageSize(string path);
/// <summary>
/// Gets the size of the image.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="imageDateModified">The image date modified.</param>
/// <returns>ImageSize.</returns>
ImageSize GetImageSize(string path, DateTime imageDateModified);
/// <summary>
/// Adds the parts.
/// </summary>
/// <param name="enhancers">The enhancers.</param>
void AddParts(IEnumerable<IImageEnhancer> enhancers);
/// <summary>
/// Gets the supported enhancers.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param>
/// <returns>IEnumerable{IImageEnhancer}.</returns>
IEnumerable<IImageEnhancer> GetSupportedEnhancers(BaseItem item, ImageType imageType);
/// <summary>
/// Gets the image cache tag.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param>
/// <param name="imagePath">The image path.</param>
/// <returns>Guid.</returns>
Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath);
/// <summary>
/// Gets the image cache tag.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param>
/// <param name="originalImagePath">The original image path.</param>
/// <param name="dateModified">The date modified.</param>
/// <param name="imageEnhancers">The image enhancers.</param>
/// <returns>Guid.</returns>
Guid GetImageCacheTag(BaseItem item, ImageType imageType, string originalImagePath, DateTime dateModified,
IEnumerable<IImageEnhancer> imageEnhancers);
/// <summary>
/// Processes the image.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="imageType">Type of the image.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <param name="originalImagePath">The original image path.</param>
/// <param name="cropWhitespace">if set to <c>true</c> [crop whitespace].</param>
/// <param name="dateModified">The date modified.</param>
/// <param name="toStream">To stream.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="maxWidth">Width of the max.</param>
/// <param name="maxHeight">Height of the max.</param>
/// <param name="quality">The quality.</param>
/// <param name="enhancers">The enhancers.</param>
/// <returns>Task.</returns>
Task ProcessImage(BaseItem entity, ImageType imageType, int imageIndex, string originalImagePath, bool cropWhitespace,
DateTime dateModified, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight,
int? quality, List<IImageEnhancer> enhancers);
}
}

@ -1,5 +1,6 @@
using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.IO; using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Localization; using MediaBrowser.Controller.Localization;
@ -936,7 +937,7 @@ namespace MediaBrowser.Controller.Entities
var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds); var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders)); var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
var results = await Task.WhenAll(tasks).ConfigureAwait(false); var results = await Task.WhenAll(tasks).ConfigureAwait(false);
@ -952,7 +953,7 @@ namespace MediaBrowser.Controller.Entities
var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds); var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders)); var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
var results = await Task.WhenAll(tasks).ConfigureAwait(false); var results = await Task.WhenAll(tasks).ConfigureAwait(false);
@ -971,7 +972,7 @@ namespace MediaBrowser.Controller.Entities
var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds); var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders)); var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
var results = await Task.WhenAll(tasks).ConfigureAwait(false); var results = await Task.WhenAll(tasks).ConfigureAwait(false);
@ -1562,5 +1563,64 @@ namespace MediaBrowser.Controller.Entities
ScreenshotImagePaths.Remove(path); ScreenshotImagePaths.Remove(path);
} }
} }
/// <summary>
/// Gets the image path.
/// </summary>
/// <param name="imageType">Type of the image.</param>
/// <param name="imageIndex">Index of the image.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.InvalidOperationException">
/// </exception>
/// <exception cref="System.ArgumentNullException">item</exception>
public string GetImagePath(ImageType imageType, int imageIndex)
{
if (imageType == ImageType.Backdrop)
{
return BackdropImagePaths[imageIndex];
}
if (imageType == ImageType.Screenshot)
{
return ScreenshotImagePaths[imageIndex];
}
if (imageType == ImageType.Chapter)
{
return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
}
return GetImage(imageType);
}
/// <summary>
/// Gets the image date modified.
/// </summary>
/// <param name="imagePath">The image path.</param>
/// <returns>DateTime.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public DateTime GetImageDateModified(string imagePath)
{
if (string.IsNullOrEmpty(imagePath))
{
throw new ArgumentNullException("imagePath");
}
var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
// If we didn't the metafile entry, check the Season
if (metaFileEntry == null)
{
var episode = this as Episode;
if (episode != null && episode.Season != null)
{
episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
}
}
// See if we can avoid a file system lookup by looking for the file in ResolveArgs
return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.LastWriteTimeUtc;
}
} }
} }

@ -62,7 +62,7 @@ namespace MediaBrowser.Controller.Entities.Movies
var itemsChanged = !SpecialFeatureIds.SequenceEqual(newItemIds); var itemsChanged = !SpecialFeatureIds.SequenceEqual(newItemIds);
var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders)); var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
var results = await Task.WhenAll(tasks).ConfigureAwait(false); var results = await Task.WhenAll(tasks).ConfigureAwait(false);

@ -1,5 +1,4 @@
using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.MediaInfo;
using MediaBrowser.Controller.MediaInfo;
namespace MediaBrowser.Controller namespace MediaBrowser.Controller
{ {
@ -14,12 +13,6 @@ namespace MediaBrowser.Controller
/// <value>The instance.</value> /// <value>The instance.</value>
public static Kernel Instance { get; private set; } public static Kernel Instance { get; private set; }
/// <summary>
/// Gets the image manager.
/// </summary>
/// <value>The image manager.</value>
public ImageManager ImageManager { get; set; }
/// <summary> /// <summary>
/// Gets the FFMPEG controller. /// Gets the FFMPEG controller.
/// </summary> /// </summary>

@ -71,6 +71,7 @@
<Compile Include="..\SharedVersion.cs"> <Compile Include="..\SharedVersion.cs">
<Link>Properties\SharedVersion.cs</Link> <Link>Properties\SharedVersion.cs</Link>
</Compile> </Compile>
<Compile Include="Drawing\IImageProcessor.cs" />
<Compile Include="Dto\IDtoService.cs" /> <Compile Include="Dto\IDtoService.cs" />
<Compile Include="Entities\AdultVideo.cs" /> <Compile Include="Entities\AdultVideo.cs" />
<Compile Include="Entities\Audio\IHasAlbumArtist.cs" /> <Compile Include="Entities\Audio\IHasAlbumArtist.cs" />
@ -95,8 +96,6 @@
<Compile Include="Providers\IDynamicInfoProvider.cs" /> <Compile Include="Providers\IDynamicInfoProvider.cs" />
<Compile Include="Session\ISessionManager.cs" /> <Compile Include="Session\ISessionManager.cs" />
<Compile Include="Drawing\ImageExtensions.cs" /> <Compile Include="Drawing\ImageExtensions.cs" />
<Compile Include="Drawing\ImageHeader.cs" />
<Compile Include="Drawing\ImageManager.cs" />
<Compile Include="Entities\AggregateFolder.cs" /> <Compile Include="Entities\AggregateFolder.cs" />
<Compile Include="Entities\Audio\Artist.cs" /> <Compile Include="Entities\Audio\Artist.cs" />
<Compile Include="Entities\Audio\Audio.cs" /> <Compile Include="Entities\Audio\Audio.cs" />

@ -5,7 +5,7 @@ using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
namespace MediaBrowser.Controller.Drawing namespace MediaBrowser.Server.Implementations.Drawing
{ {
/// <summary> /// <summary>
/// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349 /// Taken from http://stackoverflow.com/questions/111345/getting-image-dimensions-without-reading-the-entire-file/111349

@ -1,108 +1,79 @@
using MediaBrowser.Common.Extensions; using System.Collections.Generic;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Drawing.Imaging; using System.Drawing.Imaging;
using System.Globalization; using System.Globalization;
using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Drawing;
using System;
using System.Collections.Concurrent;
using System.IO;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
namespace MediaBrowser.Controller.Drawing namespace MediaBrowser.Server.Implementations.Drawing
{ {
/// <summary> /// <summary>
/// Class ImageManager /// Class ImageProcessor
/// </summary> /// </summary>
public class ImageManager public class ImageProcessor : IImageProcessor
{ {
/// <summary> /// <summary>
/// Gets the list of currently registered image processors /// The us culture
/// Image processors are specialized metadata providers that run after the normal ones
/// </summary>
/// <value>The image enhancers.</value>
public IEnumerable<IImageEnhancer> ImageEnhancers { get; set; }
/// <summary>
/// Gets the image size cache.
/// </summary> /// </summary>
/// <value>The image size cache.</value> protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
private FileSystemRepository ImageSizeCache { get; set; }
/// <summary>
/// Gets or sets the resized image cache.
/// </summary>
/// <value>The resized image cache.</value>
private FileSystemRepository ResizedImageCache { get; set; }
/// <summary>
/// Gets the cropped image cache.
/// </summary>
/// <value>The cropped image cache.</value>
private FileSystemRepository CroppedImageCache { get; set; }
/// <summary> /// <summary>
/// Gets the cropped image cache. /// The _cached imaged sizes
/// </summary> /// </summary>
/// <value>The cropped image cache.</value> private readonly ConcurrentDictionary<string, ImageSize> _cachedImagedSizes = new ConcurrentDictionary<string, ImageSize>();
private FileSystemRepository EnhancedImageCache { get; set; }
/// <summary> /// <summary>
/// The cached imaged sizes /// Gets the list of currently registered image processors
/// Image processors are specialized metadata providers that run after the normal ones
/// </summary> /// </summary>
private readonly ConcurrentDictionary<string, ImageSize> _cachedImagedSizes = new ConcurrentDictionary<string, ImageSize>(); /// <value>The image enhancers.</value>
public IEnumerable<IImageEnhancer> ImageEnhancers { get; private set; }
/// <summary> /// <summary>
/// The _logger /// The _logger
/// </summary> /// </summary>
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IItemRepository _itemRepo;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ImageManager" /> class. /// The _app paths
/// </summary> /// </summary>
/// <param name="logger">The logger.</param> private readonly IServerApplicationPaths _appPaths;
/// <param name="appPaths">The app paths.</param>
/// <param name="itemRepo">The item repo.</param> private readonly string _imageSizeCachePath;
public ImageManager(ILogger logger, IServerApplicationPaths appPaths, IItemRepository itemRepo) private readonly string _croppedWhitespaceImageCachePath;
private readonly string _enhancedImageCachePath;
private readonly string _resizedImageCachePath;
public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths)
{ {
_logger = logger; _logger = logger;
_itemRepo = itemRepo; _appPaths = appPaths;
ImageSizeCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "image-sizes")); _imageSizeCachePath = Path.Combine(_appPaths.ImageCachePath, "image-sizes");
ResizedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "resized-images")); _croppedWhitespaceImageCachePath = Path.Combine(_appPaths.ImageCachePath, "cropped-images");
CroppedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "cropped-images")); _enhancedImageCachePath = Path.Combine(_appPaths.ImageCachePath, "enhanced-images");
EnhancedImageCache = new FileSystemRepository(Path.Combine(appPaths.ImageCachePath, "enhanced-images")); _resizedImageCachePath = Path.Combine(_appPaths.ImageCachePath, "resized-images");
}
public void AddParts(IEnumerable<IImageEnhancer> enhancers)
{
ImageEnhancers = enhancers.ToArray();
} }
/// <summary>
/// Processes an image by resizing to target dimensions
/// </summary>
/// <param name="entity">The entity that owns the image</param>
/// <param name="imageType">The image type</param>
/// <param name="imageIndex">The image index (currently only used with backdrops)</param>
/// <param name="originalImagePath">The original image path.</param>
/// <param name="cropWhitespace">if set to <c>true</c> [crop whitespace].</param>
/// <param name="dateModified">The last date modified of the original image file</param>
/// <param name="toStream">The stream to save the new image to</param>
/// <param name="width">Use if a fixed width is required. Aspect ratio will be preserved.</param>
/// <param name="height">Use if a fixed height is required. Aspect ratio will be preserved.</param>
/// <param name="maxWidth">Use if a max width is required. Aspect ratio will be preserved.</param>
/// <param name="maxHeight">Use if a max height is required. Aspect ratio will be preserved.</param>
/// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
/// <param name="enhancers">The enhancers.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">entity</exception>
public async Task ProcessImage(BaseItem entity, ImageType imageType, int imageIndex, string originalImagePath, bool cropWhitespace, DateTime dateModified, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality, List<IImageEnhancer> enhancers) public async Task ProcessImage(BaseItem entity, ImageType imageType, int imageIndex, string originalImagePath, bool cropWhitespace, DateTime dateModified, Stream toStream, int? width, int? height, int? maxWidth, int? maxHeight, int? quality, List<IImageEnhancer> enhancers)
{ {
if (entity == null) if (entity == null)
@ -117,7 +88,7 @@ namespace MediaBrowser.Controller.Drawing
if (cropWhitespace) if (cropWhitespace)
{ {
originalImagePath = await GetCroppedImage(originalImagePath, dateModified).ConfigureAwait(false); originalImagePath = await GetWhitespaceCroppedImage(originalImagePath, dateModified).ConfigureAwait(false);
} }
// No enhancement - don't cache // No enhancement - don't cache
@ -246,6 +217,76 @@ namespace MediaBrowser.Controller.Drawing
} }
} }
/// <summary>
/// Crops whitespace from an image, caches the result, and returns the cached path
/// </summary>
/// <param name="originalImagePath">The original image path.</param>
/// <param name="dateModified">The date modified.</param>
/// <returns>System.String.</returns>
private async Task<string> GetWhitespaceCroppedImage(string originalImagePath, DateTime dateModified)
{
var name = originalImagePath;
name += "datemodified=" + dateModified.Ticks;
var croppedImagePath = GetCachePath(_croppedWhitespaceImageCachePath, name, Path.GetExtension(originalImagePath));
var semaphore = GetLock(croppedImagePath);
await semaphore.WaitAsync().ConfigureAwait(false);
// Check again in case of contention
if (File.Exists(croppedImagePath))
{
semaphore.Release();
return croppedImagePath;
}
try
{
using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
{
// Copy to memory stream to avoid Image locking file
using (var memoryStream = new MemoryStream())
{
await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
{
var outputFormat = originalImage.RawFormat;
using (var croppedImage = originalImage.CropWhitespace())
{
var parentPath = Path.GetDirectoryName(croppedImagePath);
if (!Directory.Exists(parentPath))
{
Directory.CreateDirectory(parentPath);
}
using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
croppedImage.Save(outputFormat, outputStream, 100);
}
}
}
}
}
}
catch (Exception ex)
{
// We have to have a catch-all here because some of the .net image methods throw a plain old Exception
_logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
return originalImagePath;
}
finally
{
semaphore.Release();
}
return croppedImagePath;
}
/// <summary> /// <summary>
/// Caches the resized image. /// Caches the resized image.
/// </summary> /// </summary>
@ -288,31 +329,40 @@ namespace MediaBrowser.Controller.Drawing
filename += "datemodified=" + dateModified.Ticks; filename += "datemodified=" + dateModified.Ticks;
return ResizedImageCache.GetResourcePath(filename, Path.GetExtension(originalPath)); return GetCachePath(_resizedImageCachePath, filename, Path.GetExtension(originalPath));
} }
/// <summary>
/// Gets the size of the image.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>ImageSize.</returns>
public ImageSize GetImageSize(string path)
{
return GetImageSize(path, File.GetLastWriteTimeUtc(path));
}
/// <summary> /// <summary>
/// Gets image dimensions /// Gets the size of the image.
/// </summary> /// </summary>
/// <param name="imagePath">The image path.</param> /// <param name="path">The path.</param>
/// <param name="dateModified">The date modified.</param> /// <param name="imageDateModified">The image date modified.</param>
/// <returns>Task{ImageSize}.</returns> /// <returns>ImageSize.</returns>
/// <exception cref="System.ArgumentNullException">imagePath</exception> /// <exception cref="System.ArgumentNullException">path</exception>
public ImageSize GetImageSize(string imagePath, DateTime dateModified) public ImageSize GetImageSize(string path, DateTime imageDateModified)
{ {
if (string.IsNullOrEmpty(imagePath)) if (string.IsNullOrEmpty(path))
{ {
throw new ArgumentNullException("imagePath"); throw new ArgumentNullException("path");
} }
var name = imagePath + "datemodified=" + dateModified.Ticks; var name = path + "datemodified=" + imageDateModified.Ticks;
ImageSize size; ImageSize size;
if (!_cachedImagedSizes.TryGetValue(name, out size)) if (!_cachedImagedSizes.TryGetValue(name, out size))
{ {
size = GetImageSize(name, imagePath); size = GetImageSizeInternal(name, path);
_cachedImagedSizes.AddOrUpdate(name, size, (keyName, oldValue) => size); _cachedImagedSizes.AddOrUpdate(name, size, (keyName, oldValue) => size);
} }
@ -320,18 +370,16 @@ namespace MediaBrowser.Controller.Drawing
return size; return size;
} }
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary> /// <summary>
/// Gets the size of the image. /// Gets the image size internal.
/// </summary> /// </summary>
/// <param name="keyName">Name of the key.</param> /// <param name="cacheKey">The cache key.</param>
/// <param name="imagePath">The image path.</param> /// <param name="path">The path.</param>
/// <returns>ImageSize.</returns> /// <returns>ImageSize.</returns>
private ImageSize GetImageSize(string keyName, string imagePath) private ImageSize GetImageSizeInternal(string cacheKey, string path)
{ {
// Now check the file system cache // Now check the file system cache
var fullCachePath = ImageSizeCache.GetResourcePath(keyName, ".txt"); var fullCachePath = GetCachePath(_imageSizeCachePath, cacheKey, ".txt");
try try
{ {
@ -366,7 +414,7 @@ namespace MediaBrowser.Controller.Drawing
// Cache file doesn't exist no biggie // Cache file doesn't exist no biggie
} }
var size = ImageHeader.GetDimensions(imagePath, _logger); var size = ImageHeader.GetDimensions(path, _logger);
var parentPath = Path.GetDirectoryName(fullCachePath); var parentPath = Path.GetDirectoryName(fullCachePath);
@ -383,173 +431,64 @@ namespace MediaBrowser.Controller.Drawing
} }
/// <summary> /// <summary>
/// Gets the image path. /// Gets the image cache tag.
/// </summary> /// </summary>
/// <param name="item">The item.</param> /// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param> /// <param name="imageType">Type of the image.</param>
/// <param name="imageIndex">Index of the image.</param> /// <param name="imagePath">The image path.</param>
/// <returns>System.String.</returns> /// <returns>Guid.</returns>
/// <exception cref="System.ArgumentNullException">item</exception> /// <exception cref="System.ArgumentNullException">item</exception>
/// <exception cref="System.InvalidOperationException"></exception> public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
public string GetImagePath(BaseItem item, ImageType imageType, int imageIndex)
{ {
if (item == null) if (item == null)
{ {
throw new ArgumentNullException("item"); throw new ArgumentNullException("item");
} }
if (imageType == ImageType.Backdrop) if (string.IsNullOrEmpty(imagePath))
{
if (item.BackdropImagePaths == null)
{
throw new InvalidOperationException(string.Format("Item {0} does not have any Backdrops.", item.Name));
}
return item.BackdropImagePaths[imageIndex];
}
if (imageType == ImageType.Screenshot)
{
if (item.ScreenshotImagePaths == null)
{ {
throw new InvalidOperationException(string.Format("Item {0} does not have any Screenshots.", item.Name)); throw new ArgumentNullException("imagePath");
} }
return item.ScreenshotImagePaths[imageIndex]; var dateModified = item.GetImageDateModified(imagePath);
}
if (imageType == ImageType.Chapter) var supportedEnhancers = GetSupportedEnhancers(item, imageType).ToList();
{
return _itemRepo.GetChapter(item.Id, imageIndex).ImagePath;
}
return item.GetImage(imageType); return GetImageCacheTag(item, imageType, imagePath, dateModified, supportedEnhancers);
} }
/// <summary> /// <summary>
/// Gets the image date modified. /// Gets the image cache tag.
/// </summary> /// </summary>
/// <param name="item">The item.</param> /// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param> /// <param name="imageType">Type of the image.</param>
/// <param name="imageIndex">Index of the image.</param> /// <param name="originalImagePath">The original image path.</param>
/// <returns>DateTime.</returns> /// <param name="dateModified">The date modified of the original image file.</param>
/// <exception cref="System.ArgumentNullException">item</exception> /// <param name="imageEnhancers">The image enhancers.</param>
public DateTime GetImageDateModified(BaseItem item, ImageType imageType, int imageIndex) /// <returns>Guid.</returns>
{
if (item == null)
{
throw new ArgumentNullException("item");
}
var imagePath = GetImagePath(item, imageType, imageIndex);
return GetImageDateModified(item, imagePath);
}
/// <summary>
/// Gets the image date modified.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imagePath">The image path.</param>
/// <returns>DateTime.</returns>
/// <exception cref="System.ArgumentNullException">item</exception> /// <exception cref="System.ArgumentNullException">item</exception>
public DateTime GetImageDateModified(BaseItem item, string imagePath) public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers)
{ {
if (item == null) if (item == null)
{ {
throw new ArgumentNullException("item"); throw new ArgumentNullException("item");
} }
if (string.IsNullOrEmpty(imagePath)) if (imageEnhancers == null)
{
throw new ArgumentNullException("imagePath");
}
var metaFileEntry = item.ResolveArgs.GetMetaFileByPath(imagePath);
// If we didn't the metafile entry, check the Season
if (metaFileEntry == null)
{
var episode = item as Episode;
if (episode != null && episode.Season != null)
{
episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
}
}
// See if we can avoid a file system lookup by looking for the file in ResolveArgs
return metaFileEntry == null ? File.GetLastWriteTimeUtc(imagePath) : metaFileEntry.LastWriteTimeUtc;
}
/// <summary>
/// Crops whitespace from an image, caches the result, and returns the cached path
/// </summary>
/// <param name="originalImagePath">The original image path.</param>
/// <param name="dateModified">The date modified.</param>
/// <returns>System.String.</returns>
private async Task<string> GetCroppedImage(string originalImagePath, DateTime dateModified)
{
var name = originalImagePath;
name += "datemodified=" + dateModified.Ticks;
var croppedImagePath = CroppedImageCache.GetResourcePath(name, Path.GetExtension(originalImagePath));
var semaphore = GetLock(croppedImagePath);
await semaphore.WaitAsync().ConfigureAwait(false);
// Check again in case of contention
if (File.Exists(croppedImagePath))
{
semaphore.Release();
return croppedImagePath;
}
try
{
using (var fileStream = new FileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
{
// Copy to memory stream to avoid Image locking file
using (var memoryStream = new MemoryStream())
{
await fileStream.CopyToAsync(memoryStream).ConfigureAwait(false);
using (var originalImage = (Bitmap)Image.FromStream(memoryStream, true, false))
{
var outputFormat = originalImage.RawFormat;
using (var croppedImage = originalImage.CropWhitespace())
{
var parentPath = Path.GetDirectoryName(croppedImagePath);
if (!Directory.Exists(parentPath))
{ {
Directory.CreateDirectory(parentPath); throw new ArgumentNullException("imageEnhancers");
} }
using (var outputStream = new FileStream(croppedImagePath, FileMode.Create, FileAccess.Write, FileShare.Read)) if (string.IsNullOrEmpty(originalImagePath))
{ {
croppedImage.Save(outputFormat, outputStream, 100); throw new ArgumentNullException("originalImagePath");
}
}
}
}
}
} }
catch (Exception ex)
{
// We have to have a catch-all here because some of the .net image methods throw a plain old Exception
_logger.ErrorException("Error cropping image {0}", ex, originalImagePath);
return originalImagePath; // Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
} var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
finally cacheKeys.Add(originalImagePath + dateModified.Ticks);
{
semaphore.Release();
}
return croppedImagePath; return string.Join("|", cacheKeys.ToArray()).GetMD5();
} }
/// <summary> /// <summary>
@ -610,10 +549,10 @@ namespace MediaBrowser.Controller.Drawing
throw new ArgumentNullException("item"); throw new ArgumentNullException("item");
} }
var cacheGuid = GetImageCacheTag(originalImagePath, dateModified, supportedEnhancers, item, imageType); var cacheGuid = GetImageCacheTag(item, imageType, originalImagePath, dateModified, supportedEnhancers);
// All enhanced images are saved as png to allow transparency // All enhanced images are saved as png to allow transparency
var enhancedImagePath = EnhancedImageCache.GetResourcePath(cacheGuid + ".png"); var enhancedImagePath = GetCachePath(_enhancedImageCachePath, cacheGuid + ".png");
var semaphore = GetLock(enhancedImagePath); var semaphore = GetLock(enhancedImagePath);
@ -665,80 +604,6 @@ namespace MediaBrowser.Controller.Drawing
return enhancedImagePath; return enhancedImagePath;
} }
/// <summary>
/// Gets the image cache tag.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param>
/// <param name="imagePath">The image path.</param>
/// <returns>Guid.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public Guid GetImageCacheTag(BaseItem item, ImageType imageType, string imagePath)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (string.IsNullOrEmpty(imagePath))
{
throw new ArgumentNullException("imagePath");
}
var dateModified = GetImageDateModified(item, imagePath);
var supportedEnhancers = ImageEnhancers.Where(i =>
{
try
{
return i.Supports(item, imageType);
}
catch (Exception ex)
{
_logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
return false;
}
}).ToList();
return GetImageCacheTag(imagePath, dateModified, supportedEnhancers, item, imageType);
}
/// <summary>
/// Gets the image cache tag.
/// </summary>
/// <param name="originalImagePath">The original image path.</param>
/// <param name="dateModified">The date modified of the original image file.</param>
/// <param name="imageEnhancers">The image enhancers.</param>
/// <param name="item">The item.</param>
/// <param name="imageType">Type of the image.</param>
/// <returns>Guid.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public Guid GetImageCacheTag(string originalImagePath, DateTime dateModified, IEnumerable<IImageEnhancer> imageEnhancers, BaseItem item, ImageType imageType)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (imageEnhancers == null)
{
throw new ArgumentNullException("imageEnhancers");
}
if (string.IsNullOrEmpty(originalImagePath))
{
throw new ArgumentNullException("originalImagePath");
}
// Cache name is created with supported enhancers combined with the last config change so we pick up new config changes
var cacheKeys = imageEnhancers.Select(i => i.GetConfigurationCacheKey(item, imageType)).ToList();
cacheKeys.Add(originalImagePath + dateModified.Ticks);
return string.Join("|", cacheKeys.ToArray()).GetMD5();
}
/// <summary> /// <summary>
/// Executes the image enhancers. /// Executes the image enhancers.
/// </summary> /// </summary>
@ -775,31 +640,113 @@ namespace MediaBrowser.Controller.Drawing
/// <summary> /// <summary>
/// The _semaphoreLocks /// The _semaphoreLocks
/// </summary> /// </summary>
private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>(); private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
/// <summary> /// <summary>
/// Gets the lock. /// Gets the lock.
/// </summary> /// </summary>
/// <param name="filename">The filename.</param> /// <param name="filename">The filename.</param>
/// <returns>System.Object.</returns> /// <returns>System.Object.</returns>
private SemaphoreSlim GetLock(string filename) private object GetObjectLock(string filename)
{ {
return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1)); return _locks.GetOrAdd(filename, key => new object());
} }
/// <summary> /// <summary>
/// The _semaphoreLocks /// The _semaphoreLocks
/// </summary> /// </summary>
private readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>(); private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
/// <summary> /// <summary>
/// Gets the lock. /// Gets the lock.
/// </summary> /// </summary>
/// <param name="filename">The filename.</param> /// <param name="filename">The filename.</param>
/// <returns>System.Object.</returns> /// <returns>System.Object.</returns>
private object GetObjectLock(string filename) private SemaphoreSlim GetLock(string filename)
{ {
return _locks.GetOrAdd(filename, key => new object()); return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
}
/// <summary>
/// Gets the cache path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="uniqueName">Name of the unique.</param>
/// <param name="fileExtension">The file extension.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">
/// path
/// or
/// uniqueName
/// or
/// fileExtension
/// </exception>
public string GetCachePath(string path, string uniqueName, string fileExtension)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrEmpty(uniqueName))
{
throw new ArgumentNullException("uniqueName");
}
if (string.IsNullOrEmpty(fileExtension))
{
throw new ArgumentNullException("fileExtension");
}
var filename = uniqueName.GetMD5() + fileExtension;
return GetCachePath(path, filename);
}
/// <summary>
/// Gets the cache path.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="filename">The filename.</param>
/// <returns>System.String.</returns>
/// <exception cref="System.ArgumentNullException">
/// path
/// or
/// filename
/// </exception>
public string GetCachePath(string path, string filename)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException("filename");
}
var prefix = filename.Substring(0, 1);
path = Path.Combine(path, prefix);
return Path.Combine(path, filename);
}
public IEnumerable<IImageEnhancer> GetSupportedEnhancers(BaseItem item, ImageType imageType)
{
return ImageEnhancers.Where(i =>
{
try
{
return i.Supports(item as BaseItem, imageType);
}
catch (Exception ex)
{
_logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
return false;
}
}).ToList();
} }
} }
} }

@ -1,5 +1,5 @@
using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller; using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
@ -30,13 +30,16 @@ namespace MediaBrowser.Server.Implementations.Dto
private readonly IUserDataRepository _userDataRepository; private readonly IUserDataRepository _userDataRepository;
private readonly IItemRepository _itemRepo; private readonly IItemRepository _itemRepo;
public DtoService(ILogger logger, ILibraryManager libraryManager, IUserManager userManager, IUserDataRepository userDataRepository, IItemRepository itemRepo) private readonly IImageProcessor _imageProcessor;
public DtoService(ILogger logger, ILibraryManager libraryManager, IUserManager userManager, IUserDataRepository userDataRepository, IItemRepository itemRepo, IImageProcessor imageProcessor)
{ {
_logger = logger; _logger = logger;
_libraryManager = libraryManager; _libraryManager = libraryManager;
_userManager = userManager; _userManager = userManager;
_userDataRepository = userDataRepository; _userDataRepository = userDataRepository;
_itemRepo = itemRepo; _itemRepo = itemRepo;
_imageProcessor = imageProcessor;
} }
/// <summary> /// <summary>
@ -209,7 +212,7 @@ namespace MediaBrowser.Server.Implementations.Dto
if (!string.IsNullOrEmpty(image)) if (!string.IsNullOrEmpty(image))
{ {
dto.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(user, ImageType.Primary, image); dto.PrimaryImageTag = _imageProcessor.GetImageCacheTag(user, ImageType.Primary, image);
try try
{ {
@ -288,7 +291,7 @@ namespace MediaBrowser.Server.Implementations.Dto
{ {
try try
{ {
info.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Primary, imagePath); info.PrimaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary, imagePath);
} }
catch (IOException) catch (IOException)
{ {
@ -409,7 +412,7 @@ namespace MediaBrowser.Server.Implementations.Dto
{ {
try try
{ {
return Kernel.Instance.ImageManager.GetImageCacheTag(item, type, path); return _imageProcessor.GetImageCacheTag(item, type, path);
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -1154,7 +1157,7 @@ namespace MediaBrowser.Server.Implementations.Dto
try try
{ {
size = Kernel.Instance.ImageManager.GetImageSize(path, dateModified); size = _imageProcessor.GetImageSize(path, dateModified);
} }
catch (FileNotFoundException) catch (FileNotFoundException)
{ {
@ -1169,21 +1172,7 @@ namespace MediaBrowser.Server.Implementations.Dto
dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height; dto.OriginalPrimaryImageAspectRatio = size.Width / size.Height;
var supportedEnhancers = Kernel.Instance.ImageManager.ImageEnhancers.Where(i => var supportedEnhancers = _imageProcessor.GetSupportedEnhancers(item, ImageType.Primary).ToList();
{
try
{
return i.Supports(item, ImageType.Primary);
}
catch (Exception ex)
{
_logger.ErrorException("Error in image enhancer: {0}", ex, i.GetType().Name);
return false;
}
}).ToList();
foreach (var enhancer in supportedEnhancers) foreach (var enhancer in supportedEnhancers)
{ {
@ -1199,6 +1188,5 @@ namespace MediaBrowser.Server.Implementations.Dto
dto.PrimaryImageAspectRatio = size.Width / size.Height; dto.PrimaryImageAspectRatio = size.Width / size.Height;
} }
} }
} }

@ -91,6 +91,7 @@
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\System.Data.SQLite.x86.1.0.88.0\lib\net45\System.Data.SQLite.Linq.dll</HintPath> <HintPath>..\packages\System.Data.SQLite.x86.1.0.88.0\lib\net45\System.Data.SQLite.Linq.dll</HintPath>
</Reference> </Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Reactive.Core"> <Reference Include="System.Reactive.Core">
<HintPath>..\packages\Rx-Core.2.1.30214.0\lib\Net45\System.Reactive.Core.dll</HintPath> <HintPath>..\packages\Rx-Core.2.1.30214.0\lib\Net45\System.Reactive.Core.dll</HintPath>
</Reference> </Reference>
@ -112,6 +113,7 @@
</Compile> </Compile>
<Compile Include="BdInfo\BdInfoExaminer.cs" /> <Compile Include="BdInfo\BdInfoExaminer.cs" />
<Compile Include="Configuration\ServerConfigurationManager.cs" /> <Compile Include="Configuration\ServerConfigurationManager.cs" />
<Compile Include="Drawing\ImageHeader.cs" />
<Compile Include="Dto\DtoService.cs" /> <Compile Include="Dto\DtoService.cs" />
<Compile Include="EntryPoints\LibraryChangedNotifier.cs" /> <Compile Include="EntryPoints\LibraryChangedNotifier.cs" />
<Compile Include="EntryPoints\LoadRegistrations.cs" /> <Compile Include="EntryPoints\LoadRegistrations.cs" />
@ -128,6 +130,7 @@
<Compile Include="HttpServer\ServerLogger.cs" /> <Compile Include="HttpServer\ServerLogger.cs" />
<Compile Include="HttpServer\StreamWriter.cs" /> <Compile Include="HttpServer\StreamWriter.cs" />
<Compile Include="HttpServer\SwaggerService.cs" /> <Compile Include="HttpServer\SwaggerService.cs" />
<Compile Include="Drawing\ImageProcessor.cs" />
<Compile Include="IO\DirectoryWatchers.cs" /> <Compile Include="IO\DirectoryWatchers.cs" />
<Compile Include="Library\CoreResolutionIgnoreRule.cs" /> <Compile Include="Library\CoreResolutionIgnoreRule.cs" />
<Compile Include="Library\LibraryManager.cs" /> <Compile Include="Library\LibraryManager.cs" />

@ -34,6 +34,7 @@ using MediaBrowser.Providers;
using MediaBrowser.Server.Implementations; using MediaBrowser.Server.Implementations;
using MediaBrowser.Server.Implementations.BdInfo; using MediaBrowser.Server.Implementations.BdInfo;
using MediaBrowser.Server.Implementations.Configuration; using MediaBrowser.Server.Implementations.Configuration;
using MediaBrowser.Server.Implementations.Drawing;
using MediaBrowser.Server.Implementations.Dto; using MediaBrowser.Server.Implementations.Dto;
using MediaBrowser.Server.Implementations.HttpServer; using MediaBrowser.Server.Implementations.HttpServer;
using MediaBrowser.Server.Implementations.IO; using MediaBrowser.Server.Implementations.IO;
@ -160,6 +161,7 @@ namespace MediaBrowser.ServerApplication
/// <value>The HTTP server.</value> /// <value>The HTTP server.</value>
private IHttpServer HttpServer { get; set; } private IHttpServer HttpServer { get; set; }
private IDtoService DtoService { get; set; } private IDtoService DtoService { get; set; }
private IImageProcessor ImageProcessor { get; set; }
/// <summary> /// <summary>
/// Gets or sets the media encoder. /// Gets or sets the media encoder.
@ -295,7 +297,10 @@ namespace MediaBrowser.ServerApplication
LocalizationManager = new LocalizationManager(ServerConfigurationManager); LocalizationManager = new LocalizationManager(ServerConfigurationManager);
RegisterSingleInstance(LocalizationManager); RegisterSingleInstance(LocalizationManager);
DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataRepository, ItemRepository); ImageProcessor = new ImageProcessor(Logger, ServerConfigurationManager.ApplicationPaths);
RegisterSingleInstance(ImageProcessor);
DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataRepository, ItemRepository, ImageProcessor);
RegisterSingleInstance(DtoService); RegisterSingleInstance(DtoService);
var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false)); var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
@ -314,11 +319,8 @@ namespace MediaBrowser.ServerApplication
/// </summary> /// </summary>
private void SetKernelProperties() private void SetKernelProperties()
{ {
ServerKernel.ImageManager = new ImageManager(LogManager.GetLogger("ImageManager"),
ApplicationPaths, ItemRepository);
Parallel.Invoke( Parallel.Invoke(
() => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository), () => ServerKernel.FFMpegManager = new FFMpegManager(ApplicationPaths, MediaEncoder, Logger, ItemRepository),
() => ServerKernel.ImageManager.ImageEnhancers = GetExports<IImageEnhancer>().OrderBy(e => e.Priority).ToArray(),
() => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(), () => LocalizedStrings.StringFiles = GetExports<LocalizedStringData>(),
SetStaticProperties SetStaticProperties
); );
@ -461,6 +463,8 @@ namespace MediaBrowser.ServerApplication
ProviderManager.AddParts(GetExports<BaseMetadataProvider>().ToArray()); ProviderManager.AddParts(GetExports<BaseMetadataProvider>().ToArray());
IsoManager.AddParts(GetExports<IIsoMounter>().ToArray()); IsoManager.AddParts(GetExports<IIsoMounter>().ToArray());
ImageProcessor.AddParts(GetExports<IImageEnhancer>().ToArray());
} }
/// <summary> /// <summary>

Loading…
Cancel
Save