DynamicHlsHelper.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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.Enums;
  12. using Jellyfin.Database.Implementations.Entities;
  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?.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. AppendPlaylistSupplementalCodecsField(playlistBuilder, state);
  268. AppendPlaylistResolutionField(playlistBuilder, state);
  269. AppendPlaylistFramerateField(playlistBuilder, state);
  270. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  271. {
  272. playlistBuilder.Append(",SUBTITLES=\"")
  273. .Append(subtitleGroup)
  274. .Append('"');
  275. }
  276. playlistBuilder.Append(Environment.NewLine);
  277. playlistBuilder.AppendLine(url);
  278. builder.Append(playlistBuilder);
  279. return playlistBuilder;
  280. }
  281. /// <summary>
  282. /// Appends a VIDEO-RANGE field containing the range of the output video stream.
  283. /// </summary>
  284. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  285. /// <param name="builder">StringBuilder to append the field to.</param>
  286. /// <param name="state">StreamState of the current stream.</param>
  287. private void AppendPlaylistVideoRangeField(StringBuilder builder, StreamState state)
  288. {
  289. if (state.VideoStream is not null && state.VideoStream.VideoRange != VideoRange.Unknown)
  290. {
  291. var videoRange = state.VideoStream.VideoRange;
  292. var videoRangeType = state.VideoStream.VideoRangeType;
  293. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  294. {
  295. if (videoRange == VideoRange.SDR)
  296. {
  297. builder.Append(",VIDEO-RANGE=SDR");
  298. }
  299. if (videoRange == VideoRange.HDR)
  300. {
  301. switch (videoRangeType)
  302. {
  303. case VideoRangeType.HLG:
  304. case VideoRangeType.DOVIWithHLG:
  305. builder.Append(",VIDEO-RANGE=HLG");
  306. break;
  307. default:
  308. builder.Append(",VIDEO-RANGE=PQ");
  309. break;
  310. }
  311. }
  312. }
  313. else
  314. {
  315. // Currently we only encode to SDR.
  316. builder.Append(",VIDEO-RANGE=SDR");
  317. }
  318. }
  319. }
  320. /// <summary>
  321. /// Appends a CODECS field containing formatted strings of
  322. /// the active streams output video and audio codecs.
  323. /// </summary>
  324. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  325. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  326. /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
  327. /// <param name="builder">StringBuilder to append the field to.</param>
  328. /// <param name="state">StreamState of the current stream.</param>
  329. private void AppendPlaylistCodecsField(StringBuilder builder, StreamState state)
  330. {
  331. // Video
  332. string videoCodecs = string.Empty;
  333. int? videoCodecLevel = GetOutputVideoCodecLevel(state);
  334. if (!string.IsNullOrEmpty(state.ActualOutputVideoCodec) && videoCodecLevel.HasValue)
  335. {
  336. videoCodecs = GetPlaylistVideoCodecs(state, state.ActualOutputVideoCodec, videoCodecLevel.Value);
  337. }
  338. // Audio
  339. string audioCodecs = string.Empty;
  340. if (!string.IsNullOrEmpty(state.ActualOutputAudioCodec))
  341. {
  342. audioCodecs = GetPlaylistAudioCodecs(state);
  343. }
  344. StringBuilder codecs = new StringBuilder();
  345. codecs.Append(videoCodecs);
  346. if (!string.IsNullOrEmpty(videoCodecs) && !string.IsNullOrEmpty(audioCodecs))
  347. {
  348. codecs.Append(',');
  349. }
  350. codecs.Append(audioCodecs);
  351. if (codecs.Length > 1)
  352. {
  353. builder.Append(",CODECS=\"")
  354. .Append(codecs)
  355. .Append('"');
  356. }
  357. }
  358. /// <summary>
  359. /// Appends a SUPPLEMENTAL-CODECS field containing formatted strings of
  360. /// the active streams output Dolby Vision Videos.
  361. /// </summary>
  362. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  363. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  364. /// <param name="builder">StringBuilder to append the field to.</param>
  365. /// <param name="state">StreamState of the current stream.</param>
  366. private void AppendPlaylistSupplementalCodecsField(StringBuilder builder, StreamState state)
  367. {
  368. // HDR dynamic metadata currently cannot exist when transcoding
  369. if (!EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  370. {
  371. return;
  372. }
  373. if (EncodingHelper.IsDovi(state.VideoStream) && !_encodingHelper.IsDoviRemoved(state))
  374. {
  375. AppendDvString();
  376. }
  377. else if (EncodingHelper.IsHdr10Plus(state.VideoStream) && !_encodingHelper.IsHdr10PlusRemoved(state))
  378. {
  379. AppendHdr10PlusString();
  380. }
  381. return;
  382. void AppendDvString()
  383. {
  384. var dvProfile = state.VideoStream.DvProfile;
  385. var dvLevel = state.VideoStream.DvLevel;
  386. var dvRangeString = state.VideoStream.VideoRangeType switch
  387. {
  388. VideoRangeType.DOVIWithHDR10 => "db1p",
  389. VideoRangeType.DOVIWithHLG => "db4h",
  390. VideoRangeType.DOVIWithHDR10Plus => "db1p", // The HDR10+ metadata would be removed if Dovi metadata is not removed
  391. _ => string.Empty // Don't label Dovi with EL and SDR due to compatability issues, ignore invalid configurations
  392. };
  393. if (dvProfile is null || dvLevel is null || string.IsNullOrEmpty(dvRangeString))
  394. {
  395. return;
  396. }
  397. var dvFourCc = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase) ? "dav1" : "dvh1";
  398. builder.Append(",SUPPLEMENTAL-CODECS=\"")
  399. .Append(dvFourCc)
  400. .Append('.')
  401. .Append(dvProfile.Value.ToString("D2", CultureInfo.InvariantCulture))
  402. .Append('.')
  403. .Append(dvLevel.Value.ToString("D2", CultureInfo.InvariantCulture))
  404. .Append('/')
  405. .Append(dvRangeString)
  406. .Append('"');
  407. }
  408. void AppendHdr10PlusString()
  409. {
  410. var videoCodecLevel = GetOutputVideoCodecLevel(state);
  411. if (string.IsNullOrEmpty(state.ActualOutputVideoCodec) || videoCodecLevel is null)
  412. {
  413. return;
  414. }
  415. var videoCodecString = GetPlaylistVideoCodecs(state, state.ActualOutputVideoCodec, videoCodecLevel.Value);
  416. builder.Append(",SUPPLEMENTAL-CODECS=\"")
  417. .Append(videoCodecString)
  418. .Append('/')
  419. .Append("cdm4")
  420. .Append('"');
  421. }
  422. }
  423. /// <summary>
  424. /// Appends a RESOLUTION field containing the resolution of the output stream.
  425. /// </summary>
  426. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  427. /// <param name="builder">StringBuilder to append the field to.</param>
  428. /// <param name="state">StreamState of the current stream.</param>
  429. private void AppendPlaylistResolutionField(StringBuilder builder, StreamState state)
  430. {
  431. if (state.OutputWidth.HasValue && state.OutputHeight.HasValue)
  432. {
  433. builder.Append(",RESOLUTION=")
  434. .Append(state.OutputWidth.GetValueOrDefault())
  435. .Append('x')
  436. .Append(state.OutputHeight.GetValueOrDefault());
  437. }
  438. }
  439. /// <summary>
  440. /// Appends a FRAME-RATE field containing the framerate of the output stream.
  441. /// </summary>
  442. /// <seealso cref="AppendPlaylist(StringBuilder, StreamState, string, int, string)"/>
  443. /// <param name="builder">StringBuilder to append the field to.</param>
  444. /// <param name="state">StreamState of the current stream.</param>
  445. private void AppendPlaylistFramerateField(StringBuilder builder, StreamState state)
  446. {
  447. double? framerate = null;
  448. if (state.TargetFramerate.HasValue)
  449. {
  450. framerate = Math.Round(state.TargetFramerate.GetValueOrDefault(), 3);
  451. }
  452. else if (state.VideoStream?.RealFrameRate is not null)
  453. {
  454. framerate = Math.Round(state.VideoStream.RealFrameRate.GetValueOrDefault(), 3);
  455. }
  456. if (framerate.HasValue)
  457. {
  458. builder.Append(",FRAME-RATE=")
  459. .Append(framerate.Value.ToString(CultureInfo.InvariantCulture));
  460. }
  461. }
  462. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream, bool enableAdaptiveBitrateStreaming, IPAddress ipAddress)
  463. {
  464. // Within the local network this will likely do more harm than good.
  465. if (_networkManager.IsInLocalNetwork(ipAddress))
  466. {
  467. return false;
  468. }
  469. if (!enableAdaptiveBitrateStreaming)
  470. {
  471. return false;
  472. }
  473. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  474. {
  475. // Opening live streams is so slow it's not even worth it
  476. return false;
  477. }
  478. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec))
  479. {
  480. return false;
  481. }
  482. if (EncodingHelper.IsCopyCodec(state.OutputAudioCodec))
  483. {
  484. return false;
  485. }
  486. if (!state.IsOutputVideo)
  487. {
  488. return false;
  489. }
  490. return state.VideoRequest?.VideoBitRate.HasValue ?? false;
  491. }
  492. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder, ClaimsPrincipal user)
  493. {
  494. if (state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Drop)
  495. {
  496. return;
  497. }
  498. var selectedIndex = state.SubtitleStream is null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Hls ? (int?)null : state.SubtitleStream.Index;
  499. const string Format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},AUTOSELECT=YES,URI=\"{3}\",LANGUAGE=\"{4}\"";
  500. foreach (var stream in subtitles)
  501. {
  502. var name = stream.DisplayTitle;
  503. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  504. var isForced = stream.IsForced;
  505. var url = string.Format(
  506. CultureInfo.InvariantCulture,
  507. "{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}&ApiKey={3}",
  508. state.Request.MediaSourceId,
  509. stream.Index.ToString(CultureInfo.InvariantCulture),
  510. 30.ToString(CultureInfo.InvariantCulture),
  511. user.GetToken());
  512. var line = string.Format(
  513. CultureInfo.InvariantCulture,
  514. Format,
  515. name,
  516. isDefault ? "YES" : "NO",
  517. isForced ? "YES" : "NO",
  518. url,
  519. stream.Language ?? "Unknown");
  520. builder.AppendLine(line);
  521. }
  522. }
  523. /// <summary>
  524. /// Appends EXT-X-IMAGE-STREAM-INF playlists for each available trickplay resolution.
  525. /// </summary>
  526. /// <param name="state">StreamState of the current stream.</param>
  527. /// <param name="trickplayResolutions">Dictionary of widths to corresponding tiles info.</param>
  528. /// <param name="builder">StringBuilder to append the field to.</param>
  529. /// <param name="user">Http user context.</param>
  530. private void AddTrickplay(StreamState state, Dictionary<int, TrickplayInfo> trickplayResolutions, StringBuilder builder, ClaimsPrincipal user)
  531. {
  532. const string playlistFormat = "#EXT-X-IMAGE-STREAM-INF:BANDWIDTH={0},RESOLUTION={1}x{2},CODECS=\"jpeg\",URI=\"{3}\"";
  533. foreach (var resolution in trickplayResolutions)
  534. {
  535. var width = resolution.Key;
  536. var trickplayInfo = resolution.Value;
  537. var url = string.Format(
  538. CultureInfo.InvariantCulture,
  539. "Trickplay/{0}/tiles.m3u8?MediaSourceId={1}&ApiKey={2}",
  540. width.ToString(CultureInfo.InvariantCulture),
  541. state.Request.MediaSourceId,
  542. user.GetToken());
  543. builder.AppendFormat(
  544. CultureInfo.InvariantCulture,
  545. playlistFormat,
  546. trickplayInfo.Bandwidth.ToString(CultureInfo.InvariantCulture),
  547. trickplayInfo.Width.ToString(CultureInfo.InvariantCulture),
  548. trickplayInfo.Height.ToString(CultureInfo.InvariantCulture),
  549. url);
  550. builder.AppendLine();
  551. }
  552. }
  553. /// <summary>
  554. /// Get the H.26X level of the output video stream.
  555. /// </summary>
  556. /// <param name="state">StreamState of the current stream.</param>
  557. /// <returns>H.26X level of the output video stream.</returns>
  558. private int? GetOutputVideoCodecLevel(StreamState state)
  559. {
  560. string levelString = string.Empty;
  561. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  562. && state.VideoStream is not null
  563. && state.VideoStream.Level.HasValue)
  564. {
  565. levelString = state.VideoStream.Level.Value.ToString(CultureInfo.InvariantCulture);
  566. }
  567. else
  568. {
  569. if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  570. {
  571. levelString = state.GetRequestedLevel(state.ActualOutputVideoCodec) ?? "41";
  572. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  573. }
  574. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  575. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  576. {
  577. levelString = state.GetRequestedLevel("h265") ?? state.GetRequestedLevel("hevc") ?? "120";
  578. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  579. }
  580. if (string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase))
  581. {
  582. levelString = state.GetRequestedLevel("av1") ?? "19";
  583. levelString = EncodingHelper.NormalizeTranscodingLevel(state, levelString);
  584. }
  585. }
  586. if (int.TryParse(levelString, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedLevel))
  587. {
  588. return parsedLevel;
  589. }
  590. return null;
  591. }
  592. /// <summary>
  593. /// Get the profile of the output video stream.
  594. /// </summary>
  595. /// <param name="state">StreamState of the current stream.</param>
  596. /// <param name="codec">Video codec.</param>
  597. /// <returns>Profile of the output video stream.</returns>
  598. private string GetOutputVideoCodecProfile(StreamState state, string codec)
  599. {
  600. string profileString = string.Empty;
  601. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  602. && !string.IsNullOrEmpty(state.VideoStream.Profile))
  603. {
  604. profileString = state.VideoStream.Profile;
  605. }
  606. else if (!string.IsNullOrEmpty(codec))
  607. {
  608. profileString = state.GetRequestedProfiles(codec).FirstOrDefault() ?? string.Empty;
  609. if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  610. {
  611. profileString ??= "high";
  612. }
  613. if (string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  614. || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
  615. || string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgnoreCase))
  616. {
  617. profileString ??= "main";
  618. }
  619. }
  620. return profileString;
  621. }
  622. /// <summary>
  623. /// Gets a formatted string of the output audio codec, for use in the CODECS field.
  624. /// </summary>
  625. /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
  626. /// <seealso cref="GetPlaylistVideoCodecs(StreamState, string, int)"/>
  627. /// <param name="state">StreamState of the current stream.</param>
  628. /// <returns>Formatted audio codec string.</returns>
  629. private string GetPlaylistAudioCodecs(StreamState state)
  630. {
  631. if (string.Equals(state.ActualOutputAudioCodec, "aac", StringComparison.OrdinalIgnoreCase))
  632. {
  633. string? profile = state.GetRequestedProfiles("aac").FirstOrDefault();
  634. return HlsCodecStringHelpers.GetAACString(profile);
  635. }
  636. if (string.Equals(state.ActualOutputAudioCodec, "mp3", StringComparison.OrdinalIgnoreCase))
  637. {
  638. return HlsCodecStringHelpers.GetMP3String();
  639. }
  640. if (string.Equals(state.ActualOutputAudioCodec, "ac3", StringComparison.OrdinalIgnoreCase))
  641. {
  642. return HlsCodecStringHelpers.GetAC3String();
  643. }
  644. if (string.Equals(state.ActualOutputAudioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
  645. {
  646. return HlsCodecStringHelpers.GetEAC3String();
  647. }
  648. if (string.Equals(state.ActualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase))
  649. {
  650. return HlsCodecStringHelpers.GetFLACString();
  651. }
  652. if (string.Equals(state.ActualOutputAudioCodec, "alac", StringComparison.OrdinalIgnoreCase))
  653. {
  654. return HlsCodecStringHelpers.GetALACString();
  655. }
  656. if (string.Equals(state.ActualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  657. {
  658. return HlsCodecStringHelpers.GetOPUSString();
  659. }
  660. return string.Empty;
  661. }
  662. /// <summary>
  663. /// Gets a formatted string of the output video codec, for use in the CODECS field.
  664. /// </summary>
  665. /// <seealso cref="AppendPlaylistCodecsField(StringBuilder, StreamState)"/>
  666. /// <seealso cref="GetPlaylistAudioCodecs(StreamState)"/>
  667. /// <param name="state">StreamState of the current stream.</param>
  668. /// <param name="codec">Video codec.</param>
  669. /// <param name="level">Video level.</param>
  670. /// <returns>Formatted video codec string.</returns>
  671. private string GetPlaylistVideoCodecs(StreamState state, string codec, int level)
  672. {
  673. if (level == 0)
  674. {
  675. // This is 0 when there's no requested level in the device profile
  676. // and the source is not encoded in H.26X or AV1
  677. _logger.LogError("Got invalid level when building CODECS field for HLS master playlist");
  678. return string.Empty;
  679. }
  680. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  681. {
  682. string profile = GetOutputVideoCodecProfile(state, "h264");
  683. return HlsCodecStringHelpers.GetH264String(profile, level);
  684. }
  685. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  686. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  687. {
  688. string profile = GetOutputVideoCodecProfile(state, "hevc");
  689. return HlsCodecStringHelpers.GetH265String(profile, level);
  690. }
  691. if (string.Equals(codec, "av1", StringComparison.OrdinalIgnoreCase))
  692. {
  693. string profile = GetOutputVideoCodecProfile(state, "av1");
  694. // Currently we only transcode to 8 bits AV1
  695. int bitDepth = 8;
  696. if (EncodingHelper.IsCopyCodec(state.OutputVideoCodec)
  697. && state.VideoStream is not null
  698. && state.VideoStream.BitDepth.HasValue)
  699. {
  700. bitDepth = state.VideoStream.BitDepth.Value;
  701. }
  702. return HlsCodecStringHelpers.GetAv1String(profile, level, false, bitDepth);
  703. }
  704. // VP9 HLS is for video remuxing only, everything is probed from the original video
  705. if (string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  706. {
  707. var width = state.VideoStream.Width ?? 0;
  708. var height = state.VideoStream.Height ?? 0;
  709. var framerate = state.VideoStream.ReferenceFrameRate ?? 30;
  710. var bitDepth = state.VideoStream.BitDepth ?? 8;
  711. return HlsCodecStringHelpers.GetVp9String(
  712. width,
  713. height,
  714. state.VideoStream.PixelFormat,
  715. framerate,
  716. bitDepth);
  717. }
  718. return string.Empty;
  719. }
  720. private int GetBitrateVariation(int bitrate)
  721. {
  722. // By default, vary by just 50k
  723. var variation = 50000;
  724. if (bitrate >= 10000000)
  725. {
  726. variation = 2000000;
  727. }
  728. else if (bitrate >= 5000000)
  729. {
  730. variation = 1500000;
  731. }
  732. else if (bitrate >= 3000000)
  733. {
  734. variation = 1000000;
  735. }
  736. else if (bitrate >= 2000000)
  737. {
  738. variation = 500000;
  739. }
  740. else if (bitrate >= 1000000)
  741. {
  742. variation = 300000;
  743. }
  744. else if (bitrate >= 600000)
  745. {
  746. variation = 200000;
  747. }
  748. else if (bitrate >= 400000)
  749. {
  750. variation = 100000;
  751. }
  752. return variation;
  753. }
  754. private string ReplaceVideoBitrate(string url, int oldValue, int newValue)
  755. {
  756. return url.Replace(
  757. "videobitrate=" + oldValue.ToString(CultureInfo.InvariantCulture),
  758. "videobitrate=" + newValue.ToString(CultureInfo.InvariantCulture),
  759. StringComparison.OrdinalIgnoreCase);
  760. }
  761. private string ReplaceProfile(string url, string codec, string oldValue, string newValue)
  762. {
  763. string profileStr = codec + "-profile=";
  764. return url.Replace(
  765. profileStr + oldValue,
  766. profileStr + newValue,
  767. StringComparison.OrdinalIgnoreCase);
  768. }
  769. private string ReplacePlaylistCodecsField(StringBuilder playlist, StringBuilder oldValue, StringBuilder newValue)
  770. {
  771. var oldPlaylist = playlist.ToString();
  772. return oldPlaylist.Replace(
  773. oldValue.ToString(),
  774. newValue.ToString(),
  775. StringComparison.Ordinal);
  776. }
  777. }