jellyfin-server/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs

598 lines
21 KiB
C#
Raw Normal View History

2015-03-29 16:45:16 +00:00
using MediaBrowser.Common.Extensions;
2015-03-07 22:43:53 +00:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Persistence;
2015-03-07 22:43:53 +00:00
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
2015-03-07 23:39:24 +00:00
using MediaBrowser.Model.Logging;
2015-03-26 04:44:24 +00:00
using MediaBrowser.Model.MediaInfo;
2015-03-29 16:45:16 +00:00
using MediaBrowser.Model.Serialization;
2015-03-03 07:03:17 +00:00
using System;
2015-03-29 16:45:16 +00:00
using System.Collections.Concurrent;
using System.Collections.Generic;
2015-03-26 04:44:24 +00:00
using System.IO;
using System.Linq;
2015-03-07 22:43:53 +00:00
using System.Threading;
using System.Threading.Tasks;
2015-10-04 04:23:11 +00:00
using CommonIO;
2015-09-20 17:56:26 +00:00
using MediaBrowser.Common.IO;
namespace MediaBrowser.Server.Implementations.Library
{
2015-03-28 20:22:27 +00:00
public class MediaSourceManager : IMediaSourceManager, IDisposable
{
private readonly IItemRepository _itemRepo;
2015-03-07 22:43:53 +00:00
private readonly IUserManager _userManager;
private readonly ILibraryManager _libraryManager;
2015-03-29 16:45:16 +00:00
private readonly IJsonSerializer _jsonSerializer;
2015-09-20 17:56:26 +00:00
private readonly IFileSystem _fileSystem;
2015-03-07 22:43:53 +00:00
private IMediaSourceProvider[] _providers;
2015-03-07 23:39:24 +00:00
private readonly ILogger _logger;
private readonly IUserDataManager _userDataManager;
2015-03-07 22:43:53 +00:00
public MediaSourceManager(IItemRepository itemRepo, IUserManager userManager, ILibraryManager libraryManager, ILogger logger, IJsonSerializer jsonSerializer, IFileSystem fileSystem, IUserDataManager userDataManager)
{
_itemRepo = itemRepo;
2015-03-07 22:43:53 +00:00
_userManager = userManager;
_libraryManager = libraryManager;
2015-03-07 23:39:24 +00:00
_logger = logger;
2015-03-29 16:45:16 +00:00
_jsonSerializer = jsonSerializer;
2015-09-20 17:56:26 +00:00
_fileSystem = fileSystem;
_userDataManager = userDataManager;
2015-03-07 22:43:53 +00:00
}
public void AddParts(IEnumerable<IMediaSourceProvider> providers)
{
_providers = providers.ToArray();
}
public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
{
var list = _itemRepo.GetMediaStreams(query)
.ToList();
foreach (var stream in list)
{
stream.SupportsExternalStream = StreamSupportsExternalStream(stream);
}
return list;
}
private bool StreamSupportsExternalStream(MediaStream stream)
{
if (stream.IsExternal)
{
return true;
}
if (stream.IsTextSubtitleStream)
{
2016-01-09 01:51:11 +00:00
if (string.Equals(stream.Codec, "ass", StringComparison.OrdinalIgnoreCase))
{
return false;
}
2015-12-14 13:54:21 +00:00
return true;
}
return false;
}
2015-03-03 07:03:17 +00:00
public IEnumerable<MediaStream> GetMediaStreams(string mediaSourceId)
{
var list = GetMediaStreams(new MediaStreamQuery
{
ItemId = new Guid(mediaSourceId)
});
return GetMediaStreamsForItem(list);
}
public IEnumerable<MediaStream> GetMediaStreams(Guid itemId)
{
var list = GetMediaStreams(new MediaStreamQuery
{
ItemId = itemId
});
return GetMediaStreamsForItem(list);
}
private IEnumerable<MediaStream> GetMediaStreamsForItem(IEnumerable<MediaStream> streams)
{
var list = streams.ToList();
var subtitleStreams = list
.Where(i => i.Type == MediaStreamType.Subtitle)
.ToList();
if (subtitleStreams.Count > 0)
{
foreach (var subStream in subtitleStreams)
{
2015-12-14 13:54:21 +00:00
subStream.SupportsExternalStream = StreamSupportsExternalStream(subStream);
2015-03-03 07:03:17 +00:00
}
}
return list;
}
2015-03-07 22:43:53 +00:00
2015-04-09 05:20:23 +00:00
public async Task<IEnumerable<MediaSourceInfo>> GetPlayackMediaSources(string id, string userId, bool enablePathSubstitution, string[] supportedLiveMediaTypes, CancellationToken cancellationToken)
2015-03-07 22:43:53 +00:00
{
var item = _libraryManager.GetItemById(id);
2015-03-07 23:39:24 +00:00
var hasMediaSources = (IHasMediaSources)item;
2015-03-31 16:24:16 +00:00
User user = null;
2015-03-07 22:43:53 +00:00
2015-04-05 15:01:57 +00:00
if (!string.IsNullOrWhiteSpace(userId))
2015-03-07 22:43:53 +00:00
{
2015-03-31 16:24:16 +00:00
user = _userManager.GetUserById(userId);
2015-03-07 22:43:53 +00:00
}
2015-04-05 15:01:57 +00:00
var mediaSources = GetStaticMediaSources(hasMediaSources, enablePathSubstitution, user);
2015-03-07 23:39:24 +00:00
var dynamicMediaSources = await GetDynamicMediaSources(hasMediaSources, cancellationToken).ConfigureAwait(false);
var list = new List<MediaSourceInfo>();
list.AddRange(mediaSources);
2015-03-08 16:25:46 +00:00
foreach (var source in dynamicMediaSources)
{
2015-03-31 16:24:16 +00:00
if (user != null)
{
SetUserProperties(hasMediaSources, source, user);
2015-03-31 16:24:16 +00:00
}
2015-03-17 03:51:35 +00:00
if (source.Protocol == MediaProtocol.File)
{
2015-03-28 20:22:27 +00:00
// TODO: Path substitution
2015-09-20 17:56:26 +00:00
if (!_fileSystem.FileExists(source.Path))
2015-04-05 15:01:57 +00:00
{
source.SupportsDirectStream = false;
}
2015-03-28 20:22:27 +00:00
}
else if (source.Protocol == MediaProtocol.Http)
{
// TODO: Allow this when the source is plain http, e.g. not HLS or Mpeg Dash
source.SupportsDirectStream = false;
2015-03-17 03:51:35 +00:00
}
2015-03-26 04:44:24 +00:00
else
{
source.SupportsDirectStream = false;
}
2015-03-17 03:51:35 +00:00
2015-03-08 16:25:46 +00:00
list.Add(source);
}
2015-03-07 23:39:24 +00:00
2015-04-05 15:01:57 +00:00
foreach (var source in list)
{
if (user != null)
{
2015-04-09 05:20:23 +00:00
if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
2015-04-05 15:01:57 +00:00
{
2015-04-09 05:20:23 +00:00
if (!user.Policy.EnableAudioPlaybackTranscoding)
{
source.SupportsTranscoding = false;
}
}
else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
{
if (!user.Policy.EnableVideoPlaybackTranscoding)
{
source.SupportsTranscoding = false;
}
2015-04-05 15:01:57 +00:00
}
}
}
2015-03-28 20:22:27 +00:00
return SortMediaSources(list).Where(i => i.Type != MediaSourceType.Placeholder);
2015-03-07 23:39:24 +00:00
}
private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(IHasMediaSources item, CancellationToken cancellationToken)
{
var tasks = _providers.Select(i => GetDynamicMediaSources(item, i, cancellationToken));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
return results.SelectMany(i => i.ToList());
}
private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(IHasMediaSources item, IMediaSourceProvider provider, CancellationToken cancellationToken)
{
try
{
2015-03-28 20:22:27 +00:00
var sources = await provider.GetMediaSources(item, cancellationToken).ConfigureAwait(false);
var list = sources.ToList();
foreach (var mediaSource in list)
{
SetKeyProperties(provider, mediaSource);
}
return list;
2015-03-07 23:39:24 +00:00
}
catch (Exception ex)
{
_logger.ErrorException("Error getting media sources", ex);
return new List<MediaSourceInfo>();
}
2015-03-07 22:43:53 +00:00
}
2015-03-28 20:22:27 +00:00
private void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource)
{
2015-07-18 02:52:27 +00:00
var prefix = provider.GetType().FullName.GetMD5().ToString("N") + LiveStreamIdDelimeter;
2015-03-28 20:22:27 +00:00
2015-03-29 04:56:39 +00:00
if (!string.IsNullOrWhiteSpace(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
2015-03-28 20:22:27 +00:00
{
2015-03-29 04:56:39 +00:00
mediaSource.OpenToken = prefix + mediaSource.OpenToken;
2015-03-28 20:22:27 +00:00
}
2015-03-29 04:56:39 +00:00
if (!string.IsNullOrWhiteSpace(mediaSource.LiveStreamId) && !mediaSource.LiveStreamId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
2015-03-28 20:22:27 +00:00
{
2015-03-29 04:56:39 +00:00
mediaSource.LiveStreamId = prefix + mediaSource.LiveStreamId;
2015-03-28 20:22:27 +00:00
}
}
2015-04-09 05:20:23 +00:00
public async Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, bool enablePathSubstitution)
2015-03-31 16:24:16 +00:00
{
2015-04-09 05:20:23 +00:00
var sources = await GetPlayackMediaSources(item.Id.ToString("N"), null, enablePathSubstitution, new[] { MediaType.Audio, MediaType.Video },
CancellationToken.None).ConfigureAwait(false);
return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
2015-03-31 16:24:16 +00:00
}
2015-04-01 21:56:32 +00:00
public IEnumerable<MediaSourceInfo> GetStaticMediaSources(IHasMediaSources item, bool enablePathSubstitution, User user = null)
2015-03-07 22:43:53 +00:00
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (!(item is Video))
{
return item.GetMediaSources(enablePathSubstitution);
}
var sources = item.GetMediaSources(enablePathSubstitution).ToList();
2015-04-01 21:56:32 +00:00
if (user != null)
2015-03-07 22:43:53 +00:00
{
2015-04-01 21:56:32 +00:00
foreach (var source in sources)
{
SetUserProperties(item, source, user);
2015-04-01 21:56:32 +00:00
}
2015-03-07 22:43:53 +00:00
}
return sources;
}
private void SetUserProperties(IHasUserData item, MediaSourceInfo source, User user)
2015-03-07 22:43:53 +00:00
{
var userData = item == null ? new UserItemData() : _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
SetDefaultAudioStreamIndex(source, userData, user);
SetDefaultSubtitleStreamIndex(source, userData, user);
}
2015-03-07 22:43:53 +00:00
private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user)
{
if (userData.SubtitleStreamIndex.HasValue && user.Configuration.RememberSubtitleSelections)
{
var index = userData.SubtitleStreamIndex.Value;
// Make sure the saved index is still valid
if (index == -1 || source.MediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.Index == index))
{
source.DefaultSubtitleStreamIndex = index;
return;
}
}
2015-03-07 22:43:53 +00:00
var preferredSubs = string.IsNullOrEmpty(user.Configuration.SubtitleLanguagePreference)
? new List<string> { }
: new List<string> { user.Configuration.SubtitleLanguagePreference };
var defaultAudioIndex = source.DefaultAudioStreamIndex;
var audioLangage = defaultAudioIndex == null
? null
: source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select(i => i.Language).FirstOrDefault();
source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(source.MediaStreams,
preferredSubs,
user.Configuration.SubtitleMode,
audioLangage);
2015-03-31 16:24:16 +00:00
MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs,
user.Configuration.SubtitleMode, audioLangage);
2015-03-07 22:43:53 +00:00
}
private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user)
{
if (userData.AudioStreamIndex.HasValue && user.Configuration.RememberAudioSelections)
{
var index = userData.AudioStreamIndex.Value;
// Make sure the saved index is still valid
if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index))
{
source.DefaultAudioStreamIndex = index;
return;
}
}
var preferredAudio = string.IsNullOrEmpty(user.Configuration.AudioLanguagePreference)
? new string[] { }
: new[] { user.Configuration.AudioLanguagePreference };
source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.Configuration.PlayDefaultAudioTrack);
}
2015-03-07 22:43:53 +00:00
private IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
{
return sources.OrderBy(i =>
{
if (i.VideoType.HasValue && i.VideoType.Value == VideoType.VideoFile)
{
return 0;
}
return 1;
}).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
.ThenByDescending(i =>
{
var stream = i.VideoStream;
return stream == null || stream.Width == null ? 0 : stream.Width.Value;
})
.ToList();
}
2015-03-29 22:38:32 +00:00
private readonly ConcurrentDictionary<string, LiveStreamInfo> _openStreams = new ConcurrentDictionary<string, LiveStreamInfo>(StringComparer.OrdinalIgnoreCase);
2015-03-28 20:22:27 +00:00
private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
2015-03-29 04:56:39 +00:00
2015-03-29 16:45:16 +00:00
public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, bool enableAutoClose, CancellationToken cancellationToken)
2015-03-28 20:22:27 +00:00
{
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
2015-03-29 16:45:16 +00:00
var tuple = GetProvider(request.OpenToken);
2015-03-28 20:22:27 +00:00
var provider = tuple.Item1;
var mediaSource = await provider.OpenMediaSource(tuple.Item2, cancellationToken).ConfigureAwait(false);
2015-03-29 22:38:32 +00:00
if (string.IsNullOrWhiteSpace(mediaSource.LiveStreamId))
{
throw new InvalidOperationException(string.Format("{0} returned null LiveStreamId", provider.GetType().Name));
}
2015-03-28 20:22:27 +00:00
SetKeyProperties(provider, mediaSource);
2015-03-29 04:56:39 +00:00
var info = new LiveStreamInfo
{
Date = DateTime.UtcNow,
EnableCloseTimer = enableAutoClose,
Id = mediaSource.LiveStreamId,
MediaSource = mediaSource
};
_openStreams.AddOrUpdate(mediaSource.LiveStreamId, info, (key, i) => info);
if (enableAutoClose)
{
StartCloseTimer();
}
2015-03-29 16:45:16 +00:00
var json = _jsonSerializer.SerializeToString(mediaSource);
2015-04-05 15:01:57 +00:00
_logger.Debug("Live stream opened: " + json);
2015-03-29 16:45:16 +00:00
var clone = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
2015-03-29 16:45:16 +00:00
if (!string.IsNullOrWhiteSpace(request.UserId))
2015-03-29 04:56:39 +00:00
{
2015-03-29 16:45:16 +00:00
var user = _userManager.GetUserById(request.UserId);
var item = string.IsNullOrWhiteSpace(request.ItemId)
? null
: _libraryManager.GetItemById(request.ItemId);
SetUserProperties(item, clone, user);
2015-03-29 04:56:39 +00:00
}
2015-03-29 16:45:16 +00:00
return new LiveStreamResponse
{
MediaSource = clone
};
2015-03-28 20:22:27 +00:00
}
finally
{
_liveStreamSemaphore.Release();
}
}
2015-03-29 04:56:39 +00:00
public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken)
{
2015-03-29 22:38:32 +00:00
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentNullException("id");
}
_logger.Debug("Getting live stream {0}", id);
2015-03-29 04:56:39 +00:00
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
LiveStreamInfo info;
if (_openStreams.TryGetValue(id, out info))
{
return info.MediaSource;
}
else
{
throw new ResourceNotFoundException();
}
}
finally
{
_liveStreamSemaphore.Release();
}
}
public async Task PingLiveStream(string id, CancellationToken cancellationToken)
{
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
LiveStreamInfo info;
if (_openStreams.TryGetValue(id, out info))
{
info.Date = DateTime.UtcNow;
}
else
{
_logger.Error("Failed to update MediaSource timestamp for {0}", id);
}
}
finally
{
_liveStreamSemaphore.Release();
}
}
public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
2015-03-28 20:22:27 +00:00
{
await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
2015-03-31 16:24:16 +00:00
LiveStreamInfo current;
if (_openStreams.TryGetValue(id, out current))
{
2015-08-02 19:08:55 +00:00
if (current.MediaSource.RequiresClosing)
2015-03-31 16:24:16 +00:00
{
var tuple = GetProvider(id);
2015-03-28 20:22:27 +00:00
2015-03-31 16:24:16 +00:00
await tuple.Item1.CloseMediaSource(tuple.Item2, cancellationToken).ConfigureAwait(false);
}
}
2015-03-28 20:22:27 +00:00
2015-03-29 04:56:39 +00:00
LiveStreamInfo removed;
if (_openStreams.TryRemove(id, out removed))
{
removed.Closed = true;
}
if (_openStreams.Count == 0)
{
StopCloseTimer();
}
2015-03-28 20:22:27 +00:00
}
finally
{
_liveStreamSemaphore.Release();
}
}
2015-07-28 19:54:45 +00:00
2015-07-18 02:52:27 +00:00
// Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
private const char LiveStreamIdDelimeter = '_';
2015-03-28 20:22:27 +00:00
private Tuple<IMediaSourceProvider, string> GetProvider(string key)
{
2015-08-24 12:54:10 +00:00
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("key");
}
2015-07-18 02:52:27 +00:00
var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2);
2015-03-28 20:22:27 +00:00
var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), keys[0], StringComparison.OrdinalIgnoreCase));
2015-08-24 02:08:20 +00:00
var splitIndex = key.IndexOf(LiveStreamIdDelimeter);
var keyId = key.Substring(splitIndex + 1);
return new Tuple<IMediaSourceProvider, string>(provider, keyId);
2015-03-28 20:22:27 +00:00
}
2015-03-29 04:56:39 +00:00
private Timer _closeTimer;
2015-06-11 03:01:41 +00:00
private readonly TimeSpan _openStreamMaxAge = TimeSpan.FromSeconds(60);
2015-03-29 04:56:39 +00:00
private void StartCloseTimer()
{
StopCloseTimer();
_closeTimer = new Timer(CloseTimerCallback, null, _openStreamMaxAge, _openStreamMaxAge);
}
private void StopCloseTimer()
{
var timer = _closeTimer;
if (timer != null)
{
_closeTimer = null;
timer.Dispose();
}
}
private async void CloseTimerCallback(object state)
{
var infos = _openStreams
.Values
.Where(i => i.EnableCloseTimer && (DateTime.UtcNow - i.Date) > _openStreamMaxAge)
.ToList();
foreach (var info in infos)
{
if (!info.Closed)
{
try
{
await CloseLiveStream(info.Id, CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error closing media source", ex);
}
}
}
}
2015-03-28 20:22:27 +00:00
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
2015-03-29 04:56:39 +00:00
StopCloseTimer();
2015-03-28 20:22:27 +00:00
Dispose(true);
}
private readonly object _disposeLock = new object();
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
lock (_disposeLock)
{
foreach (var key in _openStreams.Keys.ToList())
{
2015-03-29 04:56:39 +00:00
var task = CloseLiveStream(key, CancellationToken.None);
2015-03-28 20:22:27 +00:00
Task.WaitAll(task);
}
_openStreams.Clear();
}
}
}
2015-03-29 04:56:39 +00:00
private class LiveStreamInfo
{
public DateTime Date;
public bool EnableCloseTimer;
public string Id;
public bool Closed;
public MediaSourceInfo MediaSource;
}
}
2015-09-20 17:56:26 +00:00
}