DynamicHlsHelper.cs 34 KB

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