DynamicHlsHelper.cs 32 KB

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