DynamicHlsHelper.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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. var sdrOutputVideoBitrate = _encodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
  191. var sdrOutputAudioBitrate = 0;
  192. if (EncodingHelper.LosslessAudioCodecs.Contains(state.VideoRequest.AudioCodec, StringComparison.OrdinalIgnoreCase))
  193. {
  194. sdrOutputAudioBitrate = state.AudioStream.BitRate ?? 0;
  195. }
  196. else
  197. {
  198. sdrOutputAudioBitrate = _encodingHelper.GetAudioBitrateParam(state.VideoRequest, state.AudioStream, state.OutputAudioChannels) ?? 0;
  199. }
  200. var sdrTotalBitrate = sdrOutputAudioBitrate + sdrOutputVideoBitrate;
  201. AppendPlaylist(builder, state, sdrVideoUrl, sdrTotalBitrate, subtitleGroup);
  202. // Restore the video codec
  203. state.OutputVideoCodec = "copy";
  204. }
  205. }
  206. // Provide Level 5.0 entrance for backward compatibility.
  207. // e.g. Apple A10 chips refuse the master playlist containing SDR HEVC Main Level 5.1 video,
  208. // but in fact it is capable of playing videos up to Level 6.1.
  209. if (encodingOptions.AllowHevcEncoding
  210. && !encodingOptions.AllowAv1Encoding
  211. && EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  212. && state.VideoStream.Level.HasValue
  213. && state.VideoStream.Level > 150
  214. && state.VideoStream.VideoRange == VideoRange.SDR
  215. && string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  216. {
  217. var playlistCodecsField = new StringBuilder();
  218. AppendPlaylistCodecsField(playlistCodecsField, state);
  219. // Force the video level to 5.0.
  220. var originalLevel = state.VideoStream.Level;
  221. state.VideoStream.Level = 150;
  222. var newPlaylistCodecsField = new StringBuilder();
  223. AppendPlaylistCodecsField(newPlaylistCodecsField, state);
  224. // Restore the video level.
  225. state.VideoStream.Level = originalLevel;
  226. var newPlaylist = ReplacePlaylistCodecsField(basicPlaylist, playlistCodecsField, newPlaylistCodecsField);
  227. builder.Append(newPlaylist);
  228. }
  229. }
  230. if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIP()))
  231. {
  232. var requestedVideoBitrate = state.VideoRequest is null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
  233. // By default, vary by just 200k
  234. var variation = GetBitrateVariation(totalBitrate);
  235. var newBitrate = totalBitrate - variation;
  236. var variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
  237. AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
  238. variation *= 2;
  239. newBitrate = totalBitrate - variation;
  240. variantUrl = ReplaceVideoBitrate(playlistUrl, requestedVideoBitrate, requestedVideoBitrate - variation);
  241. AppendPlaylist(builder, state, variantUrl, newBitrate, subtitleGroup);
  242. }
  243. if (!isLiveStream && (state.VideoRequest?.EnableTrickplay ?? false))
  244. {
  245. var sourceId = Guid.Parse(state.Request.MediaSourceId);
  246. var trickplayResolutions = await _trickplayManager.GetTrickplayResolutions(sourceId).ConfigureAwait(false);
  247. AddTrickplay(state, trickplayResolutions, builder, _httpContextAccessor.HttpContext.User);
  248. }
  249. return new FileContentResult(Encoding.UTF8.GetBytes(builder.ToString()), MimeTypes.GetMimeType("playlist.m3u8"));
  250. }
  251. private StringBuilder AppendPlaylist(StringBuilder builder, StreamState state, string url, int bitrate, string? subtitleGroup)
  252. {
  253. var playlistBuilder = new StringBuilder();
  254. playlistBuilder.Append("#EXT-X-STREAM-INF:BANDWIDTH=")
  255. .Append(bitrate.ToString(CultureInfo.InvariantCulture))
  256. .Append(",AVERAGE-BANDWIDTH=")
  257. .Append(bitrate.ToString(CultureInfo.InvariantCulture));
  258. AppendPlaylistVideoRangeField(playlistBuilder, state);
  259. AppendPlaylistCodecsField(playlistBuilder, state);
  260. AppendPlaylistResolutionField(playlistBuilder, state);
  261. AppendPlaylistFramerateField(playlistBuilder, state);
  262. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  263. {
  264. playlistBuilder.Append(",SUBTITLES=\"")
  265. .Append(subtitleGroup)
  266. .Append('"');
  267. }
  268. playlistBuilder.Append(Environment.NewLine);
  269. playlistBuilder.AppendLine(url);
  270. builder.Append(playlistBuilder);
  271. return playlistBuilder;
  272. }
  273. /// <summary>
  274. /// Appends a VIDEO-RANGE field containing the range of the output video stream.
  275. /// </summary>
  276. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  277. /// <param name="builder">StringBuilder to append the field to.</param>
  278. /// <param name="state">StreamState of the current stream.</param>
  279. private void AppendPlaylistVideoRangeField(StringBuilder builder, StreamState state)
  280. {
  281. if (state.VideoStream is not null && state.VideoStream.VideoRange != VideoRange.Unknown)
  282. {
  283. var videoRange = state.VideoStream.VideoRange;
  284. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  285. {
  286. if (videoRange == VideoRange.SDR)
  287. {
  288. builder.Append(",VIDEO-RANGE=SDR");
  289. }
  290. if (videoRange == VideoRange.HDR)
  291. {
  292. builder.Append(",VIDEO-RANGE=PQ");
  293. }
  294. }
  295. else
  296. {
  297. // Currently we only encode to SDR.
  298. builder.Append(",VIDEO-RANGE=SDR");
  299. }
  300. }
  301. }
  302. /// <summary>
  303. /// Appends a CODECS field containing formatted strings of
  304. /// the active streams output video and audio codecs.
  305. /// </summary>
  306. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  307. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  308. /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
  309. /// <param name="builder">StringBuilder to append the field to.</param>
  310. /// <param name="state">StreamState of the current stream.</param>
  311. private void AppendPlaylistCodecsField(StringBuilder builder, StreamState state)
  312. {
  313. // Video
  314. string videoCodecs = string.Empty;
  315. int? videoCodecLevel = GetOutputVideoCodecLevel(state);
  316. if (!string.IsNullOrEmpty(state.ActualOutputVideoCodec) && videoCodecLevel.HasValue)
  317. {
  318. videoCodecs = GetPlaylistVideoCodecs(state, state.ActualOutputVideoCodec, videoCodecLevel.Value);
  319. }
  320. // Audio
  321. string audioCodecs = string.Empty;
  322. if (!string.IsNullOrEmpty(state.ActualOutputAudioCodec))
  323. {
  324. audioCodecs = GetPlaylistAudioCodecs(state);
  325. }
  326. StringBuilder codecs = new StringBuilder();
  327. codecs.Append(videoCodecs);
  328. if (!string.IsNullOrEmpty(videoCodecs) && !string.IsNullOrEmpty(audioCodecs))
  329. {
  330. codecs.Append(',');
  331. }
  332. codecs.Append(audioCodecs);
  333. if (codecs.Length > 1)
  334. {
  335. builder.Append(",CODECS=\"")
  336. .Append(codecs)
  337. .Append('"');
  338. }
  339. }
  340. /// <summary>
  341. /// Appends a RESOLUTION field containing the resolution of the output stream.
  342. /// </summary>
  343. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  344. /// <param name="builder">StringBuilder to append the field to.</param>
  345. /// <param name="state">StreamState of the current stream.</param>
  346. private void AppendPlaylistResolutionField(StringBuilder builder, StreamState state)
  347. {
  348. if (state.OutputWidth.HasValue && state.OutputHeight.HasValue)
  349. {
  350. builder.Append(",RESOLUTION=")
  351. .Append(state.OutputWidth.GetValueOrDefault())
  352. .Append('x')
  353. .Append(state.OutputHeight.GetValueOrDefault());
  354. }
  355. }
  356. /// <summary>
  357. /// Appends a FRAME-RATE field containing the framerate of the output stream.
  358. /// </summary>
  359. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  360. /// <param name="builder">StringBuilder to append the field to.</param>
  361. /// <param name="state">StreamState of the current stream.</param>
  362. private void AppendPlaylistFramerateField(StringBuilder builder, StreamState state)
  363. {
  364. double? framerate = null;
  365. if (state.TargetFramerate.HasValue)
  366. {
  367. framerate = Math.Round(state.TargetFramerate.GetValueOrDefault(), 3);
  368. }
  369. else if (state.VideoStream?.RealFrameRate is not null)
  370. {
  371. framerate = Math.Round(state.VideoStream.RealFrameRate.GetValueOrDefault(), 3);
  372. }
  373. if (framerate.HasValue)
  374. {
  375. builder.Append(",FRAME-RATE=")
  376. .Append(framerate.Value.ToString(CultureInfo.InvariantCulture));
  377. }
  378. }
  379. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress)
  380. {
  381. // Within the local network this will likely do more harm than good.
  382. if (_networkManager.IsInLocalNetwork(ipAddress))
  383. {
  384. return false;
  385. }
  386. if (!enableAdaptiveBitrateStreaming)
  387. {
  388. return false;
  389. }
  390. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  391. {
  392. // Opening live streams is so slow it's not even worth it
  393. return false;
  394. }
  395. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  396. {
  397. return false;
  398. }
  399. if (EncodingHelper.IsCopyCodec(state.OutputAudioCodec))
  400. {
  401. return false;
  402. }
  403. if (!state.IsOutputVideo)
  404. {
  405. return false;
  406. }
  407. // Having problems in android
  408. return false;
  409. // return state.VideoRequest.VideoBitRate.HasValue;
  410. }
  411. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder, ClaimsPrincipal user)
  412. {
  413. if (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Drop)
  414. {
  415. return;
  416. }
  417. var selectedIndex = state.SubtitleStream is null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Hls ? (int?)null : state.SubtitleStream.Index;
  418. const string Format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},AUTOSELECT=YES,URI=\"{3}\",LANGUAGE=\"{4}\"";
  419. foreach (var stream in subtitles)
  420. {
  421. var name = stream.DisplayTitle;
  422. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  423. var isForced = stream.IsForced;
  424. var url = string.Format(
  425. CultureInfo.InvariantCulture,
  426. "{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}&api_key={3}",
  427. state.Request.MediaSourceId,
  428. stream.Index.ToString(CultureInfo.InvariantCulture),
  429. 30.ToString(CultureInfo.InvariantCulture),
  430. user.GetToken());
  431. var line = string.Format(
  432. CultureInfo.InvariantCulture,
  433. Format,
  434. name,
  435. isDefault ? "YES" : "NO",
  436. isForced ? "YES" : "NO",
  437. url,
  438. stream.Language ?? "Unknown");
  439. builder.AppendLine(line);
  440. }
  441. }
  442. /// <summary>
  443. /// Appends EXT-X-IMAGE-STREAM-INF playlists for each available trickplay resolution.
  444. /// </summary>
  445. /// <param name="state">StreamState of the current stream.</param>
  446. /// <param name="trickplayResolutions">Dictionary of widths to corresponding tiles info.</param>
  447. /// <param name="builder">StringBuilder to append the field to.</param>
  448. /// <param name="user">Http user context.</param>
  449. private void AddTrickplay(StreamState state, Dictionary<int, TrickplayInfo> trickplayResolutions, StringBuilder builder, ClaimsPrincipal user)
  450. {
  451. const string playlistFormat = "#EXT-X-IMAGE-STREAM-INF:BANDWIDTH={0},RESOLUTION={1}x{2},CODECS=\"jpeg\",URI=\"{3}\"";
  452. foreach (var resolution in trickplayResolutions)
  453. {
  454. var width = resolution.Key;
  455. var trickplayInfo = resolution.Value;
  456. var url = string.Format(
  457. CultureInfo.InvariantCulture,
  458. "Trickplay/{0}/tiles.m3u8?MediaSourceId={1}&api_key={2}",
  459. width.ToString(CultureInfo.InvariantCulture),
  460. state.Request.MediaSourceId,
  461. user.GetToken());
  462. builder.AppendFormat(
  463. CultureInfo.InvariantCulture,
  464. playlistFormat,
  465. trickplayInfo.Bandwidth.ToString(CultureInfo.InvariantCulture),
  466. trickplayInfo.Width.ToString(CultureInfo.InvariantCulture),
  467. trickplayInfo.Height.ToString(CultureInfo.InvariantCulture),
  468. url);
  469. builder.AppendLine();
  470. }
  471. }
  472. /// <summary>
  473. /// Get the H.26X level of the output video stream.
  474. /// </summary>
  475. /// <param name="state">StreamState of the current stream.</param>
  476. /// <returns>H.26X level of the output video stream.</returns>
  477. private int? GetOutputVideoCodecLevel(StreamState state)
  478. {
  479. string levelString = string.Empty;
  480. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  481. && state.VideoStream is not null
  482. && state.VideoStream.Level.HasValue)
  483. {
  484. levelString = state.VideoStream.Level.Value.ToString(CultureInfo.InvariantCulture) ?? string.Empty;
  485. }
  486. else
  487. {
  488. if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  489. {
  490. levelString = state.GetRequestedLevel(state.ActualOutputVideoCodec) ?? "41";
  491. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  492. }
  493. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  494. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  495. {
  496. levelString = state.GetRequestedLevel("h265") ?? state.GetRequestedLevel("hevc") ?? "120";
  497. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  498. }
  499. if (string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase))
  500. {
  501. levelString = state.GetRequestedLevel("av1") ?? "19";
  502. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  503. }
  504. }
  505. if (int.TryParse(levelString, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedLevel))
  506. {
  507. return parsedLevel;
  508. }
  509. return null;
  510. }
  511. /// <summary>
  512. /// Get the profile of the output video stream.
  513. /// </summary>
  514. /// <param name="state">StreamState of the current stream.</param>
  515. /// <param name="codec">Video codec.</param>
  516. /// <returns>Profile of the output video stream.</returns>
  517. private string GetOutputVideoCodecProfile(StreamState state, string codec)
  518. {
  519. string profileString = string.Empty;
  520. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  521. && !string.IsNullOrEmpty(state.VideoStream.Profile))
  522. {
  523. profileString = state.VideoStream.Profile;
  524. }
  525. else if (!string.IsNullOrEmpty(codec))
  526. {
  527. profileString = state.GetRequestedProfiles(codec).FirstOrDefault() ?? string.Empty;
  528. if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  529. {
  530. profileString ??= "high";
  531. }
  532. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  533. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
  534. || string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase))
  535. {
  536. profileString ??= "main";
  537. }
  538. }
  539. return profileString;
  540. }
  541. /// <summary>
  542. /// Gets a formatted string of the output audio codec, for use in the CODECS field.
  543. /// </summary>
  544. /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
  545. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  546. /// <param name="state">StreamState of the current stream.</param>
  547. /// <returns>Formatted audio codec string.</returns>
  548. private string GetPlaylistAudioCodecs(StreamState state)
  549. {
  550. if (string.Equals(state.ActualOutputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  551. {
  552. string? profile = state.GetRequestedProfiles("aac").FirstOrDefault();
  553. return HlsCodecStringHelpers.GetAACString(profile);
  554. }
  555. if (string.Equals(state.ActualOutputAudioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
  556. {
  557. return HlsCodecStringHelpers.GetMP3String();
  558. }
  559. if (string.Equals(state.ActualOutputAudioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
  560. {
  561. return HlsCodecStringHelpers.GetAC3String();
  562. }
  563. if (string.Equals(state.ActualOutputAudioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
  564. {
  565. return HlsCodecStringHelpers.GetEAC3String();
  566. }
  567. if (string.Equals(state.ActualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase))
  568. {
  569. return HlsCodecStringHelpers.GetFLACString();
  570. }
  571. if (string.Equals(state.ActualOutputAudioCodec, "alac", StringComparison.OrdinalIgnoreCase))
  572. {
  573. return HlsCodecStringHelpers.GetALACString();
  574. }
  575. if (string.Equals(state.ActualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  576. {
  577. return HlsCodecStringHelpers.GetOPUSString();
  578. }
  579. return string.Empty;
  580. }
  581. /// <summary>
  582. /// Gets a formatted string of the output video codec, for use in the CODECS field.
  583. /// </summary>
  584. /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
  585. /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
  586. /// <param name="state">StreamState of the current stream.</param>
  587. /// <param name="codec">Video codec.</param>
  588. /// <param name="level">Video level.</param>
  589. /// <returns>Formatted video codec string.</returns>
  590. private string GetPlaylistVideoCodecs(StreamState state, string codec, int level)
  591. {
  592. if (level == 0)
  593. {
  594. // This is 0 when there's no requested level in the device profile
  595. // and the source is not encoded in H.26X or AV1
  596. _logger.LogError("Got invalid level when building CODECS field for HLS master playlist");
  597. return string.Empty;
  598. }
  599. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  600. {
  601. string profile = GetOutputVideoCodecProfile(state, "h264");
  602. return HlsCodecStringHelpers.GetH264String(profile, level);
  603. }
  604. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  605. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  606. {
  607. string profile = GetOutputVideoCodecProfile(state, "hevc");
  608. return HlsCodecStringHelpers.GetH265String(profile, level);
  609. }
  610. if (string.Equals(codec, "av1", StringComparison.OrdinalIgnoreCase))
  611. {
  612. string profile = GetOutputVideoCodecProfile(state, "av1");
  613. // Currently we only transcode to 8 bits AV1
  614. int bitDepth = 8;
  615. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  616. && state.VideoStream is not null
  617. && state.VideoStream.BitDepth.HasValue)
  618. {
  619. bitDepth = state.VideoStream.BitDepth.Value;
  620. }
  621. return HlsCodecStringHelpers.GetAv1String(profile, level, false, bitDepth);
  622. }
  623. return string.Empty;
  624. }
  625. private int GetBitrateVariation(int bitrate)
  626. {
  627. // By default, vary by just 50k
  628. var variation = 50000;
  629. if (bitrate >= 10000000)
  630. {
  631. variation = 2000000;
  632. }
  633. else if (bitrate >= 5000000)
  634. {
  635. variation = 1500000;
  636. }
  637. else if (bitrate >= 3000000)
  638. {
  639. variation = 1000000;
  640. }
  641. else if (bitrate >= 2000000)
  642. {
  643. variation = 500000;
  644. }
  645. else if (bitrate >= 1000000)
  646. {
  647. variation = 300000;
  648. }
  649. else if (bitrate >= 600000)
  650. {
  651. variation = 200000;
  652. }
  653. else if (bitrate >= 400000)
  654. {
  655. variation = 100000;
  656. }
  657. return variation;
  658. }
  659. private string ReplaceVideoBitrate(string url, int oldValue, int newValue)
  660. {
  661. return url.Replace(
  662. "videobitrate=" + oldValue.ToString(CultureInfo.InvariantCulture),
  663. "videobitrate=" + newValue.ToString(CultureInfo.InvariantCulture),
  664. StringComparison.OrdinalIgnoreCase);
  665. }
  666. private string ReplaceProfile(string url, string codec, string oldValue, string newValue)
  667. {
  668. string profileStr = codec + "-profile=";
  669. return url.Replace(
  670. profileStr + oldValue,
  671. profileStr + newValue,
  672. StringComparison.OrdinalIgnoreCase);
  673. }
  674. private string ReplacePlaylistCodecsField(StringBuilder playlist, StringBuilder oldValue, StringBuilder newValue)
  675. {
  676. var oldPlaylist = playlist.ToString();
  677. return oldPlaylist.Replace(
  678. oldValue.ToString(),
  679. newValue.ToString(),
  680. StringComparison.Ordinal);
  681. }
  682. }