UniversalAudioService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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.Library;
  13. using MediaBrowser.Controller.MediaEncoding;
  14. using MediaBrowser.Controller.Net;
  15. using MediaBrowser.Model.Dlna;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.MediaInfo;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Model.Services;
  20. using Microsoft.Extensions.Logging;
  21. namespace MediaBrowser.Api.Playback
  22. {
  23. public class BaseUniversalRequest
  24. {
  25. /// <summary>
  26. /// Gets or sets the id.
  27. /// </summary>
  28. /// <value>The id.</value>
  29. [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  30. public Guid Id { get; set; }
  31. [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
  32. public string MediaSourceId { get; set; }
  33. [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")]
  34. public string DeviceId { get; set; }
  35. public Guid UserId { get; set; }
  36. public string AudioCodec { get; set; }
  37. public string Container { get; set; }
  38. public int? MaxAudioChannels { get; set; }
  39. public int? TranscodingAudioChannels { get; set; }
  40. public long? MaxStreamingBitrate { 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 = "GET")]
  42. public long? StartTimeTicks { get; set; }
  43. public string TranscodingContainer { get; set; }
  44. public string TranscodingProtocol { get; set; }
  45. public int? MaxAudioSampleRate { get; set; }
  46. public int? MaxAudioBitDepth { get; set; }
  47. public bool EnableRedirection { get; set; }
  48. public bool EnableRemoteMedia { get; set; }
  49. public bool BreakOnNonKeyFrames { get; set; }
  50. public BaseUniversalRequest()
  51. {
  52. EnableRedirection = true;
  53. }
  54. }
  55. [Route("/Audio/{Id}/universal.{Container}", "GET", Summary = "Gets an audio stream")]
  56. [Route("/Audio/{Id}/universal", "GET", Summary = "Gets an audio stream")]
  57. [Route("/Audio/{Id}/universal.{Container}", "HEAD", Summary = "Gets an audio stream")]
  58. [Route("/Audio/{Id}/universal", "HEAD", Summary = "Gets an audio stream")]
  59. public class GetUniversalAudioStream : BaseUniversalRequest
  60. {
  61. }
  62. [Authenticated]
  63. public class UniversalAudioService : BaseApiService
  64. {
  65. private readonly EncodingHelper _encodingHelper;
  66. public UniversalAudioService(
  67. ILogger<UniversalAudioService> logger,
  68. IServerConfigurationManager serverConfigurationManager,
  69. IHttpResultFactory httpResultFactory,
  70. IHttpClient httpClient,
  71. IUserManager userManager,
  72. ILibraryManager libraryManager,
  73. IIsoManager isoManager,
  74. IMediaEncoder mediaEncoder,
  75. IFileSystem fileSystem,
  76. IDlnaManager dlnaManager,
  77. IDeviceManager deviceManager,
  78. IMediaSourceManager mediaSourceManager,
  79. IJsonSerializer jsonSerializer,
  80. IAuthorizationContext authorizationContext,
  81. INetworkManager networkManager,
  82. EncodingHelper encodingHelper)
  83. : base(logger, serverConfigurationManager, httpResultFactory)
  84. {
  85. HttpClient = httpClient;
  86. UserManager = userManager;
  87. LibraryManager = libraryManager;
  88. IsoManager = isoManager;
  89. MediaEncoder = mediaEncoder;
  90. FileSystem = fileSystem;
  91. DlnaManager = dlnaManager;
  92. DeviceManager = deviceManager;
  93. MediaSourceManager = mediaSourceManager;
  94. JsonSerializer = jsonSerializer;
  95. AuthorizationContext = authorizationContext;
  96. NetworkManager = networkManager;
  97. _encodingHelper = encodingHelper;
  98. }
  99. protected IHttpClient HttpClient { get; private set; }
  100. protected IUserManager UserManager { get; private set; }
  101. protected ILibraryManager LibraryManager { get; private set; }
  102. protected IIsoManager IsoManager { get; private set; }
  103. protected IMediaEncoder MediaEncoder { get; private set; }
  104. protected IFileSystem FileSystem { get; private set; }
  105. protected IDlnaManager DlnaManager { get; private set; }
  106. protected IDeviceManager DeviceManager { get; private set; }
  107. protected IMediaSourceManager MediaSourceManager { get; private set; }
  108. protected IJsonSerializer JsonSerializer { get; private set; }
  109. protected IAuthorizationContext AuthorizationContext { get; private set; }
  110. protected INetworkManager NetworkManager { get; private set; }
  111. public Task<object> Get(GetUniversalAudioStream request)
  112. {
  113. return GetUniversalStream(request, false);
  114. }
  115. public Task<object> Head(GetUniversalAudioStream request)
  116. {
  117. return GetUniversalStream(request, true);
  118. }
  119. private DeviceProfile GetDeviceProfile(GetUniversalAudioStream request)
  120. {
  121. var deviceProfile = new DeviceProfile();
  122. var directPlayProfiles = new List<DirectPlayProfile>();
  123. var containers = (request.Container ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  124. foreach (var container in containers)
  125. {
  126. var parts = container.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
  127. var audioCodecs = parts.Length == 1 ? null : string.Join(",", parts.Skip(1).ToArray());
  128. directPlayProfiles.Add(new DirectPlayProfile
  129. {
  130. Type = DlnaProfileType.Audio,
  131. Container = parts[0],
  132. AudioCodec = audioCodecs
  133. });
  134. }
  135. deviceProfile.DirectPlayProfiles = directPlayProfiles.ToArray();
  136. deviceProfile.TranscodingProfiles = new[]
  137. {
  138. new TranscodingProfile
  139. {
  140. Type = DlnaProfileType.Audio,
  141. Context = EncodingContext.Streaming,
  142. Container = request.TranscodingContainer,
  143. AudioCodec = request.AudioCodec,
  144. Protocol = request.TranscodingProtocol,
  145. BreakOnNonKeyFrames = request.BreakOnNonKeyFrames,
  146. MaxAudioChannels = request.TranscodingAudioChannels.HasValue ? request.TranscodingAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : null
  147. }
  148. };
  149. var codecProfiles = new List<CodecProfile>();
  150. var conditions = new List<ProfileCondition>();
  151. if (request.MaxAudioSampleRate.HasValue)
  152. {
  153. // codec profile
  154. conditions.Add(new ProfileCondition
  155. {
  156. Condition = ProfileConditionType.LessThanEqual,
  157. IsRequired = false,
  158. Property = ProfileConditionValue.AudioSampleRate,
  159. Value = request.MaxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)
  160. });
  161. }
  162. if (request.MaxAudioBitDepth.HasValue)
  163. {
  164. // codec profile
  165. conditions.Add(new ProfileCondition
  166. {
  167. Condition = ProfileConditionType.LessThanEqual,
  168. IsRequired = false,
  169. Property = ProfileConditionValue.AudioBitDepth,
  170. Value = request.MaxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture)
  171. });
  172. }
  173. if (request.MaxAudioChannels.HasValue)
  174. {
  175. // codec profile
  176. conditions.Add(new ProfileCondition
  177. {
  178. Condition = ProfileConditionType.LessThanEqual,
  179. IsRequired = false,
  180. Property = ProfileConditionValue.AudioChannels,
  181. Value = request.MaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture)
  182. });
  183. }
  184. if (conditions.Count > 0)
  185. {
  186. // codec profile
  187. codecProfiles.Add(new CodecProfile
  188. {
  189. Type = CodecType.Audio,
  190. Container = request.Container,
  191. Conditions = conditions.ToArray()
  192. });
  193. }
  194. deviceProfile.CodecProfiles = codecProfiles.ToArray();
  195. return deviceProfile;
  196. }
  197. private async Task<object> GetUniversalStream(GetUniversalAudioStream request, bool isHeadRequest)
  198. {
  199. var deviceProfile = GetDeviceProfile(request);
  200. AuthorizationContext.GetAuthorizationInfo(Request).DeviceId = request.DeviceId;
  201. var mediaInfoService = new MediaInfoService(
  202. Logger,
  203. ServerConfigurationManager,
  204. ResultFactory,
  205. MediaSourceManager,
  206. DeviceManager,
  207. LibraryManager,
  208. NetworkManager,
  209. MediaEncoder,
  210. UserManager,
  211. AuthorizationContext)
  212. {
  213. Request = Request
  214. };
  215. var playbackInfoResult = await mediaInfoService.GetPlaybackInfo(new GetPostedPlaybackInfo
  216. {
  217. Id = request.Id,
  218. MaxAudioChannels = request.MaxAudioChannels,
  219. MaxStreamingBitrate = request.MaxStreamingBitrate,
  220. StartTimeTicks = request.StartTimeTicks,
  221. UserId = request.UserId,
  222. DeviceProfile = deviceProfile,
  223. MediaSourceId = request.MediaSourceId
  224. }).ConfigureAwait(false);
  225. var mediaSource = playbackInfoResult.MediaSources[0];
  226. if (mediaSource.SupportsDirectPlay && mediaSource.Protocol == MediaProtocol.Http)
  227. {
  228. if (request.EnableRedirection)
  229. {
  230. if (mediaSource.IsRemote && request.EnableRemoteMedia)
  231. {
  232. return ResultFactory.GetRedirectResult(mediaSource.Path);
  233. }
  234. }
  235. }
  236. var isStatic = mediaSource.SupportsDirectStream;
  237. if (!isStatic && string.Equals(mediaSource.TranscodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase))
  238. {
  239. var service = new DynamicHlsService(
  240. Logger,
  241. ServerConfigurationManager,
  242. ResultFactory,
  243. UserManager,
  244. LibraryManager,
  245. IsoManager,
  246. MediaEncoder,
  247. FileSystem,
  248. DlnaManager,
  249. DeviceManager,
  250. MediaSourceManager,
  251. JsonSerializer,
  252. AuthorizationContext,
  253. NetworkManager,
  254. _encodingHelper)
  255. {
  256. Request = Request
  257. };
  258. var transcodingProfile = deviceProfile.TranscodingProfiles[0];
  259. // hls segment container can only be mpegts or fmp4 per ffmpeg documentation
  260. // TODO: remove this when we switch back to the segment muxer
  261. var supportedHLSContainers = new string[] { "mpegts", "fmp4" };
  262. var newRequest = new GetMasterHlsAudioPlaylist
  263. {
  264. AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
  265. AudioCodec = transcodingProfile.AudioCodec,
  266. Container = ".m3u8",
  267. DeviceId = request.DeviceId,
  268. Id = request.Id,
  269. MaxAudioChannels = request.MaxAudioChannels,
  270. MediaSourceId = mediaSource.Id,
  271. PlaySessionId = playbackInfoResult.PlaySessionId,
  272. StartTimeTicks = request.StartTimeTicks,
  273. Static = isStatic,
  274. // fallback to mpegts if device reports some weird value unsupported by hls
  275. SegmentContainer = Array.Exists(supportedHLSContainers, element => element == request.TranscodingContainer) ? request.TranscodingContainer : "mpegts",
  276. AudioSampleRate = request.MaxAudioSampleRate,
  277. MaxAudioBitDepth = request.MaxAudioBitDepth,
  278. BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames,
  279. TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray())
  280. };
  281. if (isHeadRequest)
  282. {
  283. return await service.Head(newRequest).ConfigureAwait(false);
  284. }
  285. return await service.Get(newRequest).ConfigureAwait(false);
  286. }
  287. else
  288. {
  289. var service = new AudioService(
  290. Logger,
  291. ServerConfigurationManager,
  292. ResultFactory,
  293. HttpClient,
  294. UserManager,
  295. LibraryManager,
  296. IsoManager,
  297. MediaEncoder,
  298. FileSystem,
  299. DlnaManager,
  300. DeviceManager,
  301. MediaSourceManager,
  302. JsonSerializer,
  303. AuthorizationContext,
  304. _encodingHelper)
  305. {
  306. Request = Request
  307. };
  308. var newRequest = new GetAudioStream
  309. {
  310. AudioBitRate = isStatic ? (int?)null : Convert.ToInt32(Math.Min(request.MaxStreamingBitrate ?? 192000, int.MaxValue)),
  311. AudioCodec = request.AudioCodec,
  312. Container = isStatic ? null : ("." + mediaSource.TranscodingContainer),
  313. DeviceId = request.DeviceId,
  314. Id = request.Id,
  315. MaxAudioChannels = request.MaxAudioChannels,
  316. MediaSourceId = mediaSource.Id,
  317. PlaySessionId = playbackInfoResult.PlaySessionId,
  318. StartTimeTicks = request.StartTimeTicks,
  319. Static = isStatic,
  320. AudioSampleRate = request.MaxAudioSampleRate,
  321. MaxAudioBitDepth = request.MaxAudioBitDepth,
  322. TranscodeReasons = mediaSource.TranscodeReasons == null ? null : string.Join(",", mediaSource.TranscodeReasons.Select(i => i.ToString()).ToArray())
  323. };
  324. if (isHeadRequest)
  325. {
  326. return await service.Head(newRequest).ConfigureAwait(false);
  327. }
  328. return await service.Get(newRequest).ConfigureAwait(false);
  329. }
  330. }
  331. }
  332. }