DynamicHlsHelper.cs 31 KB

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