using System.IO;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Controller.Providers.MediaInfo
{
///
/// Uses ffmpeg to create video images
///
public class AudioImageProvider : BaseMetadataProvider
{
///
/// Gets or sets the image cache.
///
/// The image cache.
public FileSystemRepository ImageCache { get; set; }
///
/// The _locks
///
private readonly ConcurrentDictionary _locks = new ConcurrentDictionary();
///
/// The _media encoder
///
private readonly IMediaEncoder _mediaEncoder;
///
/// The _library manager
///
private readonly ILibraryManager _libraryManager;
///
/// Initializes a new instance of the class.
///
/// The log manager.
/// The configuration manager.
/// The library manager.
/// The media encoder.
public AudioImageProvider(ILogManager logManager, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, IMediaEncoder mediaEncoder)
: base(logManager, configurationManager)
{
_libraryManager = libraryManager;
_mediaEncoder = mediaEncoder;
ImageCache = new FileSystemRepository(Kernel.Instance.FFMpegManager.AudioImagesDataPath);
}
///
/// Gets a value indicating whether [refresh on version change].
///
/// true if [refresh on version change]; otherwise, false.
protected override bool RefreshOnVersionChange
{
get
{
return true;
}
}
///
/// Gets the provider version.
///
/// The provider version.
protected override string ProviderVersion
{
get
{
return "1";
}
}
///
/// Supportses the specified item.
///
/// The item.
/// true if XXXX, false otherwise
public override bool Supports(BaseItem item)
{
return item.LocationType == LocationType.FileSystem && item is Audio;
}
///
/// Override this to return the date that should be compared to the last refresh date
/// to determine if this provider should be re-fetched.
///
/// The item.
/// DateTime.
protected override DateTime CompareDate(BaseItem item)
{
return item.DateModified;
}
///
/// Gets the priority.
///
/// The priority.
public override MetadataProviderPriority Priority
{
get { return MetadataProviderPriority.Last; }
}
///
/// Fetches metadata and returns true or false indicating if any work that requires persistence was done
///
/// The item.
/// if set to true [force].
/// The cancellation token.
/// Task{System.Boolean}.
public override async Task FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
{
var audio = (Audio)item;
if (string.IsNullOrEmpty(audio.PrimaryImagePath) && audio.MediaStreams.Any(s => s.Type == MediaStreamType.Video))
{
try
{
await CreateImagesForSong(audio, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.ErrorException("Error extracting image for {0}", ex, item.Name);
}
}
SetLastRefreshed(item, DateTime.UtcNow);
return true;
}
///
/// Creates the images for song.
///
/// The item.
/// The cancellation token.
/// Task.
/// Can't extract an image unless the audio file has an embedded image.
private async Task CreateImagesForSong(Audio item, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var album = item.Parent as MusicAlbum;
var filename = item.Album ?? string.Empty;
filename += item.Artist ?? string.Empty;
filename += album == null ? item.Id.ToString("N") + item.DateModified.Ticks : album.Id.ToString("N") + album.DateModified.Ticks;
var path = ImageCache.GetResourcePath(filename + "_primary", ".jpg");
if (!File.Exists(path))
{
var semaphore = GetLock(path);
// Acquire a lock
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
// Check again
if (!File.Exists(path))
{
try
{
var parentPath = Path.GetDirectoryName(path);
if (!Directory.Exists(parentPath))
{
Directory.CreateDirectory(parentPath);
}
await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.AudioFile, null, path, cancellationToken).ConfigureAwait(false);
}
finally
{
semaphore.Release();
}
}
else
{
semaphore.Release();
}
}
// Image is already in the cache
item.PrimaryImagePath = path;
await _libraryManager.UpdateItem(item, cancellationToken).ConfigureAwait(false);
}
///
/// Gets the lock.
///
/// The filename.
/// SemaphoreSlim.
private SemaphoreSlim GetLock(string filename)
{
return _locks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
}
}
}