jellyfin-server/MediaBrowser.Api/Playback/MediaInfoService.cs

542 lines
21 KiB
C#
Raw Normal View History

2015-04-09 05:20:23 +00:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
2014-11-19 02:45:12 +00:00
using MediaBrowser.Controller.Net;
2015-03-16 16:47:14 +00:00
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
2015-03-28 20:22:27 +00:00
using MediaBrowser.Model.Entities;
2014-11-19 02:45:12 +00:00
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Session;
2015-03-23 17:19:21 +00:00
using System;
2015-03-16 16:47:14 +00:00
using System.Collections.Generic;
2014-11-19 02:45:12 +00:00
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.MediaEncoding;
2016-08-29 19:24:58 +00:00
using MediaBrowser.Model.Serialization;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.Services;
2014-11-19 02:45:12 +00:00
namespace MediaBrowser.Api.Playback
{
2015-03-07 22:43:53 +00:00
[Route("/Items/{Id}/PlaybackInfo", "GET", Summary = "Gets live playback media info for an item")]
public class GetPlaybackInfo : IReturn<PlaybackInfoResponse>
{
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get; set; }
[ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string UserId { get; set; }
}
[Route("/Items/{Id}/PlaybackInfo", "POST", Summary = "Gets live playback media info for an item")]
public class GetPostedPlaybackInfo : PlaybackInfoRequest, IReturn<PlaybackInfoResponse>
2015-03-07 22:43:53 +00:00
{
}
2015-03-29 16:45:16 +00:00
[Route("/LiveStreams/Open", "POST", Summary = "Opens a media source")]
public class OpenMediaSource : LiveStreamRequest, IReturn<LiveStreamResponse>
2015-03-29 04:56:39 +00:00
{
}
2015-03-29 16:45:16 +00:00
[Route("/LiveStreams/Close", "POST", Summary = "Closes a media source")]
2015-03-29 04:56:39 +00:00
public class CloseMediaSource : IReturnVoid
{
[ApiMember(Name = "LiveStreamId", Description = "LiveStreamId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
public string LiveStreamId { get; set; }
}
2015-04-30 15:06:37 +00:00
[Route("/Playback/BitrateTest", "GET")]
2015-06-03 05:30:14 +00:00
public class GetBitrateTestBytes
2015-04-30 15:06:37 +00:00
{
[ApiMember(Name = "Size", Description = "Size", IsRequired = true, DataType = "int", ParameterType = "query", Verb = "GET")]
public long Size { get; set; }
public GetBitrateTestBytes()
{
// 100k
Size = 102400;
}
}
2015-09-18 01:51:22 +00:00
2014-11-19 02:45:12 +00:00
[Authenticated]
public class MediaInfoService : BaseApiService
{
2015-03-07 22:43:53 +00:00
private readonly IMediaSourceManager _mediaSourceManager;
private readonly IDeviceManager _deviceManager;
private readonly ILibraryManager _libraryManager;
2015-04-09 05:20:23 +00:00
private readonly IServerConfigurationManager _config;
private readonly INetworkManager _networkManager;
private readonly IMediaEncoder _mediaEncoder;
private readonly IUserManager _userManager;
2016-08-29 19:24:58 +00:00
private readonly IJsonSerializer _json;
2016-11-10 14:41:24 +00:00
private readonly IAuthorizationContext _authContext;
2014-11-19 02:45:12 +00:00
2016-11-10 14:41:24 +00:00
public MediaInfoService(IMediaSourceManager mediaSourceManager, IDeviceManager deviceManager, ILibraryManager libraryManager, IServerConfigurationManager config, INetworkManager networkManager, IMediaEncoder mediaEncoder, IUserManager userManager, IJsonSerializer json, IAuthorizationContext authContext)
2014-11-19 02:45:12 +00:00
{
2015-03-07 22:43:53 +00:00
_mediaSourceManager = mediaSourceManager;
_deviceManager = deviceManager;
_libraryManager = libraryManager;
2015-04-09 05:20:23 +00:00
_config = config;
_networkManager = networkManager;
_mediaEncoder = mediaEncoder;
_userManager = userManager;
2016-08-29 19:24:58 +00:00
_json = json;
2016-11-10 14:41:24 +00:00
_authContext = authContext;
}
2015-04-30 15:06:37 +00:00
public object Get(GetBitrateTestBytes request)
{
var bytes = new byte[request.Size];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = 0;
}
return ResultFactory.GetResult(bytes, "application/octet-stream");
}
public async Task<object> Get(GetPlaybackInfo request)
{
2015-04-09 05:20:23 +00:00
var result = await GetPlaybackInfo(request.Id, request.UserId, new[] { MediaType.Audio, MediaType.Video }).ConfigureAwait(false);
return ToOptimizedResult(result);
2014-11-19 02:45:12 +00:00
}
2015-03-29 04:56:39 +00:00
public async Task<object> Post(OpenMediaSource request)
{
2016-11-10 14:41:24 +00:00
var authInfo = _authContext.GetAuthorizationInfo(Request);
2015-03-29 16:45:16 +00:00
2017-04-17 19:01:16 +00:00
var result = await _mediaSourceManager.OpenLiveStream(request, CancellationToken.None).ConfigureAwait(false);
2015-03-29 16:45:16 +00:00
var profile = request.DeviceProfile;
if (profile == null)
{
var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
if (caps != null)
{
profile = caps.DeviceProfile;
}
}
if (profile != null)
{
var item = _libraryManager.GetItemById(request.ItemId);
2015-03-29 22:38:32 +00:00
SetDeviceSpecificData(item, result.MediaSource, profile, authInfo, request.MaxStreamingBitrate,
request.StartTimeTicks ?? 0, result.MediaSource.Id, request.AudioStreamIndex,
request.SubtitleStreamIndex, request.MaxAudioChannels, request.PlaySessionId, request.UserId, true, true, true, true, true, true);
2015-03-29 16:45:16 +00:00
}
2015-03-29 22:38:32 +00:00
else
2015-03-29 16:45:16 +00:00
{
2015-03-29 22:38:32 +00:00
if (!string.IsNullOrWhiteSpace(result.MediaSource.TranscodingUrl))
{
result.MediaSource.TranscodingUrl += "&LiveStreamId=" + result.MediaSource.LiveStreamId;
}
2015-03-29 16:45:16 +00:00
}
2015-03-29 04:56:39 +00:00
return ToOptimizedResult(result);
}
public void Post(CloseMediaSource request)
{
2016-09-29 12:55:49 +00:00
var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId);
2015-03-29 04:56:39 +00:00
Task.WaitAll(task);
}
2017-02-17 21:11:13 +00:00
public async Task<PlaybackInfoResponse> GetPlaybackInfo(GetPostedPlaybackInfo request)
2015-03-16 16:47:14 +00:00
{
2016-11-10 14:41:24 +00:00
var authInfo = _authContext.GetAuthorizationInfo(Request);
var profile = request.DeviceProfile;
2015-04-09 05:20:23 +00:00
2016-08-29 19:24:58 +00:00
//Logger.Info("GetPostedPlaybackInfo profile: {0}", _json.SerializeToString(profile));
2016-01-30 18:31:31 +00:00
if (profile == null)
2015-03-26 23:10:34 +00:00
{
2016-01-30 18:31:31 +00:00
var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
if (caps != null)
2015-03-26 23:10:34 +00:00
{
profile = caps.DeviceProfile;
}
}
2015-04-09 05:20:23 +00:00
var info = await GetPlaybackInfo(request.Id, request.UserId, new[] { MediaType.Audio, MediaType.Video }, request.MediaSourceId, request.LiveStreamId).ConfigureAwait(false);
if (profile != null)
{
2015-03-28 20:22:27 +00:00
var mediaSourceId = request.MediaSourceId;
2015-04-09 18:00:30 +00:00
SetDeviceSpecificData(request.Id, info, profile, authInfo, request.MaxStreamingBitrate ?? profile.MaxStreamingBitrate, request.StartTimeTicks ?? 0, mediaSourceId, request.AudioStreamIndex, request.SubtitleStreamIndex, request.MaxAudioChannels, request.UserId, request.EnableDirectPlay, request.ForceDirectPlayRemoteMediaSource, request.EnableDirectStream, request.EnableTranscoding, request.AllowVideoStreamCopy, request.AllowAudioStreamCopy);
}
2017-02-17 21:11:13 +00:00
return info;
}
public async Task<object> Post(GetPostedPlaybackInfo request)
{
var result = await GetPlaybackInfo(request).ConfigureAwait(false);
return ToOptimizedResult(result);
2015-03-07 22:43:53 +00:00
}
2014-11-26 04:12:29 +00:00
2017-01-21 20:27:07 +00:00
private T Clone<T>(T obj)
{
// Since we're going to be setting properties on MediaSourceInfos that come out of _mediaSourceManager, we should clone it
// Should we move this directly into MediaSourceManager?
var json = _json.SerializeToString(obj);
return _json.DeserializeFromString<T>(json);
}
2015-04-09 05:20:23 +00:00
private async Task<PlaybackInfoResponse> GetPlaybackInfo(string id, string userId, string[] supportedLiveMediaTypes, string mediaSourceId = null, string liveStreamId = null)
2015-03-07 22:43:53 +00:00
{
var result = new PlaybackInfoResponse();
2014-11-19 02:45:12 +00:00
2015-03-31 16:24:16 +00:00
if (string.IsNullOrWhiteSpace(liveStreamId))
2015-03-28 20:22:27 +00:00
{
2015-03-31 16:24:16 +00:00
IEnumerable<MediaSourceInfo> mediaSources;
try
{
2015-04-09 05:20:23 +00:00
mediaSources = await _mediaSourceManager.GetPlayackMediaSources(id, userId, true, supportedLiveMediaTypes, CancellationToken.None).ConfigureAwait(false);
2015-03-31 16:24:16 +00:00
}
catch (PlaybackException ex)
{
mediaSources = new List<MediaSourceInfo>();
result.ErrorCode = ex.ErrorCode;
}
2015-03-26 19:18:21 +00:00
2015-03-31 16:24:16 +00:00
result.MediaSources = mediaSources.ToList();
2015-03-26 19:18:21 +00:00
2015-03-31 16:24:16 +00:00
if (!string.IsNullOrWhiteSpace(mediaSourceId))
{
result.MediaSources = result.MediaSources
.Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
.ToList();
}
}
else
2015-03-16 16:47:14 +00:00
{
2015-03-31 16:24:16 +00:00
var mediaSource = await _mediaSourceManager.GetLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
result.MediaSources = new List<MediaSourceInfo> { mediaSource };
2015-03-16 16:47:14 +00:00
}
if (result.MediaSources.Count == 0)
{
if (!result.ErrorCode.HasValue)
{
result.ErrorCode = PlaybackErrorCode.NoCompatibleStream;
}
}
else
{
2017-01-21 20:27:07 +00:00
result.MediaSources = Clone(result.MediaSources);
2015-03-29 18:31:28 +00:00
result.PlaySessionId = Guid.NewGuid().ToString("N");
}
return result;
}
2015-03-29 16:45:16 +00:00
private void SetDeviceSpecificData(string itemId,
PlaybackInfoResponse result,
DeviceProfile profile,
AuthorizationInfo auth,
2017-01-03 05:15:59 +00:00
long? maxBitrate,
2015-03-26 19:18:21 +00:00
long startTimeTicks,
string mediaSourceId,
int? audioStreamIndex,
int? subtitleStreamIndex,
2016-10-20 18:02:42 +00:00
int? maxAudioChannels,
2017-02-20 07:04:03 +00:00
string userId,
bool enableDirectPlay,
2017-03-10 18:33:17 +00:00
bool forceDirectPlayRemoteMediaSource,
2017-02-20 07:04:03 +00:00
bool enableDirectStream,
bool enableTranscoding,
bool allowVideoStreamCopy,
bool allowAudioStreamCopy)
{
var item = _libraryManager.GetItemById(itemId);
foreach (var mediaSource in result.MediaSources)
{
SetDeviceSpecificData(item, mediaSource, profile, auth, maxBitrate, startTimeTicks, mediaSourceId, audioStreamIndex, subtitleStreamIndex, maxAudioChannels, result.PlaySessionId, userId, enableDirectPlay, forceDirectPlayRemoteMediaSource, enableDirectStream, enableTranscoding, allowVideoStreamCopy, allowAudioStreamCopy);
2015-03-29 04:56:39 +00:00
}
2015-03-26 19:18:21 +00:00
2016-04-14 19:12:00 +00:00
SortMediaSources(result, maxBitrate);
2015-03-29 04:56:39 +00:00
}
2015-03-29 04:56:39 +00:00
private void SetDeviceSpecificData(BaseItem item,
MediaSourceInfo mediaSource,
DeviceProfile profile,
AuthorizationInfo auth,
2017-01-03 05:15:59 +00:00
long? maxBitrate,
2015-03-29 04:56:39 +00:00
long startTimeTicks,
string mediaSourceId,
int? audioStreamIndex,
2015-04-01 21:55:50 +00:00
int? subtitleStreamIndex,
2016-10-20 18:02:42 +00:00
int? maxAudioChannels,
string playSessionId,
2017-02-20 07:04:03 +00:00
string userId,
bool enableDirectPlay,
2017-03-10 18:33:17 +00:00
bool forceDirectPlayRemoteMediaSource,
2017-02-20 07:04:03 +00:00
bool enableDirectStream,
bool enableTranscoding,
bool allowVideoStreamCopy,
bool allowAudioStreamCopy)
2015-03-29 04:56:39 +00:00
{
var streamBuilder = new StreamBuilder(_mediaEncoder, Logger);
2015-03-26 19:18:21 +00:00
2015-03-29 04:56:39 +00:00
var options = new VideoOptions
{
MediaSources = new List<MediaSourceInfo> { mediaSource },
Context = EncodingContext.Streaming,
DeviceId = auth.DeviceId,
ItemId = item.Id.ToString("N"),
2016-10-20 18:02:42 +00:00
Profile = profile,
MaxAudioChannels = maxAudioChannels
2015-03-29 04:56:39 +00:00
};
if (string.Equals(mediaSourceId, mediaSource.Id, StringComparison.OrdinalIgnoreCase))
{
options.MediaSourceId = mediaSourceId;
options.AudioStreamIndex = audioStreamIndex;
options.SubtitleStreamIndex = subtitleStreamIndex;
}
var user = _userManager.GetUserById(userId);
2017-02-20 07:04:03 +00:00
if (!enableDirectPlay)
{
mediaSource.SupportsDirectPlay = false;
}
if (!enableDirectStream)
{
mediaSource.SupportsDirectStream = false;
}
if (!enableTranscoding)
{
mediaSource.SupportsTranscoding = false;
}
2015-03-29 04:56:39 +00:00
if (mediaSource.SupportsDirectPlay)
{
2017-03-10 18:33:17 +00:00
if (mediaSource.IsRemote && forceDirectPlayRemoteMediaSource)
{
}
else
{
var supportsDirectStream = mediaSource.SupportsDirectStream;
2017-03-10 18:33:17 +00:00
// Dummy this up to fool StreamBuilder
mediaSource.SupportsDirectStream = true;
options.MaxBitrate = maxBitrate;
2017-03-10 18:33:17 +00:00
if (item is Audio)
{
2017-03-10 18:33:17 +00:00
if (!user.Policy.EnableAudioPlaybackTranscoding)
{
options.ForceDirectPlay = true;
}
}
2017-03-10 18:33:17 +00:00
else if (item is Video)
2016-08-13 22:27:14 +00:00
{
2017-03-10 18:33:17 +00:00
if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing)
{
options.ForceDirectPlay = true;
}
2016-08-13 22:27:14 +00:00
}
2017-03-10 18:33:17 +00:00
// The MediaSource supports direct stream, now test to see if the client supports it
var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
streamBuilder.BuildAudioItem(options) :
streamBuilder.BuildVideoItem(options);
2015-03-29 04:56:39 +00:00
2017-03-10 18:33:17 +00:00
if (streamInfo == null || !streamInfo.IsDirectStream)
{
mediaSource.SupportsDirectPlay = false;
}
2017-03-10 18:33:17 +00:00
// Set this back to what it was
mediaSource.SupportsDirectStream = supportsDirectStream;
2015-03-30 19:57:37 +00:00
2017-03-10 18:33:17 +00:00
if (streamInfo != null)
{
SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
}
2015-03-30 19:57:37 +00:00
}
2015-03-29 04:56:39 +00:00
}
if (mediaSource.SupportsDirectStream)
{
2015-04-09 18:00:30 +00:00
options.MaxBitrate = GetMaxBitrate(maxBitrate);
2015-09-18 01:51:22 +00:00
if (item is Audio)
{
if (!user.Policy.EnableAudioPlaybackTranscoding)
{
options.ForceDirectStream = true;
}
}
2016-08-13 22:27:14 +00:00
else if (item is Video)
{
if (!user.Policy.EnableAudioPlaybackTranscoding && !user.Policy.EnableVideoPlaybackTranscoding && !user.Policy.EnablePlaybackRemuxing)
{
options.ForceDirectStream = true;
}
}
2015-03-29 04:56:39 +00:00
// The MediaSource supports direct stream, now test to see if the client supports it
var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
streamBuilder.BuildAudioItem(options) :
streamBuilder.BuildVideoItem(options);
if (streamInfo == null || !streamInfo.IsDirectStream)
{
2015-03-29 04:56:39 +00:00
mediaSource.SupportsDirectStream = false;
}
2015-03-30 19:57:37 +00:00
if (streamInfo != null)
{
2015-04-02 02:47:59 +00:00
SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
2015-03-30 19:57:37 +00:00
}
}
2015-03-28 20:22:27 +00:00
2015-03-29 04:56:39 +00:00
if (mediaSource.SupportsTranscoding)
{
2015-04-09 18:00:30 +00:00
options.MaxBitrate = GetMaxBitrate(maxBitrate);
2015-09-18 01:51:22 +00:00
2015-03-29 04:56:39 +00:00
// The MediaSource supports direct stream, now test to see if the client supports it
var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
streamBuilder.BuildAudioItem(options) :
streamBuilder.BuildVideoItem(options);
2015-04-01 21:55:50 +00:00
if (streamInfo != null)
{
streamInfo.PlaySessionId = playSessionId;
if (streamInfo.PlayMethod == PlayMethod.Transcode)
{
streamInfo.StartPositionTicks = startTimeTicks;
mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).TrimStart('-');
if (!allowVideoStreamCopy)
{
mediaSource.TranscodingUrl += "&allowVideoStreamCopy=false";
}
if (!allowAudioStreamCopy)
{
mediaSource.TranscodingUrl += "&allowAudioStreamCopy=false";
}
mediaSource.TranscodingContainer = streamInfo.Container;
mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
}
// Do this after the above so that StartPositionTicks is set
SetDeviceSpecificSubtitleInfo(streamInfo, mediaSource, auth.Token);
2015-03-29 04:56:39 +00:00
}
2015-03-30 19:57:37 +00:00
}
}
2017-01-03 05:15:59 +00:00
private long? GetMaxBitrate(long? clientMaxBitrate)
2015-04-09 18:00:30 +00:00
{
var maxBitrate = clientMaxBitrate;
2015-04-28 13:56:57 +00:00
var remoteClientMaxBitrate = _config.Configuration.RemoteClientBitrateLimit;
2015-04-09 18:00:30 +00:00
2015-09-18 01:51:22 +00:00
if (remoteClientMaxBitrate > 0)
2015-04-09 18:00:30 +00:00
{
2015-09-18 01:51:22 +00:00
var isInLocalNetwork = _networkManager.IsInLocalNetwork(Request.RemoteIp);
Logger.Info("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, Request.RemoteIp, isInLocalNetwork);
if (!isInLocalNetwork)
{
maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
}
2015-04-09 18:00:30 +00:00
}
return maxBitrate;
}
2015-04-02 02:47:59 +00:00
private void SetDeviceSpecificSubtitleInfo(StreamInfo info, MediaSourceInfo mediaSource, string accessToken)
2015-03-30 19:57:37 +00:00
{
2015-04-02 02:47:59 +00:00
var profiles = info.GetSubtitleProfiles(false, "-", accessToken);
2015-03-31 16:24:16 +00:00
mediaSource.DefaultSubtitleStreamIndex = info.SubtitleStreamIndex;
2015-03-30 19:57:37 +00:00
foreach (var profile in profiles)
{
foreach (var stream in mediaSource.MediaStreams)
{
if (stream.Type == MediaStreamType.Subtitle && stream.Index == profile.Index)
{
stream.DeliveryMethod = profile.DeliveryMethod;
if (profile.DeliveryMethod == SubtitleDeliveryMethod.External)
{
2015-04-03 02:36:15 +00:00
stream.DeliveryUrl = profile.Url.TrimStart('-');
2015-04-02 02:47:59 +00:00
stream.IsExternalUrl = profile.IsExternalUrl;
2015-03-30 19:57:37 +00:00
}
}
}
2015-03-29 04:56:39 +00:00
}
2015-03-28 20:22:27 +00:00
}
2017-01-03 05:15:59 +00:00
private void SortMediaSources(PlaybackInfoResponse result, long? maxBitrate)
2015-03-28 20:22:27 +00:00
{
var originalList = result.MediaSources.ToList();
result.MediaSources = result.MediaSources.OrderBy(i =>
{
// Nothing beats direct playing a file
if (i.SupportsDirectPlay && i.Protocol == MediaProtocol.File)
{
return 0;
}
return 1;
}).ThenBy(i =>
{
// Let's assume direct streaming a file is just as desirable as direct playing a remote url
if (i.SupportsDirectPlay || i.SupportsDirectStream)
{
return 0;
}
return 1;
}).ThenBy(i =>
{
switch (i.Protocol)
{
case MediaProtocol.File:
return 0;
default:
return 1;
}
2016-04-14 19:12:00 +00:00
}).ThenBy(i =>
{
if (maxBitrate.HasValue)
{
if (i.Bitrate.HasValue)
{
if (i.Bitrate.Value <= maxBitrate.Value)
{
return 0;
}
return 2;
}
}
return 1;
2015-03-28 20:22:27 +00:00
}).ThenBy(originalList.IndexOf)
.ToList();
2014-11-19 02:45:12 +00:00
}
}
}