MediaInfoService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. using MediaBrowser.Controller.Devices;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Model.Dlna;
  6. using MediaBrowser.Model.Dto;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.MediaInfo;
  9. using MediaBrowser.Model.Session;
  10. using ServiceStack;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Api.Playback
  17. {
  18. [Route("/Items/{Id}/MediaInfo", "GET", Summary = "Gets live playback media info for an item")]
  19. public class GetLiveMediaInfo : IReturn<PlaybackInfoResponse>
  20. {
  21. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  22. public string Id { get; set; }
  23. [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  24. public string UserId { get; set; }
  25. }
  26. [Route("/Items/{Id}/PlaybackInfo", "GET", Summary = "Gets live playback media info for an item")]
  27. public class GetPlaybackInfo : IReturn<PlaybackInfoResponse>
  28. {
  29. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  30. public string Id { get; set; }
  31. [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  32. public string UserId { get; set; }
  33. }
  34. [Route("/Items/{Id}/PlaybackInfo", "POST", Summary = "Gets live playback media info for an item")]
  35. public class GetPostedPlaybackInfo : PlaybackInfoRequest, IReturn<PlaybackInfoResponse>
  36. {
  37. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  38. public string Id { get; set; }
  39. [ApiMember(Name = "UserId", Description = "User Id", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  40. public string UserId { get; set; }
  41. [ApiMember(Name = "StartTimeTicks", Description = "Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
  42. public long? StartTimeTicks { get; set; }
  43. [ApiMember(Name = "AudioStreamIndex", Description = "Optional. The index of the audio stream to use. If omitted the first audio stream will be used.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
  44. public int? AudioStreamIndex { get; set; }
  45. [ApiMember(Name = "SubtitleStreamIndex", Description = "Optional. The index of the subtitle stream to use. If omitted no subtitles will be used.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
  46. public int? SubtitleStreamIndex { get; set; }
  47. [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  48. public string MediaSourceId { get; set; }
  49. }
  50. [Authenticated]
  51. public class MediaInfoService : BaseApiService
  52. {
  53. private readonly IMediaSourceManager _mediaSourceManager;
  54. private readonly IDeviceManager _deviceManager;
  55. private readonly ILibraryManager _libraryManager;
  56. public MediaInfoService(IMediaSourceManager mediaSourceManager, IDeviceManager deviceManager, ILibraryManager libraryManager)
  57. {
  58. _mediaSourceManager = mediaSourceManager;
  59. _deviceManager = deviceManager;
  60. _libraryManager = libraryManager;
  61. }
  62. public async Task<object> Get(GetPlaybackInfo request)
  63. {
  64. var result = await GetPlaybackInfo(request.Id, request.UserId).ConfigureAwait(false);
  65. return ToOptimizedResult(result);
  66. }
  67. public async Task<object> Get(GetLiveMediaInfo request)
  68. {
  69. var result = await GetPlaybackInfo(request.Id, request.UserId).ConfigureAwait(false);
  70. return ToOptimizedResult(result);
  71. }
  72. public async Task<object> Post(GetPostedPlaybackInfo request)
  73. {
  74. var info = await GetPlaybackInfo(request.Id, request.UserId, request.MediaSourceId).ConfigureAwait(false);
  75. var authInfo = AuthorizationContext.GetAuthorizationInfo(Request);
  76. var profile = request.DeviceProfile;
  77. if (profile == null)
  78. {
  79. var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
  80. if (caps != null)
  81. {
  82. profile = caps.DeviceProfile;
  83. }
  84. }
  85. if (profile != null)
  86. {
  87. var mediaSourceId = request.MediaSourceId;
  88. SetDeviceSpecificData(request.Id, info, profile, authInfo, null, request.StartTimeTicks ?? 0, mediaSourceId, request.AudioStreamIndex, request.SubtitleStreamIndex);
  89. }
  90. return ToOptimizedResult(info);
  91. }
  92. private async Task<PlaybackInfoResponse> GetPlaybackInfo(string id, string userId, string mediaSourceId = null)
  93. {
  94. var result = new PlaybackInfoResponse();
  95. IEnumerable<MediaSourceInfo> mediaSources;
  96. try
  97. {
  98. mediaSources = await _mediaSourceManager.GetPlayackMediaSources(id, userId, true, CancellationToken.None).ConfigureAwait(false);
  99. }
  100. catch (PlaybackException ex)
  101. {
  102. mediaSources = new List<MediaSourceInfo>();
  103. result.ErrorCode = ex.ErrorCode;
  104. }
  105. result.MediaSources = mediaSources.ToList();
  106. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  107. {
  108. result.MediaSources = result.MediaSources
  109. .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  110. .ToList();
  111. }
  112. if (result.MediaSources.Count == 0)
  113. {
  114. if (!result.ErrorCode.HasValue)
  115. {
  116. result.ErrorCode = PlaybackErrorCode.NoCompatibleStream;
  117. }
  118. }
  119. else
  120. {
  121. result.StreamId = Guid.NewGuid().ToString("N");
  122. }
  123. return result;
  124. }
  125. private void SetDeviceSpecificData(string itemId,
  126. PlaybackInfoResponse result,
  127. DeviceProfile profile,
  128. AuthorizationInfo auth,
  129. int? maxBitrate,
  130. long startTimeTicks,
  131. string mediaSourceId,
  132. int? audioStreamIndex,
  133. int? subtitleStreamIndex)
  134. {
  135. var streamBuilder = new StreamBuilder();
  136. var item = _libraryManager.GetItemById(itemId);
  137. foreach (var mediaSource in result.MediaSources)
  138. {
  139. var options = new VideoOptions
  140. {
  141. MediaSources = new List<MediaSourceInfo> { mediaSource },
  142. Context = EncodingContext.Streaming,
  143. DeviceId = auth.DeviceId,
  144. ItemId = item.Id.ToString("N"),
  145. Profile = profile,
  146. MaxBitrate = maxBitrate
  147. };
  148. if (string.Equals(mediaSourceId, mediaSource.Id, StringComparison.OrdinalIgnoreCase))
  149. {
  150. options.MediaSourceId = mediaSourceId;
  151. options.AudioStreamIndex = audioStreamIndex;
  152. options.SubtitleStreamIndex = subtitleStreamIndex;
  153. }
  154. if (mediaSource.SupportsDirectPlay)
  155. {
  156. var supportsDirectStream = mediaSource.SupportsDirectStream;
  157. // Dummy this up to fool StreamBuilder
  158. mediaSource.SupportsDirectStream = true;
  159. // The MediaSource supports direct stream, now test to see if the client supports it
  160. var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
  161. streamBuilder.BuildAudioItem(options) :
  162. streamBuilder.BuildVideoItem(options);
  163. if (streamInfo == null || !streamInfo.IsDirectStream)
  164. {
  165. mediaSource.SupportsDirectPlay = false;
  166. }
  167. // Set this back to what it was
  168. mediaSource.SupportsDirectStream = supportsDirectStream;
  169. }
  170. if (mediaSource.SupportsDirectStream)
  171. {
  172. // The MediaSource supports direct stream, now test to see if the client supports it
  173. var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
  174. streamBuilder.BuildAudioItem(options) :
  175. streamBuilder.BuildVideoItem(options);
  176. if (streamInfo == null || !streamInfo.IsDirectStream)
  177. {
  178. mediaSource.SupportsDirectStream = false;
  179. }
  180. }
  181. if (mediaSource.SupportsTranscoding)
  182. {
  183. // The MediaSource supports direct stream, now test to see if the client supports it
  184. var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
  185. streamBuilder.BuildAudioItem(options) :
  186. streamBuilder.BuildVideoItem(options);
  187. if (streamInfo != null && streamInfo.PlayMethod == PlayMethod.Transcode)
  188. {
  189. streamInfo.StartPositionTicks = startTimeTicks;
  190. mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).Substring(1);
  191. mediaSource.TranscodingContainer = streamInfo.Container;
  192. mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
  193. }
  194. }
  195. }
  196. SortMediaSources(result);
  197. }
  198. private void SortMediaSources(PlaybackInfoResponse result)
  199. {
  200. var originalList = result.MediaSources.ToList();
  201. result.MediaSources = result.MediaSources.OrderBy(i =>
  202. {
  203. // Nothing beats direct playing a file
  204. if (i.SupportsDirectPlay && i.Protocol == MediaProtocol.File)
  205. {
  206. return 0;
  207. }
  208. return 1;
  209. }).ThenBy(i =>
  210. {
  211. // Let's assume direct streaming a file is just as desirable as direct playing a remote url
  212. if (i.SupportsDirectPlay || i.SupportsDirectStream)
  213. {
  214. return 0;
  215. }
  216. return 1;
  217. }).ThenBy(i =>
  218. {
  219. switch (i.Protocol)
  220. {
  221. case MediaProtocol.File:
  222. return 0;
  223. default:
  224. return 1;
  225. }
  226. }).ThenBy(originalList.IndexOf)
  227. .ToList();
  228. }
  229. }
  230. }