UniversalAudioService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Api.Playback.Hls;
  7. using MediaBrowser.Api.Playback.Progressive;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.Devices;
  11. using MediaBrowser.Controller.Dlna;
  12. using MediaBrowser.Controller.Drawing;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Controller.Net;
  16. using MediaBrowser.Model.Dlna;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.MediaInfo;
  19. using MediaBrowser.Model.Serialization;
  20. using MediaBrowser.Model.Services;
  21. using MediaBrowser.Model.System;
  22. namespace MediaBrowser.Api.Playback
  23. {
  24. public class BaseUniversalRequest
  25. {
  26. /// <summary>
  27. /// Gets or sets the id.
  28. /// </summary>
  29. /// <value>The id.</value>
  30. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  31. public string Id { get; set; }
  32. [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  33. public string MediaSourceId { get; set; }
  34. [ApiMember(Name = "DeviceId", Description = "The device id of the client requesting. Used to stop encoding processes when needed.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  35. public string DeviceId { get; set; }
  36. public string UserId { get; set; }
  37. public string AudioCodec { get; set; }
  38. public string Container { get; set; }
  39. public int? MaxAudioChannels { get; set; }
  40. public int? TranscodingAudioChannels { get; set; }
  41. public long? MaxStreamingBitrate { get; set; }
  42. [ApiMember(Name = "StartTimeTicks", Description = "Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  43. public long? StartTimeTicks { get; set; }
  44. public string TranscodingContainer { get; set; }
  45. public string TranscodingProtocol { get; set; }
  46. public int? MaxAudioSampleRate { get; set; }
  47. public int? MaxAudioBitDepth { get; set; }
  48. public bool EnableRedirection { get; set; }
  49. public bool EnableRemoteMedia { get; set; }
  50. public bool BreakOnNonKeyFrames { get; set; }
  51. public BaseUniversalRequest()
  52. {
  53. EnableRedirection = true;
  54. }
  55. }
  56. [Route("/Audio/{Id}/universal.{Container}", "GET", Summary = "Gets an audio stream")]
  57. [Route("/Audio/{Id}/universal", "GET", Summary = "Gets an audio stream")]
  58. [Route("/Audio/{Id}/universal.{Container}", "HEAD", Summary = "Gets an audio stream")]
  59. [Route("/Audio/{Id}/universal", "HEAD", Summary = "Gets an audio stream")]
  60. public class GetUniversalAudioStream : BaseUniversalRequest
  61. {
  62. }
  63. [Authenticated]
  64. public class UniversalAudioService : BaseApiService
  65. {
  66. public UniversalAudioService(IServerConfigurationManager serverConfigurationManager, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, IDeviceManager deviceManager, ISubtitleEncoder subtitleEncoder, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext, IImageProcessor imageProcessor, INetworkManager networkManager, IEnvironmentInfo environmentInfo)
  67. {
  68. ServerConfigurationManager = serverConfigurationManager;
  69. UserManager = userManager;
  70. LibraryManager = libraryManager;
  71. IsoManager = isoManager;
  72. MediaEncoder = mediaEncoder;
  73. FileSystem = fileSystem;
  74. DlnaManager = dlnaManager;
  75. DeviceManager = deviceManager;
  76. SubtitleEncoder = subtitleEncoder;
  77. MediaSourceManager = mediaSourceManager;
  78. ZipClient = zipClient;
  79. JsonSerializer = jsonSerializer;
  80. AuthorizationContext = authorizationContext;
  81. ImageProcessor = imageProcessor;
  82. NetworkManager = networkManager;
  83. EnvironmentInfo = environmentInfo;
  84. }
  85. protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
  86. protected IUserManager UserManager { get; private set; }
  87. protected ILibraryManager LibraryManager { get; private set; }
  88. protected IIsoManager IsoManager { get; private set; }
  89. protected IMediaEncoder MediaEncoder { get; private set; }
  90. protected IFileSystem FileSystem { get; private set; }
  91. protected IDlnaManager DlnaManager { get; private set; }
  92. protected IDeviceManager DeviceManager { get; private set; }
  93. protected ISubtitleEncoder SubtitleEncoder { get; private set; }
  94. protected IMediaSourceManager MediaSourceManager { get; private set; }
  95. protected IZipClient ZipClient { get; private set; }
  96. protected IJsonSerializer JsonSerializer { get; private set; }
  97. protected IAuthorizationContext AuthorizationContext { get; private set; }
  98. protected IImageProcessor ImageProcessor { get; private set; }
  99. protected INetworkManager NetworkManager { get; private set; }
  100. protected IEnvironmentInfo EnvironmentInfo { get; private set; }
  101. public Task<object> Get(GetUniversalAudioStream request)
  102. {
  103. return GetUniversalStream(request, false);
  104. }
  105. public Task<object> Head(GetUniversalAudioStream request)
  106. {
  107. return GetUniversalStream(request, true);
  108. }
  109. private DeviceProfile GetDeviceProfile(GetUniversalAudioStream request)
  110. {
  111. var deviceProfile = new DeviceProfile();
  112. var directPlayProfiles = new List<DirectPlayProfile>();
  113. directPlayProfiles.Add(new DirectPlayProfile
  114. {
  115. Type = DlnaProfileType.Audio,
  116. Container = request.Container
  117. });
  118. deviceProfile.DirectPlayProfiles = directPlayProfiles.ToArray();
  119. deviceProfile.TranscodingProfiles = new[]
  120. {
  121. new TranscodingProfile
  122. {
  123. Type = DlnaProfileType.Audio,
  124. Context = EncodingContext.Streaming,
  125. Container = request.TranscodingContainer,
  126. AudioCodec = request.AudioCodec,
  127. Protocol = request.TranscodingProtocol,
  128. BreakOnNonKeyFrames = request.BreakOnNonKeyFrames,
  129. MaxAudioChannels = request.TranscodingAudioChannels.HasValue ? request.TranscodingAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : null
  130. }
  131. };
  132. var codecProfiles = new List<CodecProfile>();
  133. var conditions = new List<ProfileCondition>();
  134. if (request.MaxAudioSampleRate.HasValue)
  135. {
  136. // codec profile
  137. conditions.Add(new ProfileCondition
  138. {
  139. Condition = ProfileConditionType.LessThanEqual,
  140. IsRequired = false,
  141. Property = ProfileConditionValue.AudioSampleRate,
  142. Value = request.MaxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)
  143. });
  144. }
  145. if (request.MaxAudioBitDepth.HasValue)
  146. {
  147. // codec profile
  148. conditions.Add(new ProfileCondition
  149. {
  150. Condition = ProfileConditionType.LessThanEqual,
  151. IsRequired = false,
  152. Property = ProfileConditionValue.AudioBitDepth,
  153. Value = request.MaxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture)
  154. });
  155. }
  156. if (request.MaxAudioChannels.HasValue)
  157. {
  158. // codec profile
  159. conditions.Add(new ProfileCondition
  160. {
  161. Condition = ProfileConditionType.LessThanEqual,
  162. IsRequired = false,
  163. Property = ProfileConditionValue.AudioChannels,
  164. Value = request.MaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture)
  165. });
  166. }
  167. if (conditions.Count > 0)
  168. {
  169. // codec profile
  170. codecProfiles.Add(new CodecProfile
  171. {
  172. Type = CodecType.Audio,
  173. Container = request.Container,
  174. Conditions = conditions.ToArray()
  175. });
  176. }
  177. deviceProfile.CodecProfiles = codecProfiles.ToArray();
  178. return deviceProfile;
  179. }
  180. private async Task<object> GetUniversalStream(GetUniversalAudioStream request, bool isHeadRequest)
  181. {
  182. var deviceProfile = GetDeviceProfile(request);
  183. AuthorizationContext.GetAuthorizationInfo(Request).DeviceId = request.DeviceId;
  184. var mediaInfoService = new MediaInfoService(MediaSourceManager, DeviceManager, LibraryManager, ServerConfigurationManager, NetworkManager, MediaEncoder, UserManager, JsonSerializer, AuthorizationContext)
  185. {
  186. Request = Request
  187. };
  188. var playbackInfoResult = await mediaInfoService.GetPlaybackInfo(new GetPostedPlaybackInfo
  189. {
  190. Id = request.Id,
  191. MaxAudioChannels = request.MaxAudioChannels,
  192. MaxStreamingBitrate = request.MaxStreamingBitrate,
  193. StartTimeTicks = request.StartTimeTicks,
  194. UserId = request.UserId,
  195. DeviceProfile = deviceProfile,
  196. MediaSourceId = request.MediaSourceId
  197. }).ConfigureAwait(false);
  198. var mediaSource = playbackInfoResult.MediaSources[0];
  199. if (mediaSource.SupportsDirectPlay && mediaSource.Protocol == MediaProtocol.Http)
  200. {
  201. if (request.EnableRedirection)
  202. {
  203. if (mediaSource.IsRemote && request.EnableRemoteMedia)
  204. {
  205. return ResultFactory.GetRedirectResult(mediaSource.Path);
  206. }
  207. }
  208. }
  209. var isStatic = mediaSource.SupportsDirectStream;
  210. if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
  211. {
  212. var service = new DynamicHlsService(ServerConfigurationManager,
  213. UserManager,
  214. LibraryManager,
  215. IsoManager,
  216. MediaEncoder,
  217. FileSystem,
  218. DlnaManager,
  219. SubtitleEncoder,
  220. DeviceManager,
  221. MediaSourceManager,
  222. ZipClient,
  223. JsonSerializer,
  224. AuthorizationContext,
  225. NetworkManager)
  226. {
  227. Request = Request
  228. };
  229. var transcodingProfile = deviceProfile.TranscodingProfiles[0];
  230. var newRequest = new GetMasterHlsAudioPlaylist
  231. {
  232. AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
  233. AudioCodec = transcodingProfile.AudioCodec,
  234. Container = ".m3u8",
  235. DeviceId = request.DeviceId,
  236. Id = request.Id,
  237. MaxAudioChannels = request.MaxAudioChannels,
  238. MediaSourceId = mediaSource.Id,
  239. PlaySessionId = playbackInfoResult.PlaySessionId,
  240. StartTimeTicks = request.StartTimeTicks,
  241. Static = isStatic,
  242. SegmentContainer = request.TranscodingContainer,
  243. AudioSampleRate = request.MaxAudioSampleRate,
  244. MaxAudioBitDepth = request.MaxAudioBitDepth,
  245. BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames,
  246. TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray())
  247. };
  248. if (isHeadRequest)
  249. {
  250. return await service.Head(newRequest).ConfigureAwait(false);
  251. }
  252. return await service.Get(newRequest).ConfigureAwait(false);
  253. }
  254. else
  255. {
  256. var service = new AudioService(ServerConfigurationManager,
  257. UserManager,
  258. LibraryManager,
  259. IsoManager,
  260. MediaEncoder,
  261. FileSystem,
  262. DlnaManager,
  263. SubtitleEncoder,
  264. DeviceManager,
  265. MediaSourceManager,
  266. ZipClient,
  267. JsonSerializer,
  268. AuthorizationContext,
  269. ImageProcessor,
  270. EnvironmentInfo)
  271. {
  272. Request = Request
  273. };
  274. var newRequest = new GetAudioStream
  275. {
  276. AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
  277. AudioCodec = request.AudioCodec,
  278. Container = isStatic ? null : ("." + mediaSource.TranscodingContainer),
  279. DeviceId = request.DeviceId,
  280. Id = request.Id,
  281. MaxAudioChannels = request.MaxAudioChannels,
  282. MediaSourceId = mediaSource.Id,
  283. PlaySessionId = playbackInfoResult.PlaySessionId,
  284. StartTimeTicks = request.StartTimeTicks,
  285. Static = isStatic,
  286. AudioSampleRate = request.MaxAudioSampleRate,
  287. MaxAudioBitDepth = request.MaxAudioBitDepth,
  288. TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray())
  289. };
  290. if (isHeadRequest)
  291. {
  292. return await service.Head(newRequest).ConfigureAwait(false);
  293. }
  294. return await service.Get(newRequest).ConfigureAwait(false);
  295. }
  296. }
  297. }
  298. }