DynamicHlsHelper.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Security.Claims;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Api.Extensions;
  11. using Jellyfin.Data.Entities;
  12. using Jellyfin.Data.Enums;
  13. using Jellyfin.Extensions;
  14. using MediaBrowser.Common.Configuration;
  15. using MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller.Configuration;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.MediaEncoding;
  20. using MediaBrowser.Controller.Streaming;
  21. using MediaBrowser.Controller.Trickplay;
  22. using MediaBrowser.Model.Dlna;
  23. using MediaBrowser.Model.Entities;
  24. using MediaBrowser.Model.Net;
  25. using Microsoft.AspNetCore.Http;
  26. using Microsoft.AspNetCore.Mvc;
  27. using Microsoft.Extensions.Logging;
  28. using Microsoft.Net.Http.Headers;
  29. namespace Jellyfin.Api.Helpers;
  30. /// <summary>
  31. /// Dynamic hls helper.
  32. /// </summary>
  33. public class DynamicHlsHelper
  34. {
  35. private readonly ILibraryManager _libraryManager;
  36. private readonly IUserManager _userManager;
  37. private readonly IMediaSourceManager _mediaSourceManager;
  38. private readonly IServerConfigurationManager _serverConfigurationManager;
  39. private readonly IMediaEncoder _mediaEncoder;
  40. private readonly ITranscodeManager _transcodeManager;
  41. private readonly INetworkManager _networkManager;
  42. private readonly ILogger<DynamicHlsHelper> _logger;
  43. private readonly IHttpContextAccessor _httpContextAccessor;
  44. private readonly EncodingHelper _encodingHelper;
  45. private readonly ITrickplayManager _trickplayManager;
  46. /// <summary>
  47. /// Initializes a new instance of the <see cref="DynamicHlsHelper"/> class.
  48. /// </summary>
  49. /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
  50. /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
  51. /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
  52. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  53. /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
  54. /// <param name="transcodeManager">Instance of <see cref="ITranscodeManager"/>.</param>
  55. /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
  56. /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsHelper}"/> interface.</param>
  57. /// <param name="httpContextAccessor">Instance of the <see cref="IHttpContextAccessor"/> interface.</param>
  58. /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
  59. /// <param name="trickplayManager">Instance of <see cref="ITrickplayManager"/>.</param>
  60. public DynamicHlsHelper(
  61. ILibraryManager libraryManager,
  62. IUserManager userManager,
  63. IMediaSourceManager mediaSourceManager,
  64. IServerConfigurationManager serverConfigurationManager,
  65. IMediaEncoder mediaEncoder,
  66. ITranscodeManager transcodeManager,
  67. INetworkManager networkManager,
  68. ILogger<DynamicHlsHelper> logger,
  69. IHttpContextAccessor httpContextAccessor,
  70. EncodingHelper encodingHelper,
  71. ITrickplayManager trickplayManager)
  72. {
  73. _libraryManager = libraryManager;
  74. _userManager = userManager;
  75. _mediaSourceManager = mediaSourceManager;
  76. _serverConfigurationManager = serverConfigurationManager;
  77. _mediaEncoder = mediaEncoder;
  78. _transcodeManager = transcodeManager;
  79. _networkManager = networkManager;
  80. _logger = logger;
  81. _httpContextAccessor = httpContextAccessor;
  82. _encodingHelper = encodingHelper;
  83. _trickplayManager = trickplayManager;
  84. }
  85. /// <summary>
  86. /// Get master hls playlist.
  87. /// </summary>
  88. /// <param name="transcodingJobType">Transcoding job type.</param>
  89. /// <param name="streamingRequest">Streaming request dto.</param>
  90. /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
  91. /// <returns>A <see cref="Task"/> containing the resulting <see cref="ActionResult"/>.</returns>
  92. public async Task<ActionResult> GetMasterHlsPlaylist(
  93. TranscodingJobType transcodingJobType,
  94. StreamingRequestDto streamingRequest,
  95. bool enableAdaptiveBitrateStreaming)
  96. {
  97. var isHeadRequest = _httpContextAccessor.HttpContext?.Request.Method == WebRequestMethods.Http.Head;
  98. // CTS lifecycle is managed internally.
  99. var cancellationTokenSource = new CancellationTokenSource();
  100. return await GetMasterPlaylistInternal(
  101. streamingRequest,
  102. isHeadRequest,
  103. enableAdaptiveBitrateStreaming,
  104. transcodingJobType,
  105. cancellationTokenSource).ConfigureAwait(false);
  106. }
  107. private async Task<ActionResult> GetMasterPlaylistInternal(
  108. StreamingRequestDto streamingRequest,
  109. bool isHeadRequest,
  110. bool enableAdaptiveBitrateStreaming,
  111. TranscodingJobType transcodingJobType,
  112. CancellationTokenSource cancellationTokenSource)
  113. {
  114. if (_httpContextAccessor.HttpContext is null)
  115. {
  116. throw new ResourceNotFoundException(nameof(_httpContextAccessor.HttpContext));
  117. }
  118. using var state = await StreamingHelpers.GetStreamingState(
  119. streamingRequest,
  120. _httpContextAccessor.HttpContext,
  121. _mediaSourceManager,
  122. _userManager,
  123. _libraryManager,
  124. _serverConfigurationManager,
  125. _mediaEncoder,
  126. _encodingHelper,
  127. _transcodeManager,
  128. transcodingJobType,
  129. cancellationTokenSource.Token)
  130. .ConfigureAwait(false);
  131. _httpContextAccessor.HttpContext.Response.Headers.Append(HeaderNames.Expires, "0");
  132. if (isHeadRequest)
  133. {
  134. return new FileContentResult(Array.Empty<byte>(), MimeTypes.GetMimeType("playlist.m3u8"));
  135. }
  136. var totalBitrate = (state.OutputAudioBitrate ?? 0) + (state.OutputVideoBitrate ?? 0);
  137. var builder = new StringBuilder();
  138. builder.AppendLine("#EXTM3U");
  139. var isLiveStream = state.IsSegmentedLiveStream;
  140. var queryString = _httpContextAccessor.HttpContext.Request.QueryString.ToString();
  141. // from universal audio service
  142. if (!string.IsNullOrWhiteSpace(state.Request.SegmentContainer)
  143. && !queryString.Contains("SegmentContainer", StringComparison.OrdinalIgnoreCase))
  144. {
  145. queryString += "&SegmentContainer=" + state.Request.SegmentContainer;
  146. }
  147. // from universal audio service
  148. if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons)
  149. && !queryString.Contains("TranscodeReasons=", StringComparison.OrdinalIgnoreCase))
  150. {
  151. queryString += "&TranscodeReasons=" + state.Request.TranscodeReasons;
  152. }
  153. // Main stream
  154. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  155. playlistUrl += queryString;
  156. var subtitleStreams = state.MediaSource
  157. .MediaStreams
  158. .Where(i => i.IsTextSubtitleStream)
  159. .ToList();
  160. var subtitleGroup = subtitleStreams.Count > 0 && (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Hls || state.VideoRequest!.EnableSubtitlesInManifest)
  161. ? "subs"
  162. : null;
  163. // If we're burning in subtitles then don't add additional subs to the manifest
  164. if (state.SubtitleStream is not null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  165. {
  166. subtitleGroup = null;
  167. }
  168. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  169. {
  170. AddSubtitles(state, subtitleStreams, builder, _httpContextAccessor.HttpContext.User);
  171. }
  172. var basicPlaylist = AppendPlaylist(builder, state, playlistUrl, totalBitrate, subtitleGroup);
  173. if (state.VideoStream is not null && state.VideoRequest is not null)
  174. {
  175. var encodingOptions = _serverConfigurationManager.GetEncodingOptions();
  176. // Provide SDR HEVC entrance for backward compatibility.
  177. if (encodingOptions.AllowHevcEncoding
  178. && !encodingOptions.AllowAv1Encoding
  179. && EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  180. && state.VideoStream.VideoRange == VideoRange.HDR
  181. && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  182. {
  183. var requestedVideoProfiles = state.GetRequestedProfiles("hevc");
  184. if (requestedVideoProfiles is not null && requestedVideoProfiles.Length > 0)
  185. {
  186. // Force HEVC Main Profile and disable video stream copy.
  187. state.OutputVideoCodec = "hevc";
  188. var sdrVideoUrl = ReplaceProfile(playlistUrl, "hevc", string.Join(',', requestedVideoProfiles), "main");
  189. sdrVideoUrl += "&AllowVideoStreamCopy=false";
  190. // HACK: Use the same bitrate so that the client can choose by other attributes, such as color range.
  191. AppendPlaylist(builder, state, sdrVideoUrl, totalBitrate, subtitleGroup);
  192. // Restore the video codec
  193. state.OutputVideoCodec = "copy";
  194. }
  195. }
  196. // Provide Level 5.0 entrance for backward compatibility.
  197. // e.g. Apple A10 chips refuse the master playlist containing SDR HEVC Main Level 5.1 video,
  198. // but in fact it is capable of playing videos up to Level 6.1.
  199. if (encodingOptions.AllowHevcEncoding
  200. && !encodingOptions.AllowAv1Encoding
  201. && EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  202. && state.VideoStream.Level.HasValue
  203. && state.VideoStream.Level > 150
  204. && state.VideoStream.VideoRange == VideoRange.SDR
  205. && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  206. {
  207. var playlistCodecsField = new StringBuilder();
  208. AppendPlaylistCodecsField(playlistCodecsField, state);
  209. // Force the video level to 5.0.
  210. var originalLevel = state.VideoStream.Level;
  211. state.VideoStream.Level = 150;
  212. var newPlaylistCodecsField = new StringBuilder();
  213. AppendPlaylistCodecsField(newPlaylistCodecsField, state);
  214. // Restore the video level.
  215. state.VideoStream.Level = originalLevel;
  216. var newPlaylist = ReplacePlaylistCodecsField(basicPlaylist, playlistCodecsField, newPlaylistCodecsField);
  217. builder.Append(newPlaylist);
  218. }
  219. }
  220. if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIP()))
  221. {
  222. var requestedVideoBitrate = state.VideoRequest is null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
  223. // By default, vary by just 200k
  224. var variation = GetBitrateVariation(totalBitrate);
  225. var newBitrate = totalBitrate - variation;
  226. var variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
  227. AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
  228. variation *= 2;
  229. newBitrate = totalBitrate - variation;
  230. variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
  231. AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
  232. }
  233. if (!isLiveStream && (state.VideoRequest?.EnableTrickplay ?? false))
  234. {
  235. var sourceId = Guid.Parse(state.Request.MediaSourceId);
  236. var trickplayResolutions = await _trickplayManager.GetTrickplayResolutions(sourceId).ConfigureAwait(false);
  237. AddTrickplay(state, trickplayResolutions, builder, _httpContextAccessor.HttpContext.User);
  238. }
  239. return new FileContentResult(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
  240. }
  241. private StringBuilder AppendPlaylist(StringBuilder builder, StreamState state, string url, int bitrate, string? subtitleGroup)
  242. {
  243. var playlistBuilder = new StringBuilder();
  244. playlistBuilder.Append("#EXT-X-STREAM-INF:BANDWIDTH=")
  245. .Append(bitrate.ToString(CultureInfo.InvariantCulture))
  246. .Append(",AVERAGE-BANDWIDTH=")
  247. .Append(bitrate.ToString(CultureInfo.InvariantCulture));
  248. AppendPlaylistVideoRangeField(playlistBuilder, state);
  249. AppendPlaylistCodecsField(playlistBuilder, state);
  250. AppendPlaylistResolutionField(playlistBuilder, state);
  251. AppendPlaylistFramerateField(playlistBuilder, state);
  252. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  253. {
  254. playlistBuilder.Append(",SUBTITLES=\"")
  255. .Append(subtitleGroup)
  256. .Append('"');
  257. }
  258. playlistBuilder.Append(Environment.NewLine);
  259. playlistBuilder.AppendLine(url);
  260. builder.Append(playlistBuilder);
  261. return playlistBuilder;
  262. }
  263. /// <summary>
  264. /// Appends a VIDEO-RANGE field containing the range of the output video stream.
  265. /// </summary>
  266. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  267. /// <param name="builder">StringBuilder to append the field to.</param>
  268. /// <param name="state">StreamState of the current stream.</param>
  269. private void AppendPlaylistVideoRangeField(StringBuilder builder, StreamState state)
  270. {
  271. if (state.VideoStream is not null && state.VideoStream.VideoRange != VideoRange.Unknown)
  272. {
  273. var videoRange = state.VideoStream.VideoRange;
  274. var videoRangeType = state.VideoStream.VideoRangeType;
  275. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  276. {
  277. if (videoRange == VideoRange.SDR)
  278. {
  279. builder.Append(",VIDEO-RANGE=SDR");
  280. }
  281. if (videoRange == VideoRange.HDR)
  282. {
  283. if (videoRangeType == VideoRangeType.HLG)
  284. {
  285. builder.Append(",VIDEO-RANGE=HLG");
  286. }
  287. else
  288. {
  289. builder.Append(",VIDEO-RANGE=PQ");
  290. }
  291. }
  292. }
  293. else
  294. {
  295. // Currently we only encode to SDR.
  296. builder.Append(",VIDEO-RANGE=SDR");
  297. }
  298. }
  299. }
  300. /// <summary>
  301. /// Appends a CODECS field containing formatted strings of
  302. /// the active streams output video and audio codecs.
  303. /// </summary>
  304. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  305. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  306. /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
  307. /// <param name="builder">StringBuilder to append the field to.</param>
  308. /// <param name="state">StreamState of the current stream.</param>
  309. private void AppendPlaylistCodecsField(StringBuilder builder, StreamState state)
  310. {
  311. // Video
  312. string videoCodecs = string.Empty;
  313. int? videoCodecLevel = GetOutputVideoCodecLevel(state);
  314. if (!string.IsNullOrEmpty(state.ActualOutputVideoCodec) && videoCodecLevel.HasValue)
  315. {
  316. videoCodecs = GetPlaylistVideoCodecs(state, state.ActualOutputVideoCodec, videoCodecLevel.Value);
  317. }
  318. // Audio
  319. string audioCodecs = string.Empty;
  320. if (!string.IsNullOrEmpty(state.ActualOutputAudioCodec))
  321. {
  322. audioCodecs = GetPlaylistAudioCodecs(state);
  323. }
  324. StringBuilder codecs = new StringBuilder();
  325. codecs.Append(videoCodecs);
  326. if (!string.IsNullOrEmpty(videoCodecs) && !string.IsNullOrEmpty(audioCodecs))
  327. {
  328. codecs.Append(',');
  329. }
  330. codecs.Append(audioCodecs);
  331. if (codecs.Length > 1)
  332. {
  333. builder.Append(",CODECS=\"")
  334. .Append(codecs)
  335. .Append('"');
  336. }
  337. }
  338. /// <summary>
  339. /// Appends a RESOLUTION field containing the resolution of the output stream.
  340. /// </summary>
  341. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  342. /// <param name="builder">StringBuilder to append the field to.</param>
  343. /// <param name="state">StreamState of the current stream.</param>
  344. private void AppendPlaylistResolutionField(StringBuilder builder, StreamState state)
  345. {
  346. if (state.OutputWidth.HasValue && state.OutputHeight.HasValue)
  347. {
  348. builder.Append(",RESOLUTION=")
  349. .Append(state.OutputWidth.GetValueOrDefault())
  350. .Append('x')
  351. .Append(state.OutputHeight.GetValueOrDefault());
  352. }
  353. }
  354. /// <summary>
  355. /// Appends a FRAME-RATE field containing the framerate of the output stream.
  356. /// </summary>
  357. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  358. /// <param name="builder">StringBuilder to append the field to.</param>
  359. /// <param name="state">StreamState of the current stream.</param>
  360. private void AppendPlaylistFramerateField(StringBuilder builder, StreamState state)
  361. {
  362. double? framerate = null;
  363. if (state.TargetFramerate.HasValue)
  364. {
  365. framerate = Math.Round(state.TargetFramerate.GetValueOrDefault(), 3);
  366. }
  367. else if (state.VideoStream?.RealFrameRate is not null)
  368. {
  369. framerate = Math.Round(state.VideoStream.RealFrameRate.GetValueOrDefault(), 3);
  370. }
  371. if (framerate.HasValue)
  372. {
  373. builder.Append(",FRAME-RATE=")
  374. .Append(framerate.Value.ToString(CultureInfo.InvariantCulture));
  375. }
  376. }
  377. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress)
  378. {
  379. // Within the local network this will likely do more harm than good.
  380. if (_networkManager.IsInLocalNetwork(ipAddress))
  381. {
  382. return false;
  383. }
  384. if (!enableAdaptiveBitrateStreaming)
  385. {
  386. return false;
  387. }
  388. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  389. {
  390. // Opening live streams is so slow it's not even worth it
  391. return false;
  392. }
  393. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  394. {
  395. return false;
  396. }
  397. if (EncodingHelper.IsCopyCodec(state.OutputAudioCodec))
  398. {
  399. return false;
  400. }
  401. if (!state.IsOutputVideo)
  402. {
  403. return false;
  404. }
  405. // Having problems in android
  406. return false;
  407. // return state.VideoRequest.VideoBitRate.HasValue;
  408. }
  409. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder, ClaimsPrincipal user)
  410. {
  411. if (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Drop)
  412. {
  413. return;
  414. }
  415. var selectedIndex = state.SubtitleStream is null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Hls ? (int?)null : state.SubtitleStream.Index;
  416. const string Format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},AUTOSELECT=YES,URI=\"{3}\",LANGUAGE=\"{4}\"";
  417. foreach (var stream in subtitles)
  418. {
  419. var name = stream.DisplayTitle;
  420. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  421. var isForced = stream.IsForced;
  422. var url = string.Format(
  423. CultureInfo.InvariantCulture,
  424. "{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}&api_key={3}",
  425. state.Request.MediaSourceId,
  426. stream.Index.ToString(CultureInfo.InvariantCulture),
  427. 30.ToString(CultureInfo.InvariantCulture),
  428. user.GetToken());
  429. var line = string.Format(
  430. CultureInfo.InvariantCulture,
  431. Format,
  432. name,
  433. isDefault ? "YES" : "NO",
  434. isForced ? "YES" : "NO",
  435. url,
  436. stream.Language ?? "Unknown");
  437. builder.AppendLine(line);
  438. }
  439. }
  440. /// <summary>
  441. /// Appends EXT-X-IMAGE-STREAM-INF playlists for each available trickplay resolution.
  442. /// </summary>
  443. /// <param name="state">StreamState of the current stream.</param>
  444. /// <param name="trickplayResolutions">Dictionary of widths to corresponding tiles info.</param>
  445. /// <param name="builder">StringBuilder to append the field to.</param>
  446. /// <param name="user">Http user context.</param>
  447. private void AddTrickplay(StreamState state, Dictionary<int, TrickplayInfo> trickplayResolutions, StringBuilder builder, ClaimsPrincipal user)
  448. {
  449. const string playlistFormat = "#EXT-X-IMAGE-STREAM-INF:BANDWIDTH={0},RESOLUTION={1}x{2},CODECS=\"jpeg\",URI=\"{3}\"";
  450. foreach (var resolution in trickplayResolutions)
  451. {
  452. var width = resolution.Key;
  453. var trickplayInfo = resolution.Value;
  454. var url = string.Format(
  455. CultureInfo.InvariantCulture,
  456. "Trickplay/{0}/tiles.m3u8?MediaSourceId={1}&api_key={2}",
  457. width.ToString(CultureInfo.InvariantCulture),
  458. state.Request.MediaSourceId,
  459. user.GetToken());
  460. builder.AppendFormat(
  461. CultureInfo.InvariantCulture,
  462. playlistFormat,
  463. trickplayInfo.Bandwidth.ToString(CultureInfo.InvariantCulture),
  464. trickplayInfo.Width.ToString(CultureInfo.InvariantCulture),
  465. trickplayInfo.Height.ToString(CultureInfo.InvariantCulture),
  466. url);
  467. builder.AppendLine();
  468. }
  469. }
  470. /// <summary>
  471. /// Get the H.26X level of the output video stream.
  472. /// </summary>
  473. /// <param name="state">StreamState of the current stream.</param>
  474. /// <returns>H.26X level of the output video stream.</returns>
  475. private int? GetOutputVideoCodecLevel(StreamState state)
  476. {
  477. string levelString = string.Empty;
  478. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  479. && state.VideoStream is not null
  480. && state.VideoStream.Level.HasValue)
  481. {
  482. levelString = state.VideoStream.Level.Value.ToString(CultureInfo.InvariantCulture) ?? string.Empty;
  483. }
  484. else
  485. {
  486. if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  487. {
  488. levelString = state.GetRequestedLevel(state.ActualOutputVideoCodec) ?? "41";
  489. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  490. }
  491. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  492. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  493. {
  494. levelString = state.GetRequestedLevel("h265") ?? state.GetRequestedLevel("hevc") ?? "120";
  495. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  496. }
  497. if (string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase))
  498. {
  499. levelString = state.GetRequestedLevel("av1") ?? "19";
  500. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  501. }
  502. }
  503. if (int.TryParse(levelString, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedLevel))
  504. {
  505. return parsedLevel;
  506. }
  507. return null;
  508. }
  509. /// <summary>
  510. /// Get the profile of the output video stream.
  511. /// </summary>
  512. /// <param name="state">StreamState of the current stream.</param>
  513. /// <param name="codec">Video codec.</param>
  514. /// <returns>Profile of the output video stream.</returns>
  515. private string GetOutputVideoCodecProfile(StreamState state, string codec)
  516. {
  517. string profileString = string.Empty;
  518. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  519. && !string.IsNullOrEmpty(state.VideoStream.Profile))
  520. {
  521. profileString = state.VideoStream.Profile;
  522. }
  523. else if (!string.IsNullOrEmpty(codec))
  524. {
  525. profileString = state.GetRequestedProfiles(codec).FirstOrDefault() ?? string.Empty;
  526. if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  527. {
  528. profileString ??= "high";
  529. }
  530. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  531. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
  532. || string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase))
  533. {
  534. profileString ??= "main";
  535. }
  536. }
  537. return profileString;
  538. }
  539. /// <summary>
  540. /// Gets a formatted string of the output audio codec, for use in the CODECS field.
  541. /// </summary>
  542. /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
  543. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  544. /// <param name="state">StreamState of the current stream.</param>
  545. /// <returns>Formatted audio codec string.</returns>
  546. private string GetPlaylistAudioCodecs(StreamState state)
  547. {
  548. if (string.Equals(state.ActualOutputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  549. {
  550. string? profile = state.GetRequestedProfiles("aac").FirstOrDefault();
  551. return HlsCodecStringHelpers.GetAACString(profile);
  552. }
  553. if (string.Equals(state.ActualOutputAudioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
  554. {
  555. return HlsCodecStringHelpers.GetMP3String();
  556. }
  557. if (string.Equals(state.ActualOutputAudioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
  558. {
  559. return HlsCodecStringHelpers.GetAC3String();
  560. }
  561. if (string.Equals(state.ActualOutputAudioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
  562. {
  563. return HlsCodecStringHelpers.GetEAC3String();
  564. }
  565. if (string.Equals(state.ActualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase))
  566. {
  567. return HlsCodecStringHelpers.GetFLACString();
  568. }
  569. if (string.Equals(state.ActualOutputAudioCodec, "alac", StringComparison.OrdinalIgnoreCase))
  570. {
  571. return HlsCodecStringHelpers.GetALACString();
  572. }
  573. if (string.Equals(state.ActualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  574. {
  575. return HlsCodecStringHelpers.GetOPUSString();
  576. }
  577. return string.Empty;
  578. }
  579. /// <summary>
  580. /// Gets a formatted string of the output video codec, for use in the CODECS field.
  581. /// </summary>
  582. /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
  583. /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
  584. /// <param name="state">StreamState of the current stream.</param>
  585. /// <param name="codec">Video codec.</param>
  586. /// <param name="level">Video level.</param>
  587. /// <returns>Formatted video codec string.</returns>
  588. private string GetPlaylistVideoCodecs(StreamState state, string codec, int level)
  589. {
  590. if (level == 0)
  591. {
  592. // This is 0 when there's no requested level in the device profile
  593. // and the source is not encoded in H.26X or AV1
  594. _logger.LogError("Got invalid level when building CODECS field for HLS master playlist");
  595. return string.Empty;
  596. }
  597. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  598. {
  599. string profile = GetOutputVideoCodecProfile(state, "h264");
  600. return HlsCodecStringHelpers.GetH264String(profile, level);
  601. }
  602. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  603. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  604. {
  605. string profile = GetOutputVideoCodecProfile(state, "hevc");
  606. return HlsCodecStringHelpers.GetH265String(profile, level);
  607. }
  608. if (string.Equals(codec, "av1", StringComparison.OrdinalIgnoreCase))
  609. {
  610. string profile = GetOutputVideoCodecProfile(state, "av1");
  611. // Currently we only transcode to 8 bits AV1
  612. int bitDepth = 8;
  613. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  614. && state.VideoStream is not null
  615. && state.VideoStream.BitDepth.HasValue)
  616. {
  617. bitDepth = state.VideoStream.BitDepth.Value;
  618. }
  619. return HlsCodecStringHelpers.GetAv1String(profile, level, false, bitDepth);
  620. }
  621. return string.Empty;
  622. }
  623. private int GetBitrateVariation(int bitrate)
  624. {
  625. // By default, vary by just 50k
  626. var variation = 50000;
  627. if (bitrate >= 10000000)
  628. {
  629. variation = 2000000;
  630. }
  631. else if (bitrate >= 5000000)
  632. {
  633. variation = 1500000;
  634. }
  635. else if (bitrate >= 3000000)
  636. {
  637. variation = 1000000;
  638. }
  639. else if (bitrate >= 2000000)
  640. {
  641. variation = 500000;
  642. }
  643. else if (bitrate >= 1000000)
  644. {
  645. variation = 300000;
  646. }
  647. else if (bitrate >= 600000)
  648. {
  649. variation = 200000;
  650. }
  651. else if (bitrate >= 400000)
  652. {
  653. variation = 100000;
  654. }
  655. return variation;
  656. }
  657. private string ReplaceVideoBitrate(string url, int oldValue, int newValue)
  658. {
  659. return url.Replace(
  660. "videobitrate=" + oldValue.ToString(CultureInfo.InvariantCulture),
  661. "videobitrate=" + newValue.ToString(CultureInfo.InvariantCulture),
  662. StringComparison.OrdinalIgnoreCase);
  663. }
  664. private string ReplaceProfile(string url, string codec, string oldValue, string newValue)
  665. {
  666. string profileStr = codec + "-profile=";
  667. return url.Replace(
  668. profileStr + oldValue,
  669. profileStr + newValue,
  670. StringComparison.OrdinalIgnoreCase);
  671. }
  672. private string ReplacePlaylistCodecsField(StringBuilder playlist, StringBuilder oldValue, StringBuilder newValue)
  673. {
  674. var oldPlaylist = playlist.ToString();
  675. return oldPlaylist.Replace(
  676. oldValue.ToString(),
  677. newValue.ToString(),
  678. StringComparison.Ordinal);
  679. }
  680. }