MediaInfoService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 = "MaxStreamingBitrate", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
  42. public int? MaxStreamingBitrate { get; set; }
  43. [ApiMember(Name = "StartTimeTicks", Description = "Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "POST")]
  44. public long? StartTimeTicks { get; set; }
  45. [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")]
  46. public int? AudioStreamIndex { get; set; }
  47. [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")]
  48. public int? SubtitleStreamIndex { get; set; }
  49. [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  50. public string MediaSourceId { get; set; }
  51. }
  52. [Route("/LiveStreams/Open", "POST", Summary = "Opens a media source")]
  53. public class OpenMediaSource : LiveStreamRequest, IReturn<LiveStreamResponse>
  54. {
  55. }
  56. [Route("/LiveStreams/Close", "POST", Summary = "Closes a media source")]
  57. public class CloseMediaSource : IReturnVoid
  58. {
  59. [ApiMember(Name = "LiveStreamId", Description = "LiveStreamId", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "POST")]
  60. public string LiveStreamId { get; set; }
  61. }
  62. [Authenticated]
  63. public class MediaInfoService : BaseApiService
  64. {
  65. private readonly IMediaSourceManager _mediaSourceManager;
  66. private readonly IDeviceManager _deviceManager;
  67. private readonly ILibraryManager _libraryManager;
  68. public MediaInfoService(IMediaSourceManager mediaSourceManager, IDeviceManager deviceManager, ILibraryManager libraryManager)
  69. {
  70. _mediaSourceManager = mediaSourceManager;
  71. _deviceManager = deviceManager;
  72. _libraryManager = libraryManager;
  73. }
  74. public async Task<object> Get(GetPlaybackInfo request)
  75. {
  76. var result = await GetPlaybackInfo(request.Id, request.UserId).ConfigureAwait(false);
  77. return ToOptimizedResult(result);
  78. }
  79. public async Task<object> Get(GetLiveMediaInfo request)
  80. {
  81. var result = await GetPlaybackInfo(request.Id, request.UserId).ConfigureAwait(false);
  82. return ToOptimizedResult(result);
  83. }
  84. public async Task<object> Post(OpenMediaSource request)
  85. {
  86. var authInfo = AuthorizationContext.GetAuthorizationInfo(Request);
  87. var result = await _mediaSourceManager.OpenLiveStream(request, false, CancellationToken.None).ConfigureAwait(false);
  88. var profile = request.DeviceProfile;
  89. if (profile == null)
  90. {
  91. var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
  92. if (caps != null)
  93. {
  94. profile = caps.DeviceProfile;
  95. }
  96. }
  97. if (profile != null)
  98. {
  99. var item = _libraryManager.GetItemById(request.ItemId);
  100. SetDeviceSpecificData(item, result.MediaSource, profile, authInfo, request.MaxStreamingBitrate, request.StartTimeTicks ?? 0, result.MediaSource.Id, request.AudioStreamIndex, request.SubtitleStreamIndex);
  101. }
  102. if (!string.IsNullOrWhiteSpace(result.MediaSource.TranscodingUrl))
  103. {
  104. result.MediaSource.TranscodingUrl += "&LiveStreamId=" + result.MediaSource.LiveStreamId;
  105. }
  106. return ToOptimizedResult(result);
  107. }
  108. public void Post(CloseMediaSource request)
  109. {
  110. var task = _mediaSourceManager.CloseLiveStream(request.LiveStreamId, CancellationToken.None);
  111. Task.WaitAll(task);
  112. }
  113. public async Task<object> Post(GetPostedPlaybackInfo request)
  114. {
  115. var info = await GetPlaybackInfo(request.Id, request.UserId, request.MediaSourceId).ConfigureAwait(false);
  116. var authInfo = AuthorizationContext.GetAuthorizationInfo(Request);
  117. var profile = request.DeviceProfile;
  118. if (profile == null)
  119. {
  120. var caps = _deviceManager.GetCapabilities(authInfo.DeviceId);
  121. if (caps != null)
  122. {
  123. profile = caps.DeviceProfile;
  124. }
  125. }
  126. if (profile != null)
  127. {
  128. var mediaSourceId = request.MediaSourceId;
  129. SetDeviceSpecificData(request.Id, info, profile, authInfo, request.MaxStreamingBitrate, request.StartTimeTicks ?? 0, mediaSourceId, request.AudioStreamIndex, request.SubtitleStreamIndex);
  130. }
  131. return ToOptimizedResult(info);
  132. }
  133. private async Task<PlaybackInfoResponse> GetPlaybackInfo(string id, string userId, string mediaSourceId = null)
  134. {
  135. var result = new PlaybackInfoResponse();
  136. IEnumerable<MediaSourceInfo> mediaSources;
  137. try
  138. {
  139. mediaSources = await _mediaSourceManager.GetPlayackMediaSources(id, userId, true, CancellationToken.None).ConfigureAwait(false);
  140. }
  141. catch (PlaybackException ex)
  142. {
  143. mediaSources = new List<MediaSourceInfo>();
  144. result.ErrorCode = ex.ErrorCode;
  145. }
  146. result.MediaSources = mediaSources.ToList();
  147. if (!string.IsNullOrWhiteSpace(mediaSourceId))
  148. {
  149. result.MediaSources = result.MediaSources
  150. .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  151. .ToList();
  152. }
  153. if (result.MediaSources.Count == 0)
  154. {
  155. if (!result.ErrorCode.HasValue)
  156. {
  157. result.ErrorCode = PlaybackErrorCode.NoCompatibleStream;
  158. }
  159. }
  160. else
  161. {
  162. result.StreamId = Guid.NewGuid().ToString("N");
  163. }
  164. return result;
  165. }
  166. private void SetDeviceSpecificData(string itemId,
  167. PlaybackInfoResponse result,
  168. DeviceProfile profile,
  169. AuthorizationInfo auth,
  170. int? maxBitrate,
  171. long startTimeTicks,
  172. string mediaSourceId,
  173. int? audioStreamIndex,
  174. int? subtitleStreamIndex)
  175. {
  176. var item = _libraryManager.GetItemById(itemId);
  177. foreach (var mediaSource in result.MediaSources)
  178. {
  179. SetDeviceSpecificData(item, mediaSource, profile, auth, maxBitrate, startTimeTicks, mediaSourceId, audioStreamIndex, subtitleStreamIndex);
  180. }
  181. SortMediaSources(result);
  182. }
  183. private void SetDeviceSpecificData(BaseItem item,
  184. MediaSourceInfo mediaSource,
  185. DeviceProfile profile,
  186. AuthorizationInfo auth,
  187. int? maxBitrate,
  188. long startTimeTicks,
  189. string mediaSourceId,
  190. int? audioStreamIndex,
  191. int? subtitleStreamIndex)
  192. {
  193. var streamBuilder = new StreamBuilder();
  194. var options = new VideoOptions
  195. {
  196. MediaSources = new List<MediaSourceInfo> { mediaSource },
  197. Context = EncodingContext.Streaming,
  198. DeviceId = auth.DeviceId,
  199. ItemId = item.Id.ToString("N"),
  200. Profile = profile,
  201. MaxBitrate = maxBitrate
  202. };
  203. if (string.Equals(mediaSourceId, mediaSource.Id, StringComparison.OrdinalIgnoreCase))
  204. {
  205. options.MediaSourceId = mediaSourceId;
  206. options.AudioStreamIndex = audioStreamIndex;
  207. options.SubtitleStreamIndex = subtitleStreamIndex;
  208. }
  209. if (mediaSource.SupportsDirectPlay)
  210. {
  211. var supportsDirectStream = mediaSource.SupportsDirectStream;
  212. // Dummy this up to fool StreamBuilder
  213. mediaSource.SupportsDirectStream = true;
  214. // The MediaSource supports direct stream, now test to see if the client supports it
  215. var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
  216. streamBuilder.BuildAudioItem(options) :
  217. streamBuilder.BuildVideoItem(options);
  218. if (streamInfo == null || !streamInfo.IsDirectStream)
  219. {
  220. mediaSource.SupportsDirectPlay = false;
  221. }
  222. // Set this back to what it was
  223. mediaSource.SupportsDirectStream = supportsDirectStream;
  224. }
  225. if (mediaSource.SupportsDirectStream)
  226. {
  227. // The MediaSource supports direct stream, now test to see if the client supports it
  228. var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
  229. streamBuilder.BuildAudioItem(options) :
  230. streamBuilder.BuildVideoItem(options);
  231. if (streamInfo == null || !streamInfo.IsDirectStream)
  232. {
  233. mediaSource.SupportsDirectStream = false;
  234. }
  235. }
  236. if (mediaSource.SupportsTranscoding)
  237. {
  238. // The MediaSource supports direct stream, now test to see if the client supports it
  239. var streamInfo = string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase) ?
  240. streamBuilder.BuildAudioItem(options) :
  241. streamBuilder.BuildVideoItem(options);
  242. if (streamInfo != null && streamInfo.PlayMethod == PlayMethod.Transcode)
  243. {
  244. streamInfo.StartPositionTicks = startTimeTicks;
  245. mediaSource.TranscodingUrl = streamInfo.ToUrl("-", auth.Token).Substring(1);
  246. mediaSource.TranscodingContainer = streamInfo.Container;
  247. mediaSource.TranscodingSubProtocol = streamInfo.SubProtocol;
  248. }
  249. }
  250. }
  251. private void SortMediaSources(PlaybackInfoResponse result)
  252. {
  253. var originalList = result.MediaSources.ToList();
  254. result.MediaSources = result.MediaSources.OrderBy(i =>
  255. {
  256. // Nothing beats direct playing a file
  257. if (i.SupportsDirectPlay && i.Protocol == MediaProtocol.File)
  258. {
  259. return 0;
  260. }
  261. return 1;
  262. }).ThenBy(i =>
  263. {
  264. // Let's assume direct streaming a file is just as desirable as direct playing a remote url
  265. if (i.SupportsDirectPlay || i.SupportsDirectStream)
  266. {
  267. return 0;
  268. }
  269. return 1;
  270. }).ThenBy(i =>
  271. {
  272. switch (i.Protocol)
  273. {
  274. case MediaProtocol.File:
  275. return 0;
  276. default:
  277. return 1;
  278. }
  279. }).ThenBy(originalList.IndexOf)
  280. .ToList();
  281. }
  282. }
  283. }