DynamicHlsHelper.cs 33 KB

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