UniversalAudioController.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Api.Attributes;
  8. using Jellyfin.Api.Helpers;
  9. using Jellyfin.Api.ModelBinders;
  10. using Jellyfin.Api.Models.StreamingDtos;
  11. using Jellyfin.Data.Enums;
  12. using Jellyfin.Extensions;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Entities;
  15. using MediaBrowser.Controller.Library;
  16. using MediaBrowser.Controller.MediaEncoding;
  17. using MediaBrowser.Controller.Streaming;
  18. using MediaBrowser.Model.Dlna;
  19. using MediaBrowser.Model.MediaInfo;
  20. using MediaBrowser.Model.Session;
  21. using Microsoft.AspNetCore.Authorization;
  22. using Microsoft.AspNetCore.Http;
  23. using Microsoft.AspNetCore.Mvc;
  24. using Microsoft.Extensions.Logging;
  25. namespace Jellyfin.Api.Controllers;
  26. /// <summary>
  27. /// The universal audio controller.
  28. /// </summary>
  29. [Route("")]
  30. public class UniversalAudioController : BaseJellyfinApiController
  31. {
  32. private readonly ILibraryManager _libraryManager;
  33. private readonly ILogger<UniversalAudioController> _logger;
  34. private readonly MediaInfoHelper _mediaInfoHelper;
  35. private readonly AudioHelper _audioHelper;
  36. private readonly DynamicHlsHelper _dynamicHlsHelper;
  37. private readonly IUserManager _userManager;
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="UniversalAudioController"/> class.
  40. /// </summary>
  41. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  42. /// <param name="logger">Instance of the <see cref="ILogger{UniversalAudioController}"/> interface.</param>
  43. /// <param name="mediaInfoHelper">Instance of <see cref="MediaInfoHelper"/>.</param>
  44. /// <param name="audioHelper">Instance of <see cref="AudioHelper"/>.</param>
  45. /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
  46. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  47. public UniversalAudioController(
  48. ILibraryManager libraryManager,
  49. ILogger<UniversalAudioController> logger,
  50. MediaInfoHelper mediaInfoHelper,
  51. AudioHelper audioHelper,
  52. DynamicHlsHelper dynamicHlsHelper,
  53. IUserManager userManager)
  54. {
  55. _libraryManager = libraryManager;
  56. _logger = logger;
  57. _mediaInfoHelper = mediaInfoHelper;
  58. _audioHelper = audioHelper;
  59. _dynamicHlsHelper = dynamicHlsHelper;
  60. _userManager = userManager;
  61. }
  62. /// <summary>
  63. /// Gets an audio stream.
  64. /// </summary>
  65. /// <param name="itemId">The item id.</param>
  66. /// <param name="container">Optional. The audio container.</param>
  67. /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
  68. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  69. /// <param name="userId">Optional. The user id.</param>
  70. /// <param name="audioCodec">Optional. The audio codec to transcode to.</param>
  71. /// <param name="maxAudioChannels">Optional. The maximum number of audio channels.</param>
  72. /// <param name="transcodingAudioChannels">Optional. The number of how many audio channels to transcode to.</param>
  73. /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
  74. /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be left to encoder defaults.</param>
  75. /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
  76. /// <param name="transcodingContainer">Optional. The container to transcode to.</param>
  77. /// <param name="transcodingProtocol">Optional. The transcoding protocol.</param>
  78. /// <param name="maxAudioSampleRate">Optional. The maximum audio sample rate.</param>
  79. /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
  80. /// <param name="enableRemoteMedia">Optional. Whether to enable remote media.</param>
  81. /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
  82. /// <param name="enableRedirection">Whether to enable redirection. Defaults to true.</param>
  83. /// <response code="200">Audio stream returned.</response>
  84. /// <response code="302">Redirected to remote audio stream.</response>
  85. /// <response code="404">Item not found.</response>
  86. /// <returns>A <see cref="Task"/> containing the audio file.</returns>
  87. [HttpGet("Audio/{itemId}/universal")]
  88. [HttpHead("Audio/{itemId}/universal", Name = "HeadUniversalAudioStream")]
  89. [Authorize]
  90. [ProducesResponseType(StatusCodes.Status200OK)]
  91. [ProducesResponseType(StatusCodes.Status302Found)]
  92. [ProducesResponseType(StatusCodes.Status404NotFound)]
  93. [ProducesAudioFile]
  94. public async Task<ActionResult> GetUniversalAudioStream(
  95. [FromRoute, Required] Guid itemId,
  96. [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] container,
  97. [FromQuery] string? mediaSourceId,
  98. [FromQuery] string? deviceId,
  99. [FromQuery] Guid? userId,
  100. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? audioCodec,
  101. [FromQuery] int? maxAudioChannels,
  102. [FromQuery] int? transcodingAudioChannels,
  103. [FromQuery] int? maxStreamingBitrate,
  104. [FromQuery] int? audioBitRate,
  105. [FromQuery] long? startTimeTicks,
  106. [FromQuery] [RegularExpression(EncodingHelper.ValidationRegex)] string? transcodingContainer,
  107. [FromQuery] MediaStreamProtocol? transcodingProtocol,
  108. [FromQuery] int? maxAudioSampleRate,
  109. [FromQuery] int? maxAudioBitDepth,
  110. [FromQuery] bool? enableRemoteMedia,
  111. [FromQuery] bool breakOnNonKeyFrames = false,
  112. [FromQuery] bool enableRedirection = true)
  113. {
  114. userId = RequestHelpers.GetUserId(User, userId);
  115. var user = userId.IsNullOrEmpty()
  116. ? null
  117. : _userManager.GetUserById(userId.Value);
  118. var item = _libraryManager.GetItemById<BaseItem>(itemId, user);
  119. if (item is null)
  120. {
  121. return NotFound();
  122. }
  123. var deviceProfile = GetDeviceProfile(container, transcodingContainer, audioCodec, transcodingProtocol, breakOnNonKeyFrames, transcodingAudioChannels, maxAudioSampleRate, maxAudioBitDepth, maxAudioChannels);
  124. _logger.LogInformation("GetPostedPlaybackInfo profile: {@Profile}", deviceProfile);
  125. var info = await _mediaInfoHelper.GetPlaybackInfo(
  126. item,
  127. user,
  128. mediaSourceId)
  129. .ConfigureAwait(false);
  130. // set device specific data
  131. foreach (var sourceInfo in info.MediaSources)
  132. {
  133. sourceInfo.TranscodingContainer = transcodingContainer;
  134. sourceInfo.TranscodingSubProtocol = transcodingProtocol ?? sourceInfo.TranscodingSubProtocol;
  135. _mediaInfoHelper.SetDeviceSpecificData(
  136. item,
  137. sourceInfo,
  138. deviceProfile,
  139. User,
  140. maxStreamingBitrate ?? deviceProfile.MaxStreamingBitrate,
  141. startTimeTicks ?? 0,
  142. mediaSourceId ?? string.Empty,
  143. null,
  144. null,
  145. maxAudioChannels,
  146. info.PlaySessionId!,
  147. userId ?? Guid.Empty,
  148. true,
  149. true,
  150. true,
  151. true,
  152. true,
  153. Request.HttpContext.GetNormalizedRemoteIP());
  154. }
  155. _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);
  156. foreach (var source in info.MediaSources)
  157. {
  158. _mediaInfoHelper.NormalizeMediaSourceContainer(source, deviceProfile, DlnaProfileType.Video);
  159. }
  160. var mediaSource = info.MediaSources[0];
  161. if (mediaSource.SupportsDirectPlay && mediaSource.Protocol == MediaProtocol.Http && enableRedirection && mediaSource.IsRemote && enableRemoteMedia.HasValue && enableRemoteMedia.Value)
  162. {
  163. return Redirect(mediaSource.Path);
  164. }
  165. // This one is currently very misleading as the SupportsDirectStream is always false
  166. // The definition of DirectStream also seems changed during development
  167. // It used to mean HTTP direct streaming, but now HLS is used even for DirectStream
  168. var isStatic = mediaSource.SupportsDirectStream;
  169. if (mediaSource.TranscodingSubProtocol == MediaStreamProtocol.hls)
  170. {
  171. // hls segment container can only be mpegts or fmp4 per ffmpeg documentation
  172. // ffmpeg option -> file extension
  173. // mpegts -> ts
  174. // fmp4 -> mp4
  175. var supportedHlsContainers = new[] { "ts", "mp4" };
  176. // fallback to mpegts if device reports some weird value unsupported by hls
  177. var segmentContainer = Array.Exists(supportedHlsContainers, element => element == transcodingContainer) ? transcodingContainer : "ts";
  178. var dynamicHlsRequestDto = new HlsAudioRequestDto
  179. {
  180. Id = itemId,
  181. Container = ".m3u8",
  182. Static = isStatic,
  183. PlaySessionId = info.PlaySessionId,
  184. SegmentContainer = segmentContainer,
  185. MediaSourceId = mediaSourceId,
  186. DeviceId = deviceId,
  187. AudioCodec = mediaSource.TranscodeReasons == TranscodeReason.ContainerNotSupported ? "copy" : audioCodec,
  188. EnableAutoStreamCopy = true,
  189. AllowAudioStreamCopy = true,
  190. AllowVideoStreamCopy = true,
  191. BreakOnNonKeyFrames = breakOnNonKeyFrames,
  192. AudioSampleRate = maxAudioSampleRate,
  193. MaxAudioChannels = maxAudioChannels,
  194. MaxAudioBitDepth = maxAudioBitDepth,
  195. AudioBitRate = audioBitRate ?? maxStreamingBitrate,
  196. StartTimeTicks = startTimeTicks,
  197. SubtitleMethod = SubtitleDeliveryMethod.Hls,
  198. RequireAvc = false,
  199. DeInterlace = false,
  200. RequireNonAnamorphic = false,
  201. EnableMpegtsM2TsMode = false,
  202. TranscodeReasons = mediaSource.TranscodeReasons == 0 ? null : mediaSource.TranscodeReasons.ToString(),
  203. Context = EncodingContext.Static,
  204. StreamOptions = new Dictionary<string, string>(),
  205. EnableAdaptiveBitrateStreaming = true
  206. };
  207. return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType.Hls, dynamicHlsRequestDto, true)
  208. .ConfigureAwait(false);
  209. }
  210. var audioStreamingDto = new StreamingRequestDto
  211. {
  212. Id = itemId,
  213. Container = isStatic ? null : ("." + mediaSource.TranscodingContainer),
  214. Static = isStatic,
  215. PlaySessionId = info.PlaySessionId,
  216. MediaSourceId = mediaSourceId,
  217. DeviceId = deviceId,
  218. AudioCodec = audioCodec,
  219. EnableAutoStreamCopy = true,
  220. AllowAudioStreamCopy = true,
  221. AllowVideoStreamCopy = true,
  222. BreakOnNonKeyFrames = breakOnNonKeyFrames,
  223. AudioSampleRate = maxAudioSampleRate,
  224. MaxAudioChannels = maxAudioChannels,
  225. AudioBitRate = isStatic ? null : (audioBitRate ?? maxStreamingBitrate),
  226. MaxAudioBitDepth = maxAudioBitDepth,
  227. AudioChannels = maxAudioChannels,
  228. CopyTimestamps = true,
  229. StartTimeTicks = startTimeTicks,
  230. SubtitleMethod = SubtitleDeliveryMethod.Embed,
  231. TranscodeReasons = mediaSource.TranscodeReasons == 0 ? null : mediaSource.TranscodeReasons.ToString(),
  232. Context = EncodingContext.Static
  233. };
  234. return await _audioHelper.GetAudioStream(TranscodingJobType.Progressive, audioStreamingDto).ConfigureAwait(false);
  235. }
  236. private DeviceProfile GetDeviceProfile(
  237. string[] containers,
  238. string? transcodingContainer,
  239. string? audioCodec,
  240. MediaStreamProtocol? transcodingProtocol,
  241. bool? breakOnNonKeyFrames,
  242. int? transcodingAudioChannels,
  243. int? maxAudioSampleRate,
  244. int? maxAudioBitDepth,
  245. int? maxAudioChannels)
  246. {
  247. var deviceProfile = new DeviceProfile();
  248. int len = containers.Length;
  249. var directPlayProfiles = new DirectPlayProfile[len];
  250. for (int i = 0; i < len; i++)
  251. {
  252. var parts = containers[i].Split('|', StringSplitOptions.RemoveEmptyEntries);
  253. var audioCodecs = parts.Length == 1 ? null : string.Join(',', parts.Skip(1));
  254. directPlayProfiles[i] = new DirectPlayProfile
  255. {
  256. Type = DlnaProfileType.Audio,
  257. Container = parts[0],
  258. AudioCodec = audioCodecs
  259. };
  260. }
  261. deviceProfile.DirectPlayProfiles = directPlayProfiles;
  262. deviceProfile.TranscodingProfiles = new[]
  263. {
  264. new TranscodingProfile
  265. {
  266. Type = DlnaProfileType.Audio,
  267. Context = EncodingContext.Streaming,
  268. Container = transcodingContainer ?? "mp3",
  269. AudioCodec = audioCodec ?? "mp3",
  270. Protocol = transcodingProtocol ?? MediaStreamProtocol.http,
  271. BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
  272. MaxAudioChannels = transcodingAudioChannels?.ToString(CultureInfo.InvariantCulture)
  273. }
  274. };
  275. var codecProfiles = new List<CodecProfile>();
  276. var conditions = new List<ProfileCondition>();
  277. if (maxAudioSampleRate.HasValue)
  278. {
  279. // codec profile
  280. conditions.Add(
  281. new ProfileCondition
  282. {
  283. Condition = ProfileConditionType.LessThanEqual,
  284. IsRequired = false,
  285. Property = ProfileConditionValue.AudioSampleRate,
  286. Value = maxAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture)
  287. });
  288. }
  289. if (maxAudioBitDepth.HasValue)
  290. {
  291. // codec profile
  292. conditions.Add(
  293. new ProfileCondition
  294. {
  295. Condition = ProfileConditionType.LessThanEqual,
  296. IsRequired = false,
  297. Property = ProfileConditionValue.AudioBitDepth,
  298. Value = maxAudioBitDepth.Value.ToString(CultureInfo.InvariantCulture)
  299. });
  300. }
  301. if (maxAudioChannels.HasValue)
  302. {
  303. // codec profile
  304. conditions.Add(
  305. new ProfileCondition
  306. {
  307. Condition = ProfileConditionType.LessThanEqual,
  308. IsRequired = false,
  309. Property = ProfileConditionValue.AudioChannels,
  310. Value = maxAudioChannels.Value.ToString(CultureInfo.InvariantCulture)
  311. });
  312. }
  313. if (conditions.Count > 0)
  314. {
  315. // codec profile
  316. codecProfiles.Add(
  317. new CodecProfile
  318. {
  319. Type = CodecType.Audio,
  320. Container = string.Join(',', containers),
  321. Conditions = conditions.ToArray()
  322. });
  323. }
  324. deviceProfile.CodecProfiles = codecProfiles.ToArray();
  325. return deviceProfile;
  326. }
  327. }