jellyfin/MediaBrowser.Api/Playback/MediaInfoService.cs

417 lines
16 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;
2014-11-19 02:45:12 +00:00
using ServiceStack;
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;
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;
2014-11-19 02:45:12 +00:00
2015-04-09 05:20:23 +00:00
public MediaInfoService(IMediaSourceManager mediaSourceManager, IDeviceManager deviceManager, ILibraryManager libraryManager, IServerConfigurationManager config, INetworkManager networkManager)
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;
}
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)
{
2015-03-29 16:45:16 +00:00
var authInfo = AuthorizationContext.GetAuthorizationInfo(Request);
var result = await _mediaSourceManager.OpenLiveStream(request, false, CancellationToken.None).ConfigureAwait(false);
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,
2015-04-01 21:55:50 +00:00
request.SubtitleStreamIndex, request.PlaySessionId);
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)
{
var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId, CancellationToken.None);
Task.WaitAll(task);
}
public async Task<object> Post(GetPostedPlaybackInfo request)
2015-03-16 16:47:14 +00:00
{
var authInfo = AuthorizationContext.GetAuthorizationInfo(Request);
var profile = request.DeviceProfile;
2015-04-09 05:20:23 +00:00
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
2015-12-18 16:43:42 +00:00
SetDeviceSpecificData(request.Id, info, profile, authInfo, request.MaxStreamingBitrate ?? profile.MaxStreamingBitrate, request.StartTimeTicks ?? 0, mediaSourceId, request.AudioStreamIndex, request.SubtitleStreamIndex);
}
return ToOptimizedResult(info);
2015-03-07 22:43:53 +00:00
}
2014-11-26 04:12:29 +00:00
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
{
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,
int? maxBitrate,
2015-03-26 19:18:21 +00:00
long startTimeTicks,
string mediaSourceId,
int? audioStreamIndex,
int? subtitleStreamIndex)
{
var item = _libraryManager.GetItemById(itemId);
foreach (var mediaSource in result.MediaSources)
{
2015-04-01 21:55:50 +00:00
SetDeviceSpecificData(item, mediaSource, profile, auth, maxBitrate, startTimeTicks, mediaSourceId, audioStreamIndex, subtitleStreamIndex, result.PlaySessionId);
2015-03-29 04:56:39 +00:00
}
2015-03-26 19:18:21 +00:00
2015-03-29 04:56:39 +00:00
SortMediaSources(result);
}
2015-03-29 04:56:39 +00:00
private void SetDeviceSpecificData(BaseItem item,
MediaSourceInfo mediaSource,
DeviceProfile profile,
AuthorizationInfo auth,
int? maxBitrate,
long startTimeTicks,
string mediaSourceId,
int? audioStreamIndex,
2015-04-01 21:55:50 +00:00
int? subtitleStreamIndex,
string playSessionId)
2015-03-29 04:56:39 +00:00
{
2015-04-04 19:35:29 +00:00
var streamBuilder = new StreamBuilder(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"),
2015-04-09 18:00:30 +00:00
Profile = profile
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;
}
2015-03-29 04:56:39 +00:00
if (mediaSource.SupportsDirectPlay)
{
var supportsDirectStream = mediaSource.SupportsDirectStream;
2015-03-29 04:56:39 +00:00
// Dummy this up to fool StreamBuilder
mediaSource.SupportsDirectStream = true;
2015-04-09 18:00:30 +00:00
options.MaxBitrate = maxBitrate;
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.SupportsDirectPlay = false;
}
2015-03-29 04:56:39 +00:00
// Set this back to what it was
mediaSource.SupportsDirectStream = supportsDirectStream;
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-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
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('-');
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
}
}
2015-04-09 18:00:30 +00:00
private int? GetMaxBitrate(int? clientMaxBitrate)
{
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
}
private void SortMediaSources(PlaybackInfoResponse result)
{
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;
}
}).ThenBy(originalList.IndexOf)
.ToList();
2014-11-19 02:45:12 +00:00
}
}
}