< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.DynamicHlsController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/DynamicHlsController.cs
Line coverage
1%
Covered lines: 14
Uncovered lines: 795
Coverable lines: 809
Total lines: 2097
Line coverage: 1.7%
Branch coverage
4%
Covered branches: 10
Total branches: 222
Branch coverage: 4.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/16/2026 - 12:15:55 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 20828/2/2026 - 12:17:28 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 20838/9/2026 - 12:16:58 AM Line coverage: 1.6% (13/807) Branch coverage: 3.6% (8/222) Total lines: 208810/29/2026 - 12:17:11 AM Line coverage: 1.7% (14/809) Branch coverage: 4.5% (10/222) Total lines: 2097 5/16/2026 - 12:15:55 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 20828/2/2026 - 12:17:28 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 20838/9/2026 - 12:16:58 AM Line coverage: 1.6% (13/807) Branch coverage: 3.6% (8/222) Total lines: 208810/29/2026 - 12:17:11 AM Line coverage: 1.7% (14/809) Branch coverage: 4.5% (10/222) Total lines: 2097

Coverage delta

Coverage delta 2 -2

Metrics

File(s)

/srv/git/jellyfin/Jellyfin.Api/Controllers/DynamicHlsController.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.ComponentModel.DataAnnotations;
 4using System.Diagnostics.CodeAnalysis;
 5using System.Globalization;
 6using System.IO;
 7using System.Linq;
 8using System.Text;
 9using System.Threading;
 10using System.Threading.Tasks;
 11using Jellyfin.Api.Attributes;
 12using Jellyfin.Api.Extensions;
 13using Jellyfin.Api.Helpers;
 14using Jellyfin.Api.Models.StreamingDtos;
 15using Jellyfin.Data.Enums;
 16using Jellyfin.Extensions;
 17using Jellyfin.MediaEncoding.Hls.Playlist;
 18using MediaBrowser.Common.Configuration;
 19using MediaBrowser.Controller.Configuration;
 20using MediaBrowser.Controller.Library;
 21using MediaBrowser.Controller.MediaEncoding;
 22using MediaBrowser.Controller.Streaming;
 23using MediaBrowser.Model.Configuration;
 24using MediaBrowser.Model.Dlna;
 25using MediaBrowser.Model.Entities;
 26using MediaBrowser.Model.IO;
 27using MediaBrowser.Model.Net;
 28using Microsoft.AspNetCore.Authorization;
 29using Microsoft.AspNetCore.Http;
 30using Microsoft.AspNetCore.Mvc;
 31using Microsoft.Extensions.Logging;
 32
 33namespace Jellyfin.Api.Controllers;
 34
 35/// <summary>
 36/// Dynamic hls controller.
 37/// </summary>
 38[Route("")]
 39[Authorize]
 40[ApiExplorerSettings(IgnoreApi = true)]
 41public class DynamicHlsController : BaseJellyfinApiController
 42{
 43    private const EncoderPreset DefaultVodEncoderPreset = EncoderPreset.veryfast;
 44    private const EncoderPreset DefaultEventEncoderPreset = EncoderPreset.superfast;
 45    private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
 46
 047    private readonly Version _minFFmpegFlacInMp4 = new Version(6, 0);
 048    private readonly Version _minFFmpegX265BframeInFmp4 = new Version(7, 0, 1);
 049    private readonly Version _minFFmpegHlsSegmentOptions = new Version(5, 0);
 50
 51    private readonly ILibraryManager _libraryManager;
 52    private readonly IUserManager _userManager;
 53    private readonly IMediaSourceManager _mediaSourceManager;
 54    private readonly IServerConfigurationManager _serverConfigurationManager;
 55    private readonly IMediaEncoder _mediaEncoder;
 56    private readonly IFileSystem _fileSystem;
 57    private readonly ITranscodeManager _transcodeManager;
 58    private readonly ILogger<DynamicHlsController> _logger;
 59    private readonly EncodingHelper _encodingHelper;
 60    private readonly IDynamicHlsPlaylistGenerator _dynamicHlsPlaylistGenerator;
 61    private readonly DynamicHlsHelper _dynamicHlsHelper;
 62    private readonly EncodingOptions _encodingOptions;
 63
 64    /// <summary>
 65    /// Initializes a new instance of the <see cref="DynamicHlsController"/> class.
 66    /// </summary>
 67    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 68    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 69    /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
 70    /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</p
 71    /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
 72    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 73    /// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
 74    /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsController}"/> interface.</param>
 75    /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
 76    /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
 77    /// <param name="dynamicHlsPlaylistGenerator">Instance of <see cref="IDynamicHlsPlaylistGenerator"/>.</param>
 078    public DynamicHlsController(
 079        ILibraryManager libraryManager,
 080        IUserManager userManager,
 081        IMediaSourceManager mediaSourceManager,
 082        IServerConfigurationManager serverConfigurationManager,
 083        IMediaEncoder mediaEncoder,
 084        IFileSystem fileSystem,
 085        ITranscodeManager transcodeManager,
 086        ILogger<DynamicHlsController> logger,
 087        DynamicHlsHelper dynamicHlsHelper,
 088        EncodingHelper encodingHelper,
 089        IDynamicHlsPlaylistGenerator dynamicHlsPlaylistGenerator)
 90    {
 091        _libraryManager = libraryManager;
 092        _userManager = userManager;
 093        _mediaSourceManager = mediaSourceManager;
 094        _serverConfigurationManager = serverConfigurationManager;
 095        _mediaEncoder = mediaEncoder;
 096        _fileSystem = fileSystem;
 097        _transcodeManager = transcodeManager;
 098        _logger = logger;
 099        _dynamicHlsHelper = dynamicHlsHelper;
 0100        _encodingHelper = encodingHelper;
 0101        _dynamicHlsPlaylistGenerator = dynamicHlsPlaylistGenerator;
 102
 0103        _encodingOptions = serverConfigurationManager.GetEncodingOptions();
 0104    }
 105
 106    /// <summary>
 107    /// Gets a hls live stream.
 108    /// </summary>
 109    /// <param name="itemId">The item id.</param>
 110    /// <param name="container">The audio container.</param>
 111    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 112    /// <param name="params">The streaming parameters.</param>
 113    /// <param name="tag">The tag.</param>
 114    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 115    /// <param name="playSessionId">The play session id.</param>
 116    /// <param name="segmentContainer">The segment container.</param>
 117    /// <param name="segmentLength">The segment length.</param>
 118    /// <param name="minSegments">The minimum number of segments.</param>
 119    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 120    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 121    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 122    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 123    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 124    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 125    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 126    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 127    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 128    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 129    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 130    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 131    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 132    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 133    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 134    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 135    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 136    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 137    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 138    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 139    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 140    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 141    /// <param name="maxRefFrames">Optional.</param>
 142    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 143    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 144    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 145    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 146    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 147    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 148    /// <param name="liveStreamId">The live stream id.</param>
 149    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 150    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 151    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 152    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 153    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 154    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 155    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 156    /// <param name="streamOptions">Optional. The streaming options.</param>
 157    /// <param name="maxWidth">Optional. The max width.</param>
 158    /// <param name="maxHeight">Optional. The max height.</param>
 159    /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
 160    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 161    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 162    /// <response code="200">Hls live stream retrieved.</response>
 163    /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
 164    [HttpGet("Videos/{itemId}/live.m3u8")]
 165    [ProducesResponseType(StatusCodes.Status200OK)]
 166    [ProducesPlaylistFile]
 167    public async Task<ActionResult> GetLiveHlsStream(
 168        [FromRoute, Required] Guid itemId,
 169        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? container,
 170        [FromQuery] bool? @static,
 171        [FromQuery] string? @params,
 172        [FromQuery] string? tag,
 173        [FromQuery, ParameterObsolete] string? deviceProfileId,
 174        [FromQuery] string? playSessionId,
 175        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 176        [FromQuery] int? segmentLength,
 177        [FromQuery] int? minSegments,
 178        [FromQuery] string? mediaSourceId,
 179        [FromQuery] string? deviceId,
 180        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 181        [FromQuery] bool? enableAutoStreamCopy,
 182        [FromQuery] bool? allowVideoStreamCopy,
 183        [FromQuery] bool? allowAudioStreamCopy,
 184        [FromQuery] int? audioSampleRate,
 185        [FromQuery] int? maxAudioBitDepth,
 186        [FromQuery] int? audioBitRate,
 187        [FromQuery] int? audioChannels,
 188        [FromQuery] int? maxAudioChannels,
 189        [FromQuery] string? profile,
 190        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 191        [FromQuery] float? framerate,
 192        [FromQuery] float? maxFramerate,
 193        [FromQuery] bool? copyTimestamps,
 194        [FromQuery] long? startTimeTicks,
 195        [FromQuery] int? width,
 196        [FromQuery] int? height,
 197        [FromQuery] int? videoBitRate,
 198        [FromQuery] int? subtitleStreamIndex,
 199        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 200        [FromQuery] int? maxRefFrames,
 201        [FromQuery] int? maxVideoBitDepth,
 202        [FromQuery] bool? requireAvc,
 203        [FromQuery] bool? deInterlace,
 204        [FromQuery] bool? requireNonAnamorphic,
 205        [FromQuery] int? transcodingMaxAudioChannels,
 206        [FromQuery] int? cpuCoreLimit,
 207        [FromQuery] string? liveStreamId,
 208        [FromQuery] bool? enableMpegtsM2TsMode,
 209        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 210        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 211        [FromQuery] string? transcodeReasons,
 212        [FromQuery] int? audioStreamIndex,
 213        [FromQuery] int? videoStreamIndex,
 214        [FromQuery] EncodingContext? context,
 215        [FromQuery] Dictionary<string, string> streamOptions,
 216        [FromQuery] int? maxWidth,
 217        [FromQuery] int? maxHeight,
 218        [FromQuery] bool? enableSubtitlesInManifest,
 219        [FromQuery] bool enableAudioVbrEncoding = true,
 220        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 221    {
 0222        VideoRequestDto streamingRequest = new VideoRequestDto
 0223        {
 0224            Id = itemId,
 0225            Container = container,
 0226            Static = @static ?? false,
 0227            Params = @params,
 0228            Tag = tag,
 0229            PlaySessionId = playSessionId,
 0230            SegmentContainer = segmentContainer,
 0231            SegmentLength = segmentLength,
 0232            MinSegments = minSegments,
 0233            MediaSourceId = mediaSourceId,
 0234            DeviceId = deviceId,
 0235            AudioCodec = audioCodec,
 0236            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0237            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0238            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0239            AudioSampleRate = audioSampleRate,
 0240            MaxAudioChannels = maxAudioChannels,
 0241            AudioBitRate = audioBitRate,
 0242            MaxAudioBitDepth = maxAudioBitDepth,
 0243            AudioChannels = audioChannels,
 0244            Profile = profile,
 0245            Level = level,
 0246            Framerate = framerate,
 0247            MaxFramerate = maxFramerate,
 0248            CopyTimestamps = copyTimestamps ?? false,
 0249            StartTimeTicks = startTimeTicks,
 0250            Width = width,
 0251            Height = height,
 0252            VideoBitRate = videoBitRate,
 0253            SubtitleStreamIndex = subtitleStreamIndex,
 0254            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0255            MaxRefFrames = maxRefFrames,
 0256            MaxVideoBitDepth = maxVideoBitDepth,
 0257            RequireAvc = requireAvc ?? false,
 0258            DeInterlace = deInterlace ?? false,
 0259            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0260            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0261            CpuCoreLimit = cpuCoreLimit,
 0262            LiveStreamId = liveStreamId,
 0263            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0264            VideoCodec = videoCodec,
 0265            SubtitleCodec = subtitleCodec,
 0266            TranscodeReasons = transcodeReasons,
 0267            AudioStreamIndex = audioStreamIndex,
 0268            VideoStreamIndex = videoStreamIndex,
 0269            Context = context ?? EncodingContext.Streaming,
 0270            StreamOptions = streamOptions,
 0271            MaxHeight = maxHeight,
 0272            MaxWidth = maxWidth,
 0273            EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true,
 0274            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0275            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 0276        };
 277
 278        // CTS lifecycle is managed internally.
 0279        var cancellationTokenSource = new CancellationTokenSource();
 280        // Due to CTS.Token calling ThrowIfDisposed (https://github.com/dotnet/runtime/issues/29970) we have to "cache" 
 281        // since it gets disposed when ffmpeg exits
 0282        var cancellationToken = cancellationTokenSource.Token;
 0283        var state = await StreamingHelpers.GetStreamingState(
 0284                streamingRequest,
 0285                HttpContext,
 0286                _mediaSourceManager,
 0287                _userManager,
 0288                _libraryManager,
 0289                _serverConfigurationManager,
 0290                _mediaEncoder,
 0291                _encodingHelper,
 0292                _transcodeManager,
 0293                TranscodingJobType,
 0294                cancellationToken)
 0295            .ConfigureAwait(false);
 296
 0297        TranscodingJob? job = null;
 0298        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 299
 0300        if (!System.IO.File.Exists(playlistPath))
 301        {
 0302            using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 303            {
 0304                if (!System.IO.File.Exists(playlistPath))
 305                {
 306                    // If the playlist doesn't already exist, startup ffmpeg
 307                    try
 308                    {
 0309                        job = await _transcodeManager.StartFfMpeg(
 0310                                state,
 0311                                playlistPath,
 0312                                GetCommandLineArguments(playlistPath, state, true, 0),
 0313                                Request.HttpContext.User.GetUserId(),
 0314                                TranscodingJobType,
 0315                                cancellationTokenSource)
 0316                            .ConfigureAwait(false);
 0317                        job.IsLiveOutput = true;
 0318                    }
 0319                    catch
 320                    {
 0321                        state.Dispose();
 0322                        throw;
 323                    }
 324
 0325                    minSegments = state.MinSegments;
 0326                    if (minSegments > 0)
 327                    {
 0328                        await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationToke
 329                    }
 330                }
 0331            }
 332        }
 333
 0334        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 335
 0336        if (job is not null)
 337        {
 0338            _transcodeManager.OnTranscodeEndRequest(job);
 339        }
 340
 0341        var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);
 342
 0343        return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
 0344    }
 345
 346    /// <summary>
 347    /// Gets a video hls playlist stream.
 348    /// </summary>
 349    /// <param name="itemId">The item id.</param>
 350    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 351    /// <param name="params">The streaming parameters.</param>
 352    /// <param name="tag">The tag.</param>
 353    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 354    /// <param name="playSessionId">The play session id.</param>
 355    /// <param name="segmentContainer">The segment container.</param>
 356    /// <param name="segmentLength">The segment length.</param>
 357    /// <param name="minSegments">The minimum number of segments.</param>
 358    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 359    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 360    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 361    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 362    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 363    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 364    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 365    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 366    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 367    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 368    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 369    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 370    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 371    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 372    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 373    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 374    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 375    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 376    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 377    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 378    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 379    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 380    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 381    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 382    /// <param name="maxRefFrames">Optional.</param>
 383    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 384    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 385    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 386    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 387    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 388    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 389    /// <param name="liveStreamId">The live stream id.</param>
 390    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 391    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 392    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 393    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 394    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 395    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 396    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 397    /// <param name="streamOptions">Optional. The streaming options.</param>
 398    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 399    /// <param name="enableTrickplay">Enable trickplay image playlists being added to master playlist.</param>
 400    /// <param name="enableAudioVbrEncoding">Whether to enable Audio Encoding.</param>
 401    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 402    /// <response code="200">Video stream returned.</response>
 403    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 404    [HttpGet("Videos/{itemId}/master.m3u8")]
 405    [HttpHead("Videos/{itemId}/master.m3u8", Name = "HeadMasterHlsVideoPlaylist")]
 406    [ProducesResponseType(StatusCodes.Status200OK)]
 407    [ProducesPlaylistFile]
 408    public async Task<ActionResult> GetMasterHlsVideoPlaylist(
 409        [FromRoute, Required] Guid itemId,
 410        [FromQuery] bool? @static,
 411        [FromQuery] string? @params,
 412        [FromQuery] string? tag,
 413        [FromQuery, ParameterObsolete] string? deviceProfileId,
 414        [FromQuery] string? playSessionId,
 415        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 416        [FromQuery] int? segmentLength,
 417        [FromQuery] int? minSegments,
 418        [FromQuery, Required] string mediaSourceId,
 419        [FromQuery] string? deviceId,
 420        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 421        [FromQuery] bool? enableAutoStreamCopy,
 422        [FromQuery] bool? allowVideoStreamCopy,
 423        [FromQuery] bool? allowAudioStreamCopy,
 424        [FromQuery] int? audioSampleRate,
 425        [FromQuery] int? maxAudioBitDepth,
 426        [FromQuery] int? audioBitRate,
 427        [FromQuery] int? audioChannels,
 428        [FromQuery] int? maxAudioChannels,
 429        [FromQuery] string? profile,
 430        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 431        [FromQuery] float? framerate,
 432        [FromQuery] float? maxFramerate,
 433        [FromQuery] bool? copyTimestamps,
 434        [FromQuery] long? startTimeTicks,
 435        [FromQuery] int? width,
 436        [FromQuery] int? height,
 437        [FromQuery] int? maxWidth,
 438        [FromQuery] int? maxHeight,
 439        [FromQuery] int? videoBitRate,
 440        [FromQuery] int? subtitleStreamIndex,
 441        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 442        [FromQuery] int? maxRefFrames,
 443        [FromQuery] int? maxVideoBitDepth,
 444        [FromQuery] bool? requireAvc,
 445        [FromQuery] bool? deInterlace,
 446        [FromQuery] bool? requireNonAnamorphic,
 447        [FromQuery] int? transcodingMaxAudioChannels,
 448        [FromQuery] int? cpuCoreLimit,
 449        [FromQuery] string? liveStreamId,
 450        [FromQuery] bool? enableMpegtsM2TsMode,
 451        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 452        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 453        [FromQuery] string? transcodeReasons,
 454        [FromQuery] int? audioStreamIndex,
 455        [FromQuery] int? videoStreamIndex,
 456        [FromQuery] EncodingContext? context,
 457        [FromQuery] Dictionary<string, string> streamOptions,
 458        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 459        [FromQuery] bool enableTrickplay = true,
 460        [FromQuery] bool enableAudioVbrEncoding = true,
 461        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 462    {
 0463        var streamingRequest = new HlsVideoRequestDto
 0464        {
 0465            Id = itemId,
 0466            Static = @static ?? false,
 0467            Params = @params,
 0468            Tag = tag,
 0469            PlaySessionId = playSessionId,
 0470            SegmentContainer = segmentContainer,
 0471            SegmentLength = segmentLength,
 0472            MinSegments = minSegments,
 0473            MediaSourceId = mediaSourceId,
 0474            DeviceId = deviceId,
 0475            AudioCodec = audioCodec,
 0476            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0477            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0478            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0479            AudioSampleRate = audioSampleRate,
 0480            MaxAudioChannels = maxAudioChannels,
 0481            AudioBitRate = audioBitRate,
 0482            MaxAudioBitDepth = maxAudioBitDepth,
 0483            AudioChannels = audioChannels,
 0484            Profile = profile,
 0485            Level = level,
 0486            Framerate = framerate,
 0487            MaxFramerate = maxFramerate,
 0488            CopyTimestamps = copyTimestamps ?? false,
 0489            StartTimeTicks = startTimeTicks,
 0490            Width = width,
 0491            Height = height,
 0492            MaxWidth = maxWidth,
 0493            MaxHeight = maxHeight,
 0494            VideoBitRate = videoBitRate,
 0495            SubtitleStreamIndex = subtitleStreamIndex,
 0496            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0497            MaxRefFrames = maxRefFrames,
 0498            MaxVideoBitDepth = maxVideoBitDepth,
 0499            RequireAvc = requireAvc ?? false,
 0500            DeInterlace = deInterlace ?? false,
 0501            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0502            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0503            CpuCoreLimit = cpuCoreLimit,
 0504            LiveStreamId = liveStreamId,
 0505            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0506            VideoCodec = videoCodec,
 0507            SubtitleCodec = subtitleCodec,
 0508            TranscodeReasons = transcodeReasons,
 0509            AudioStreamIndex = audioStreamIndex,
 0510            VideoStreamIndex = videoStreamIndex,
 0511            Context = context ?? EncodingContext.Streaming,
 0512            StreamOptions = streamOptions,
 0513            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 0514            EnableTrickplay = enableTrickplay,
 0515            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0516            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 0517        };
 518
 0519        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 0520    }
 521
 522    /// <summary>
 523    /// Gets an audio hls playlist stream.
 524    /// </summary>
 525    /// <param name="itemId">The item id.</param>
 526    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 527    /// <param name="params">The streaming parameters.</param>
 528    /// <param name="tag">The tag.</param>
 529    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 530    /// <param name="playSessionId">The play session id.</param>
 531    /// <param name="segmentContainer">The segment container.</param>
 532    /// <param name="segmentLength">The segment length.</param>
 533    /// <param name="minSegments">The minimum number of segments.</param>
 534    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 535    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 536    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 537    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 538    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 539    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 540    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 541    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 542    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 543    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 544    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 545    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 546    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 547    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 548    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 549    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 550    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 551    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 552    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 553    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 554    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 555    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 556    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 557    /// <param name="maxRefFrames">Optional.</param>
 558    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 559    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 560    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 561    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 562    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 563    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 564    /// <param name="liveStreamId">The live stream id.</param>
 565    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 566    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 567    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 568    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 569    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 570    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 571    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 572    /// <param name="streamOptions">Optional. The streaming options.</param>
 573    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 574    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 575    /// <response code="200">Audio stream returned.</response>
 576    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 577    [HttpGet("Audio/{itemId}/master.m3u8")]
 578    [HttpHead("Audio/{itemId}/master.m3u8", Name = "HeadMasterHlsAudioPlaylist")]
 579    [ProducesResponseType(StatusCodes.Status200OK)]
 580    [ProducesPlaylistFile]
 581    public async Task<ActionResult> GetMasterHlsAudioPlaylist(
 582        [FromRoute, Required] Guid itemId,
 583        [FromQuery] bool? @static,
 584        [FromQuery] string? @params,
 585        [FromQuery] string? tag,
 586        [FromQuery, ParameterObsolete] string? deviceProfileId,
 587        [FromQuery] string? playSessionId,
 588        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 589        [FromQuery] int? segmentLength,
 590        [FromQuery] int? minSegments,
 591        [FromQuery, Required] string mediaSourceId,
 592        [FromQuery] string? deviceId,
 593        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 594        [FromQuery] bool? enableAutoStreamCopy,
 595        [FromQuery] bool? allowVideoStreamCopy,
 596        [FromQuery] bool? allowAudioStreamCopy,
 597        [FromQuery] int? audioSampleRate,
 598        [FromQuery] int? maxAudioBitDepth,
 599        [FromQuery] int? maxStreamingBitrate,
 600        [FromQuery] int? audioBitRate,
 601        [FromQuery] int? audioChannels,
 602        [FromQuery] int? maxAudioChannels,
 603        [FromQuery] string? profile,
 604        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 605        [FromQuery] float? framerate,
 606        [FromQuery] float? maxFramerate,
 607        [FromQuery] bool? copyTimestamps,
 608        [FromQuery] long? startTimeTicks,
 609        [FromQuery] int? width,
 610        [FromQuery] int? height,
 611        [FromQuery] int? videoBitRate,
 612        [FromQuery] int? subtitleStreamIndex,
 613        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 614        [FromQuery] int? maxRefFrames,
 615        [FromQuery] int? maxVideoBitDepth,
 616        [FromQuery] bool? requireAvc,
 617        [FromQuery] bool? deInterlace,
 618        [FromQuery] bool? requireNonAnamorphic,
 619        [FromQuery] int? transcodingMaxAudioChannels,
 620        [FromQuery] int? cpuCoreLimit,
 621        [FromQuery] string? liveStreamId,
 622        [FromQuery] bool? enableMpegtsM2TsMode,
 623        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 624        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 625        [FromQuery] string? transcodeReasons,
 626        [FromQuery] int? audioStreamIndex,
 627        [FromQuery] int? videoStreamIndex,
 628        [FromQuery] EncodingContext? context,
 629        [FromQuery] Dictionary<string, string> streamOptions,
 630        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 631        [FromQuery] bool enableAudioVbrEncoding = true)
 632    {
 0633        var streamingRequest = new HlsAudioRequestDto
 0634        {
 0635            Id = itemId,
 0636            Static = @static ?? false,
 0637            Params = @params,
 0638            Tag = tag,
 0639            PlaySessionId = playSessionId,
 0640            SegmentContainer = segmentContainer,
 0641            SegmentLength = segmentLength,
 0642            MinSegments = minSegments,
 0643            MediaSourceId = mediaSourceId,
 0644            DeviceId = deviceId,
 0645            AudioCodec = audioCodec,
 0646            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0647            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0648            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0649            AudioSampleRate = audioSampleRate,
 0650            MaxAudioChannels = maxAudioChannels,
 0651            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 0652            MaxAudioBitDepth = maxAudioBitDepth,
 0653            AudioChannels = audioChannels,
 0654            Profile = profile,
 0655            Level = level,
 0656            Framerate = framerate,
 0657            MaxFramerate = maxFramerate,
 0658            CopyTimestamps = copyTimestamps ?? false,
 0659            StartTimeTicks = startTimeTicks,
 0660            Width = width,
 0661            Height = height,
 0662            VideoBitRate = videoBitRate,
 0663            SubtitleStreamIndex = subtitleStreamIndex,
 0664            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0665            MaxRefFrames = maxRefFrames,
 0666            MaxVideoBitDepth = maxVideoBitDepth,
 0667            RequireAvc = requireAvc ?? false,
 0668            DeInterlace = deInterlace ?? false,
 0669            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0670            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0671            CpuCoreLimit = cpuCoreLimit,
 0672            LiveStreamId = liveStreamId,
 0673            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0674            VideoCodec = videoCodec,
 0675            SubtitleCodec = subtitleCodec,
 0676            TranscodeReasons = transcodeReasons,
 0677            AudioStreamIndex = audioStreamIndex,
 0678            VideoStreamIndex = videoStreamIndex,
 0679            Context = context ?? EncodingContext.Streaming,
 0680            StreamOptions = streamOptions,
 0681            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 0682            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0683            AlwaysBurnInSubtitleWhenTranscoding = false
 0684        };
 685
 0686        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 0687    }
 688
 689    /// <summary>
 690    /// Gets a video stream using HTTP live streaming.
 691    /// </summary>
 692    /// <param name="itemId">The item id.</param>
 693    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 694    /// <param name="params">The streaming parameters.</param>
 695    /// <param name="tag">The tag.</param>
 696    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 697    /// <param name="playSessionId">The play session id.</param>
 698    /// <param name="segmentContainer">The segment container.</param>
 699    /// <param name="segmentLength">The segment length.</param>
 700    /// <param name="minSegments">The minimum number of segments.</param>
 701    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 702    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 703    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 704    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 705    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 706    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 707    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 708    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 709    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 710    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 711    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 712    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 713    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 714    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 715    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 716    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 717    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 718    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 719    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 720    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 721    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 722    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 723    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 724    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 725    /// <param name="maxRefFrames">Optional.</param>
 726    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 727    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 728    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 729    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 730    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 731    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 732    /// <param name="liveStreamId">The live stream id.</param>
 733    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 734    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 735    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 736    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 737    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 738    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 739    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 740    /// <param name="streamOptions">Optional. The streaming options.</param>
 741    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 742    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 743    /// <response code="200">Video stream returned.</response>
 744    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 745    [HttpGet("Videos/{itemId}/main.m3u8")]
 746    [ProducesResponseType(StatusCodes.Status200OK)]
 747    [ProducesPlaylistFile]
 748    public async Task<ActionResult> GetVariantHlsVideoPlaylist(
 749        [FromRoute, Required] Guid itemId,
 750        [FromQuery] bool? @static,
 751        [FromQuery] string? @params,
 752        [FromQuery] string? tag,
 753        [FromQuery, ParameterObsolete] string? deviceProfileId,
 754        [FromQuery] string? playSessionId,
 755        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 756        [FromQuery] int? segmentLength,
 757        [FromQuery] int? minSegments,
 758        [FromQuery] string? mediaSourceId,
 759        [FromQuery] string? deviceId,
 760        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 761        [FromQuery] bool? enableAutoStreamCopy,
 762        [FromQuery] bool? allowVideoStreamCopy,
 763        [FromQuery] bool? allowAudioStreamCopy,
 764        [FromQuery] int? audioSampleRate,
 765        [FromQuery] int? maxAudioBitDepth,
 766        [FromQuery] int? audioBitRate,
 767        [FromQuery] int? audioChannels,
 768        [FromQuery] int? maxAudioChannels,
 769        [FromQuery] string? profile,
 770        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 771        [FromQuery] float? framerate,
 772        [FromQuery] float? maxFramerate,
 773        [FromQuery] bool? copyTimestamps,
 774        [FromQuery] long? startTimeTicks,
 775        [FromQuery] int? width,
 776        [FromQuery] int? height,
 777        [FromQuery] int? maxWidth,
 778        [FromQuery] int? maxHeight,
 779        [FromQuery] int? videoBitRate,
 780        [FromQuery] int? subtitleStreamIndex,
 781        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 782        [FromQuery] int? maxRefFrames,
 783        [FromQuery] int? maxVideoBitDepth,
 784        [FromQuery] bool? requireAvc,
 785        [FromQuery] bool? deInterlace,
 786        [FromQuery] bool? requireNonAnamorphic,
 787        [FromQuery] int? transcodingMaxAudioChannels,
 788        [FromQuery] int? cpuCoreLimit,
 789        [FromQuery] string? liveStreamId,
 790        [FromQuery] bool? enableMpegtsM2TsMode,
 791        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 792        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 793        [FromQuery] string? transcodeReasons,
 794        [FromQuery] int? audioStreamIndex,
 795        [FromQuery] int? videoStreamIndex,
 796        [FromQuery] EncodingContext? context,
 797        [FromQuery] Dictionary<string, string> streamOptions,
 798        [FromQuery] bool enableAudioVbrEncoding = true,
 799        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 800    {
 0801        using var cancellationTokenSource = new CancellationTokenSource();
 0802        var streamingRequest = new VideoRequestDto
 0803        {
 0804            Id = itemId,
 0805            Static = @static ?? false,
 0806            Params = @params,
 0807            Tag = tag,
 0808            PlaySessionId = playSessionId,
 0809            SegmentContainer = segmentContainer,
 0810            SegmentLength = segmentLength,
 0811            MinSegments = minSegments,
 0812            MediaSourceId = mediaSourceId,
 0813            DeviceId = deviceId,
 0814            AudioCodec = audioCodec,
 0815            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0816            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0817            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0818            AudioSampleRate = audioSampleRate,
 0819            MaxAudioChannels = maxAudioChannels,
 0820            AudioBitRate = audioBitRate,
 0821            MaxAudioBitDepth = maxAudioBitDepth,
 0822            AudioChannels = audioChannels,
 0823            Profile = profile,
 0824            Level = level,
 0825            Framerate = framerate,
 0826            MaxFramerate = maxFramerate,
 0827            CopyTimestamps = copyTimestamps ?? false,
 0828            StartTimeTicks = startTimeTicks,
 0829            Width = width,
 0830            Height = height,
 0831            MaxWidth = maxWidth,
 0832            MaxHeight = maxHeight,
 0833            VideoBitRate = videoBitRate,
 0834            SubtitleStreamIndex = subtitleStreamIndex,
 0835            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0836            MaxRefFrames = maxRefFrames,
 0837            MaxVideoBitDepth = maxVideoBitDepth,
 0838            RequireAvc = requireAvc ?? false,
 0839            DeInterlace = deInterlace ?? false,
 0840            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0841            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0842            CpuCoreLimit = cpuCoreLimit,
 0843            LiveStreamId = liveStreamId,
 0844            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0845            VideoCodec = videoCodec,
 0846            SubtitleCodec = subtitleCodec,
 0847            TranscodeReasons = transcodeReasons,
 0848            AudioStreamIndex = audioStreamIndex,
 0849            VideoStreamIndex = videoStreamIndex,
 0850            Context = context ?? EncodingContext.Streaming,
 0851            StreamOptions = streamOptions,
 0852            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0853            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 0854        };
 855
 0856        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 0857            .ConfigureAwait(false);
 0858    }
 859
 860    /// <summary>
 861    /// Gets an audio stream using HTTP live streaming.
 862    /// </summary>
 863    /// <param name="itemId">The item id.</param>
 864    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 865    /// <param name="params">The streaming parameters.</param>
 866    /// <param name="tag">The tag.</param>
 867    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 868    /// <param name="playSessionId">The play session id.</param>
 869    /// <param name="segmentContainer">The segment container.</param>
 870    /// <param name="segmentLength">The segment length.</param>
 871    /// <param name="minSegments">The minimum number of segments.</param>
 872    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 873    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 874    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 875    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 876    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 877    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 878    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 879    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 880    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 881    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 882    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 883    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 884    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 885    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 886    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 887    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 888    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 889    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 890    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 891    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 892    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 893    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 894    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 895    /// <param name="maxRefFrames">Optional.</param>
 896    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 897    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 898    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 899    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 900    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 901    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 902    /// <param name="liveStreamId">The live stream id.</param>
 903    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 904    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 905    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 906    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 907    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 908    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 909    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 910    /// <param name="streamOptions">Optional. The streaming options.</param>
 911    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 912    /// <response code="200">Audio stream returned.</response>
 913    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 914    [HttpGet("Audio/{itemId}/main.m3u8")]
 915    [ProducesResponseType(StatusCodes.Status200OK)]
 916    [ProducesPlaylistFile]
 917    public async Task<ActionResult> GetVariantHlsAudioPlaylist(
 918        [FromRoute, Required] Guid itemId,
 919        [FromQuery] bool? @static,
 920        [FromQuery] string? @params,
 921        [FromQuery] string? tag,
 922        [FromQuery, ParameterObsolete] string? deviceProfileId,
 923        [FromQuery] string? playSessionId,
 924        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 925        [FromQuery] int? segmentLength,
 926        [FromQuery] int? minSegments,
 927        [FromQuery] string? mediaSourceId,
 928        [FromQuery] string? deviceId,
 929        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 930        [FromQuery] bool? enableAutoStreamCopy,
 931        [FromQuery] bool? allowVideoStreamCopy,
 932        [FromQuery] bool? allowAudioStreamCopy,
 933        [FromQuery] int? audioSampleRate,
 934        [FromQuery] int? maxAudioBitDepth,
 935        [FromQuery] int? maxStreamingBitrate,
 936        [FromQuery] int? audioBitRate,
 937        [FromQuery] int? audioChannels,
 938        [FromQuery] int? maxAudioChannels,
 939        [FromQuery] string? profile,
 940        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 941        [FromQuery] float? framerate,
 942        [FromQuery] float? maxFramerate,
 943        [FromQuery] bool? copyTimestamps,
 944        [FromQuery] long? startTimeTicks,
 945        [FromQuery] int? width,
 946        [FromQuery] int? height,
 947        [FromQuery] int? videoBitRate,
 948        [FromQuery] int? subtitleStreamIndex,
 949        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 950        [FromQuery] int? maxRefFrames,
 951        [FromQuery] int? maxVideoBitDepth,
 952        [FromQuery] bool? requireAvc,
 953        [FromQuery] bool? deInterlace,
 954        [FromQuery] bool? requireNonAnamorphic,
 955        [FromQuery] int? transcodingMaxAudioChannels,
 956        [FromQuery] int? cpuCoreLimit,
 957        [FromQuery] string? liveStreamId,
 958        [FromQuery] bool? enableMpegtsM2TsMode,
 959        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 960        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 961        [FromQuery] string? transcodeReasons,
 962        [FromQuery] int? audioStreamIndex,
 963        [FromQuery] int? videoStreamIndex,
 964        [FromQuery] EncodingContext? context,
 965        [FromQuery] Dictionary<string, string> streamOptions,
 966        [FromQuery] bool enableAudioVbrEncoding = true)
 967    {
 0968        using var cancellationTokenSource = new CancellationTokenSource();
 0969        var streamingRequest = new StreamingRequestDto
 0970        {
 0971            Id = itemId,
 0972            Static = @static ?? false,
 0973            Params = @params,
 0974            Tag = tag,
 0975            PlaySessionId = playSessionId,
 0976            SegmentContainer = segmentContainer,
 0977            SegmentLength = segmentLength,
 0978            MinSegments = minSegments,
 0979            MediaSourceId = mediaSourceId,
 0980            DeviceId = deviceId,
 0981            AudioCodec = audioCodec,
 0982            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0983            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0984            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0985            AudioSampleRate = audioSampleRate,
 0986            MaxAudioChannels = maxAudioChannels,
 0987            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 0988            MaxAudioBitDepth = maxAudioBitDepth,
 0989            AudioChannels = audioChannels,
 0990            Profile = profile,
 0991            Level = level,
 0992            Framerate = framerate,
 0993            MaxFramerate = maxFramerate,
 0994            CopyTimestamps = copyTimestamps ?? false,
 0995            StartTimeTicks = startTimeTicks,
 0996            Width = width,
 0997            Height = height,
 0998            VideoBitRate = videoBitRate,
 0999            SubtitleStreamIndex = subtitleStreamIndex,
 01000            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 01001            MaxRefFrames = maxRefFrames,
 01002            MaxVideoBitDepth = maxVideoBitDepth,
 01003            RequireAvc = requireAvc ?? false,
 01004            DeInterlace = deInterlace ?? false,
 01005            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 01006            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 01007            CpuCoreLimit = cpuCoreLimit,
 01008            LiveStreamId = liveStreamId,
 01009            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 01010            VideoCodec = videoCodec,
 01011            SubtitleCodec = subtitleCodec,
 01012            TranscodeReasons = transcodeReasons,
 01013            AudioStreamIndex = audioStreamIndex,
 01014            VideoStreamIndex = videoStreamIndex,
 01015            Context = context ?? EncodingContext.Streaming,
 01016            StreamOptions = streamOptions,
 01017            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 01018            AlwaysBurnInSubtitleWhenTranscoding = false
 01019        };
 1020
 01021        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 01022            .ConfigureAwait(false);
 01023    }
 1024
 1025    /// <summary>
 1026    /// Gets a video stream using HTTP live streaming.
 1027    /// </summary>
 1028    /// <param name="itemId">The item id.</param>
 1029    /// <param name="playlistId">The playlist id.</param>
 1030    /// <param name="segmentId">The segment id.</param>
 1031    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1032    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1033    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1034    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1035    /// <param name="params">The streaming parameters.</param>
 1036    /// <param name="tag">The tag.</param>
 1037    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1038    /// <param name="playSessionId">The play session id.</param>
 1039    /// <param name="segmentContainer">The segment container.</param>
 1040    /// <param name="segmentLength">The desired segment length.</param>
 1041    /// <param name="minSegments">The minimum number of segments.</param>
 1042    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1043    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1044    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1045    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1046    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1047    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1048    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1049    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1050    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1051    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1052    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1053    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1054    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1055    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1056    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1057    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1058    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1059    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1060    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1061    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 1062    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 1063    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1064    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1065    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1066    /// <param name="maxRefFrames">Optional.</param>
 1067    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1068    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1069    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1070    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1071    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1072    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1073    /// <param name="liveStreamId">The live stream id.</param>
 1074    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1075    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1076    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1077    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1078    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1079    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1080    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1081    /// <param name="streamOptions">Optional. The streaming options.</param>
 1082    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1083    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 1084    /// <response code="200">Video stream returned.</response>
 1085    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1086    [HttpGet("Videos/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1087    [ProducesResponseType(StatusCodes.Status200OK)]
 1088    [ProducesVideoFile]
 1089    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1090    public async Task<ActionResult> GetHlsVideoSegment(
 1091        [FromRoute, Required] Guid itemId,
 1092        [FromRoute, Required] string playlistId,
 1093        [FromRoute, Required] int segmentId,
 1094        [FromRoute, Required][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string container,
 1095        [FromQuery, Required] long runtimeTicks,
 1096        [FromQuery, Required] long actualSegmentLengthTicks,
 1097        [FromQuery] bool? @static,
 1098        [FromQuery] string? @params,
 1099        [FromQuery] string? tag,
 1100        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1101        [FromQuery] string? playSessionId,
 1102        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 1103        [FromQuery] int? segmentLength,
 1104        [FromQuery] int? minSegments,
 1105        [FromQuery] string? mediaSourceId,
 1106        [FromQuery] string? deviceId,
 1107        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 1108        [FromQuery] bool? enableAutoStreamCopy,
 1109        [FromQuery] bool? allowVideoStreamCopy,
 1110        [FromQuery] bool? allowAudioStreamCopy,
 1111        [FromQuery] int? audioSampleRate,
 1112        [FromQuery] int? maxAudioBitDepth,
 1113        [FromQuery] int? audioBitRate,
 1114        [FromQuery] int? audioChannels,
 1115        [FromQuery] int? maxAudioChannels,
 1116        [FromQuery] string? profile,
 1117        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 1118        [FromQuery] float? framerate,
 1119        [FromQuery] float? maxFramerate,
 1120        [FromQuery] bool? copyTimestamps,
 1121        [FromQuery] long? startTimeTicks,
 1122        [FromQuery] int? width,
 1123        [FromQuery] int? height,
 1124        [FromQuery] int? maxWidth,
 1125        [FromQuery] int? maxHeight,
 1126        [FromQuery] int? videoBitRate,
 1127        [FromQuery] int? subtitleStreamIndex,
 1128        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1129        [FromQuery] int? maxRefFrames,
 1130        [FromQuery] int? maxVideoBitDepth,
 1131        [FromQuery] bool? requireAvc,
 1132        [FromQuery] bool? deInterlace,
 1133        [FromQuery] bool? requireNonAnamorphic,
 1134        [FromQuery] int? transcodingMaxAudioChannels,
 1135        [FromQuery] int? cpuCoreLimit,
 1136        [FromQuery] string? liveStreamId,
 1137        [FromQuery] bool? enableMpegtsM2TsMode,
 1138        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 1139        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 1140        [FromQuery] string? transcodeReasons,
 1141        [FromQuery] int? audioStreamIndex,
 1142        [FromQuery] int? videoStreamIndex,
 1143        [FromQuery] EncodingContext? context,
 1144        [FromQuery] Dictionary<string, string> streamOptions,
 1145        [FromQuery] bool enableAudioVbrEncoding = true,
 1146        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 1147    {
 01148        var streamingRequest = new VideoRequestDto
 01149        {
 01150            Id = itemId,
 01151            CurrentRuntimeTicks = runtimeTicks,
 01152            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 01153            Container = container,
 01154            Static = @static ?? false,
 01155            Params = @params,
 01156            Tag = tag,
 01157            PlaySessionId = playSessionId,
 01158            SegmentContainer = segmentContainer,
 01159            SegmentLength = segmentLength,
 01160            MinSegments = minSegments,
 01161            MediaSourceId = mediaSourceId,
 01162            DeviceId = deviceId,
 01163            AudioCodec = audioCodec,
 01164            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 01165            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 01166            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 01167            AudioSampleRate = audioSampleRate,
 01168            MaxAudioChannels = maxAudioChannels,
 01169            AudioBitRate = audioBitRate,
 01170            MaxAudioBitDepth = maxAudioBitDepth,
 01171            AudioChannels = audioChannels,
 01172            Profile = profile,
 01173            Level = level,
 01174            Framerate = framerate,
 01175            MaxFramerate = maxFramerate,
 01176            CopyTimestamps = copyTimestamps ?? false,
 01177            StartTimeTicks = startTimeTicks,
 01178            Width = width,
 01179            Height = height,
 01180            MaxWidth = maxWidth,
 01181            MaxHeight = maxHeight,
 01182            VideoBitRate = videoBitRate,
 01183            SubtitleStreamIndex = subtitleStreamIndex,
 01184            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 01185            MaxRefFrames = maxRefFrames,
 01186            MaxVideoBitDepth = maxVideoBitDepth,
 01187            RequireAvc = requireAvc ?? false,
 01188            DeInterlace = deInterlace ?? false,
 01189            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 01190            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 01191            CpuCoreLimit = cpuCoreLimit,
 01192            LiveStreamId = liveStreamId,
 01193            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 01194            VideoCodec = videoCodec,
 01195            SubtitleCodec = subtitleCodec,
 01196            TranscodeReasons = transcodeReasons,
 01197            AudioStreamIndex = audioStreamIndex,
 01198            VideoStreamIndex = videoStreamIndex,
 01199            Context = context ?? EncodingContext.Streaming,
 01200            StreamOptions = streamOptions,
 01201            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 01202            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 01203        };
 1204
 01205        return await GetDynamicSegment(streamingRequest, segmentId)
 01206            .ConfigureAwait(false);
 01207    }
 1208
 1209    /// <summary>
 1210    /// Gets a video stream using HTTP live streaming.
 1211    /// </summary>
 1212    /// <param name="itemId">The item id.</param>
 1213    /// <param name="playlistId">The playlist id.</param>
 1214    /// <param name="segmentId">The segment id.</param>
 1215    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1216    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1217    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1218    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1219    /// <param name="params">The streaming parameters.</param>
 1220    /// <param name="tag">The tag.</param>
 1221    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1222    /// <param name="playSessionId">The play session id.</param>
 1223    /// <param name="segmentContainer">The segment container.</param>
 1224    /// <param name="segmentLength">The segment length.</param>
 1225    /// <param name="minSegments">The minimum number of segments.</param>
 1226    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1227    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1228    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1229    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1230    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1231    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1232    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1233    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1234    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 1235    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1236    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1237    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1238    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1239    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1240    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1241    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1242    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1243    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1244    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1245    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1246    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1247    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1248    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1249    /// <param name="maxRefFrames">Optional.</param>
 1250    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1251    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1252    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1253    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1254    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1255    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1256    /// <param name="liveStreamId">The live stream id.</param>
 1257    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1258    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1259    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1260    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1261    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1262    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1263    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1264    /// <param name="streamOptions">Optional. The streaming options.</param>
 1265    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1266    /// <response code="200">Video stream returned.</response>
 1267    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1268    [HttpGet("Audio/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1269    [ProducesResponseType(StatusCodes.Status200OK)]
 1270    [ProducesAudioFile]
 1271    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1272    public async Task<ActionResult> GetHlsAudioSegment(
 1273        [FromRoute, Required] Guid itemId,
 1274        [FromRoute, Required] string playlistId,
 1275        [FromRoute, Required] int segmentId,
 1276        [FromRoute, Required][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string container,
 1277        [FromQuery, Required] long runtimeTicks,
 1278        [FromQuery, Required] long actualSegmentLengthTicks,
 1279        [FromQuery] bool? @static,
 1280        [FromQuery] string? @params,
 1281        [FromQuery] string? tag,
 1282        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1283        [FromQuery] string? playSessionId,
 1284        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 1285        [FromQuery] int? segmentLength,
 1286        [FromQuery] int? minSegments,
 1287        [FromQuery] string? mediaSourceId,
 1288        [FromQuery] string? deviceId,
 1289        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 1290        [FromQuery] bool? enableAutoStreamCopy,
 1291        [FromQuery] bool? allowVideoStreamCopy,
 1292        [FromQuery] bool? allowAudioStreamCopy,
 1293        [FromQuery] int? audioSampleRate,
 1294        [FromQuery] int? maxAudioBitDepth,
 1295        [FromQuery] int? maxStreamingBitrate,
 1296        [FromQuery] int? audioBitRate,
 1297        [FromQuery] int? audioChannels,
 1298        [FromQuery] int? maxAudioChannels,
 1299        [FromQuery] string? profile,
 1300        [FromQuery][RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 1301        [FromQuery] float? framerate,
 1302        [FromQuery] float? maxFramerate,
 1303        [FromQuery] bool? copyTimestamps,
 1304        [FromQuery] long? startTimeTicks,
 1305        [FromQuery] int? width,
 1306        [FromQuery] int? height,
 1307        [FromQuery] int? videoBitRate,
 1308        [FromQuery] int? subtitleStreamIndex,
 1309        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1310        [FromQuery] int? maxRefFrames,
 1311        [FromQuery] int? maxVideoBitDepth,
 1312        [FromQuery] bool? requireAvc,
 1313        [FromQuery] bool? deInterlace,
 1314        [FromQuery] bool? requireNonAnamorphic,
 1315        [FromQuery] int? transcodingMaxAudioChannels,
 1316        [FromQuery] int? cpuCoreLimit,
 1317        [FromQuery] string? liveStreamId,
 1318        [FromQuery] bool? enableMpegtsM2TsMode,
 1319        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 1320        [FromQuery][RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 1321        [FromQuery] string? transcodeReasons,
 1322        [FromQuery] int? audioStreamIndex,
 1323        [FromQuery] int? videoStreamIndex,
 1324        [FromQuery] EncodingContext? context,
 1325        [FromQuery] Dictionary<string, string> streamOptions,
 1326        [FromQuery] bool enableAudioVbrEncoding = true)
 1327    {
 01328        var streamingRequest = new StreamingRequestDto
 01329        {
 01330            Id = itemId,
 01331            Container = container,
 01332            CurrentRuntimeTicks = runtimeTicks,
 01333            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 01334            Static = @static ?? false,
 01335            Params = @params,
 01336            Tag = tag,
 01337            PlaySessionId = playSessionId,
 01338            SegmentContainer = segmentContainer,
 01339            SegmentLength = segmentLength,
 01340            MinSegments = minSegments,
 01341            MediaSourceId = mediaSourceId,
 01342            DeviceId = deviceId,
 01343            AudioCodec = audioCodec,
 01344            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 01345            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 01346            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 01347            AudioSampleRate = audioSampleRate,
 01348            MaxAudioChannels = maxAudioChannels,
 01349            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 01350            MaxAudioBitDepth = maxAudioBitDepth,
 01351            AudioChannels = audioChannels,
 01352            Profile = profile,
 01353            Level = level,
 01354            Framerate = framerate,
 01355            MaxFramerate = maxFramerate,
 01356            CopyTimestamps = copyTimestamps ?? false,
 01357            StartTimeTicks = startTimeTicks,
 01358            Width = width,
 01359            Height = height,
 01360            VideoBitRate = videoBitRate,
 01361            SubtitleStreamIndex = subtitleStreamIndex,
 01362            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 01363            MaxRefFrames = maxRefFrames,
 01364            MaxVideoBitDepth = maxVideoBitDepth,
 01365            RequireAvc = requireAvc ?? false,
 01366            DeInterlace = deInterlace ?? false,
 01367            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 01368            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 01369            CpuCoreLimit = cpuCoreLimit,
 01370            LiveStreamId = liveStreamId,
 01371            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 01372            VideoCodec = videoCodec,
 01373            SubtitleCodec = subtitleCodec,
 01374            TranscodeReasons = transcodeReasons,
 01375            AudioStreamIndex = audioStreamIndex,
 01376            VideoStreamIndex = videoStreamIndex,
 01377            Context = context ?? EncodingContext.Streaming,
 01378            StreamOptions = streamOptions,
 01379            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 01380            AlwaysBurnInSubtitleWhenTranscoding = false
 01381        };
 1382
 01383        return await GetDynamicSegment(streamingRequest, segmentId)
 01384            .ConfigureAwait(false);
 01385    }
 1386
 1387    private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto streamingRequest, CancellationTokenS
 1388    {
 01389        using var state = await StreamingHelpers.GetStreamingState(
 01390                streamingRequest,
 01391                HttpContext,
 01392                _mediaSourceManager,
 01393                _userManager,
 01394                _libraryManager,
 01395                _serverConfigurationManager,
 01396                _mediaEncoder,
 01397                _encodingHelper,
 01398                _transcodeManager,
 01399                TranscodingJobType,
 01400                cancellationTokenSource.Token)
 01401            .ConfigureAwait(false);
 01402        var mediaSourceId = state.BaseRequest.MediaSourceId;
 01403        double fps = state.TargetFramerate ?? 0.0f;
 01404        int segmentLength = state.SegmentLength * 1000;
 1405
 1406        // If video is transcoded and framerate is fractional (i.e. 23.976), we need to slightly adjust segment length
 01407        if (!EncodingHelper.IsCopyCodec(state.OutputVideoCodec) && Math.Abs(fps - Math.Floor(fps + 0.001f)) > 0.001)
 1408        {
 01409            double nearestIntFramerate = Math.Ceiling(fps);
 01410            segmentLength = (int)Math.Ceiling(segmentLength * (nearestIntFramerate / fps));
 1411        }
 1412
 01413        var request = new CreateMainPlaylistRequest(
 01414            mediaSourceId is null ? null : Guid.Parse(mediaSourceId),
 01415            state.MediaPath,
 01416            segmentLength,
 01417            state.RunTimeTicks ?? 0,
 01418            state.Request.SegmentContainer ?? string.Empty,
 01419            "hls1/main/",
 01420            Request.QueryString.ToString(),
 01421            EncodingHelper.IsCopyCodec(state.OutputVideoCodec));
 01422        var playlist = _dynamicHlsPlaylistGenerator.CreateMainPlaylist(request);
 1423
 01424        return new FileContentResult(Encoding.UTF8.GetBytes(playlist), MimeTypes.GetMimeType("playlist.m3u8"));
 01425    }
 1426
 1427    private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streamingRequest, int segmentId)
 1428    {
 01429        if ((streamingRequest.StartTimeTicks ?? 0) > 0)
 1430        {
 01431            throw new ArgumentException("StartTimeTicks is not allowed.");
 1432        }
 1433
 1434        // CTS lifecycle is managed internally.
 01435        var cancellationTokenSource = new CancellationTokenSource();
 01436        var cancellationToken = cancellationTokenSource.Token;
 1437
 01438        var state = await StreamingHelpers.GetStreamingState(
 01439                streamingRequest,
 01440                HttpContext,
 01441                _mediaSourceManager,
 01442                _userManager,
 01443                _libraryManager,
 01444                _serverConfigurationManager,
 01445                _mediaEncoder,
 01446                _encodingHelper,
 01447                _transcodeManager,
 01448                TranscodingJobType,
 01449                cancellationToken)
 01450            .ConfigureAwait(false);
 1451
 01452        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 1453
 01454        var segmentPath = GetSegmentPath(state, playlistPath, segmentId);
 1455
 01456        var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 1457
 1458        // Keep segment selection and transcoding replacement under the same playlist lock.
 1459        // An out-of-order request must not replace a job while another request is using its output.
 01460        using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 1461        {
 1462            TranscodingJob? job;
 01463            var startTranscoding = false;
 01464            if (System.IO.File.Exists(segmentPath))
 1465            {
 01466                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01467                _logger.LogDebug("returning {0} [it exists]", segmentPath);
 01468                return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancel
 1469            }
 1470
 01471            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 01472            var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
 1473
 01474            if (segmentId == -1)
 1475            {
 01476                _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
 01477                startTranscoding = true;
 01478                segmentId = 0;
 1479            }
 01480            else if (currentTranscodingIndex is null)
 1481            {
 01482                _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
 01483                startTranscoding = true;
 1484            }
 01485            else if (segmentId < currentTranscodingIndex.Value)
 1486            {
 01487                _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segm
 01488                startTranscoding = true;
 1489            }
 01490            else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
 1491            {
 01492                _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIn
 01493                startTranscoding = true;
 1494            }
 1495
 01496            if (startTranscoding)
 1497            {
 1498                // If the playlist doesn't already exist, startup ffmpeg
 1499                try
 1500                {
 01501                    var currentJob = _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType);
 01502                    await WaitForActiveTranscodingRequests(currentJob, cancellationToken).ConfigureAwait(false);
 1503
 01504                    await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionI
 01505                        .ConfigureAwait(false);
 1506
 01507                    if (currentTranscodingIndex.HasValue)
 1508                    {
 01509                        await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
 1510                    }
 1511
 01512                    streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
 1513
 01514                    state.WaitForPath = segmentPath;
 01515                    job = await _transcodeManager.StartFfMpeg(
 01516                        state,
 01517                        playlistPath,
 01518                        GetCommandLineArguments(playlistPath, state, false, segmentId),
 01519                        Request.HttpContext.User.GetUserId(),
 01520                        TranscodingJobType,
 01521                        cancellationTokenSource).ConfigureAwait(false);
 01522                }
 01523                catch
 1524                {
 01525                    state.Dispose();
 01526                    throw;
 1527                }
 1528
 1529                // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false
 1530            }
 1531            else
 1532            {
 01533                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01534                if (job?.TranscodingThrottler is not null)
 1535                {
 01536                    await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
 1537                }
 1538            }
 1539
 01540            _logger.LogDebug("returning {0} [general case]", segmentPath);
 01541            job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01542            return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellati
 1543        }
 01544    }
 1545
 1546    internal static async Task WaitForActiveTranscodingRequests(TranscodingJob? job, CancellationToken cancellationToken
 1547    {
 81548        while (job?.ActiveRequestCount > 0)
 1549        {
 41550            await Task.Delay(100, cancellationToken).ConfigureAwait(false);
 1551        }
 41552    }
 1553
 1554    private static double[] GetSegmentLengths(StreamState state)
 01555        => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength);
 1556
 1557    internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength)
 1558    {
 51559        var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks;
 51560        var wholeSegments = runtimeTicks / segmentLengthTicks;
 51561        var remainingTicks = runtimeTicks % segmentLengthTicks;
 1562
 51563        var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
 51564        var segments = new double[segmentsLen];
 141565        for (int i = 0; i < wholeSegments; i++)
 1566        {
 21567            segments[i] = segmentlength;
 1568        }
 1569
 51570        if (remainingTicks != 0)
 1571        {
 31572            segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
 1573        }
 1574
 51575        return segments;
 1576    }
 1577
 1578    private string GetCommandLineArguments(string outputPath, StreamState state, bool isEventPlaylist, int startNumber)
 1579    {
 01580        var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01581        var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
 1582
 01583        var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
 1584
 01585        var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) 
 01586        var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
 01587        var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
 01588        var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 01589        var outputTsArg = outputPrefix + "%d" + outputExtension;
 1590
 01591        var segmentFormat = string.Empty;
 01592        var segmentContainer = outputExtension.TrimStart('.');
 01593        var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions, segmentContainer);
 01594        var hlsArguments = $"-hls_playlist_type {(isEventPlaylist ? "event" : "vod")} -hls_list_size 0";
 1595
 01596        if (string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1597        {
 01598            segmentFormat = "mpegts";
 1599        }
 01600        else if (string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase))
 1601        {
 01602            var outputFmp4HeaderArg = OperatingSystem.IsWindows() switch
 01603            {
 01604                // on Windows, the path of fmp4 header file needs to be configured
 01605                true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"",
 01606                // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
 01607                false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""
 01608            };
 1609
 01610            var useLegacySegmentOption = _mediaEncoder.EncoderVersion < _minFFmpegHlsSegmentOptions;
 1611
 01612            if (state.VideoStream is not null && state.IsOutputVideo)
 1613            {
 1614                // fMP4 needs frag_discont to write the audio packet DTS/PTS including the initial delay into MOOF::TRAF
 1615                // HLS does not use SIDX, and skipping it avoids FFmpeg rewriting open-GOP boundary packet PTS
 01616                hlsArguments += $" {(useLegacySegmentOption ? "-hls_ts_options" : "-hls_segment_options")} movflags=+fra
 1617            }
 1618
 01619            segmentFormat = "fmp4" + outputFmp4HeaderArg;
 1620        }
 1621        else
 1622        {
 01623            _logger.LogError("Invalid HLS segment container: {SegmentContainer}, default to mpegts", segmentContainer);
 01624            segmentFormat = "mpegts";
 1625        }
 1626
 01627        var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
 01628            ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
 01629            : "128";
 1630
 01631        var baseUrlParam = string.Empty;
 01632        if (isEventPlaylist)
 1633        {
 01634            baseUrlParam = string.Format(
 01635                CultureInfo.InvariantCulture,
 01636                " -hls_base_url \"hls/{0}/\"",
 01637                Path.GetFileNameWithoutExtension(outputPath));
 1638        }
 1639
 01640        return string.Format(
 01641            CultureInfo.InvariantCulture,
 01642            "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max
 01643            inputModifier,
 01644            _encodingHelper.GetInputArgument(state, _encodingOptions, segmentContainer),
 01645            threads,
 01646            mapArgs,
 01647            GetVideoArguments(state, startNumber, isEventPlaylist, segmentContainer),
 01648            GetAudioArguments(state),
 01649            maxMuxingQueueSize,
 01650            state.SegmentLength.ToString(CultureInfo.InvariantCulture),
 01651            segmentFormat,
 01652            startNumber.ToString(CultureInfo.InvariantCulture),
 01653            baseUrlParam,
 01654            outputTsArg.EscapeProcessArgument(),
 01655            hlsArguments,
 01656            outputPath.EscapeProcessArgument()).Trim();
 1657    }
 1658
 1659    /// <summary>
 1660    /// Gets the audio arguments for transcoding.
 1661    /// </summary>
 1662    /// <param name="state">The <see cref="StreamState"/>.</param>
 1663    /// <returns>The command line arguments for audio transcoding.</returns>
 1664    private string GetAudioArguments(StreamState state)
 1665    {
 01666        if (state.AudioStream is null)
 1667        {
 01668            return string.Empty;
 1669        }
 1670
 01671        var audioCodec = _encodingHelper.GetAudioEncoder(state);
 01672        var bitStreamArgs = _encodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.Medi
 1673
 1674        // opus, dts, truehd and flac (in FFmpeg 5 and older) are experimental in mp4 muxer
 01675        var strictArgs = string.Empty;
 01676        var actualOutputAudioCodec = state.ActualOutputAudioCodec;
 01677        if (string.Equals(actualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase)
 01678            || string.Equals(actualOutputAudioCodec, "dts", StringComparison.OrdinalIgnoreCase)
 01679            || string.Equals(actualOutputAudioCodec, "truehd", StringComparison.OrdinalIgnoreCase)
 01680            || (string.Equals(actualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase)
 01681                && _mediaEncoder.EncoderVersion < _minFFmpegFlacInMp4))
 1682        {
 01683            strictArgs = " -strict -2";
 1684        }
 1685
 01686        if (!state.IsOutputVideo)
 1687        {
 01688            var audioTranscodeParams = string.Empty;
 1689
 1690            // -vn to drop any video streams
 01691            audioTranscodeParams += "-vn";
 1692
 01693            if (EncodingHelper.IsCopyCodec(audioCodec))
 1694            {
 01695                return audioTranscodeParams + " -acodec copy" + bitStreamArgs + strictArgs;
 1696            }
 1697
 01698            audioTranscodeParams += " -acodec " + audioCodec + bitStreamArgs + strictArgs;
 1699
 01700            var audioBitrate = state.OutputAudioBitrate;
 01701            var audioChannels = state.OutputAudioChannels;
 1702
 01703            if (audioBitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(state.ActualOutputAudioCodec, Stri
 1704            {
 01705                var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, audioBitrate.Value, audioChannels ?? 2);
 01706                if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1707                {
 01708                    audioTranscodeParams += vbrParam;
 1709                }
 1710                else
 1711                {
 01712                    audioTranscodeParams += " -ab " + audioBitrate.Value.ToString(CultureInfo.InvariantCulture);
 1713                }
 1714            }
 1715
 01716            if (audioChannels.HasValue)
 1717            {
 01718                audioTranscodeParams += " -ac " + audioChannels.Value.ToString(CultureInfo.InvariantCulture);
 1719            }
 1720
 01721            if (state.OutputAudioSampleRate.HasValue)
 1722            {
 01723                audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCultur
 1724            }
 1725
 01726            return audioTranscodeParams;
 1727        }
 1728
 01729        if (EncodingHelper.IsCopyCodec(audioCodec))
 1730        {
 01731            var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01732            var copyArgs = "-codec:a:0 copy" + bitStreamArgs + strictArgs;
 1733
 01734            return copyArgs;
 1735        }
 1736
 01737        var args = "-codec:a:0 " + audioCodec + bitStreamArgs + strictArgs;
 1738
 01739        var channels = state.OutputAudioChannels;
 1740
 01741        var useDownMixAlgorithm = DownMixAlgorithmsHelper.AlgorithmFilterStrings.ContainsKey((_encodingOptions.DownMixSt
 1742
 01743        if (channels.HasValue
 01744            && (channels.Value != 2
 01745                || (state.AudioStream?.Channels is not null && !useDownMixAlgorithm)))
 1746        {
 01747            args += " -ac " + channels.Value;
 1748        }
 1749
 01750        var bitrate = state.OutputAudioBitrate;
 01751        if (bitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(actualOutputAudioCodec, StringComparison.Or
 1752        {
 01753            var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, bitrate.Value, channels ?? 2);
 01754            if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1755            {
 01756                args += vbrParam;
 1757            }
 1758            else
 1759            {
 01760                args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
 1761            }
 1762        }
 1763
 01764        if (state.OutputAudioSampleRate.HasValue)
 1765        {
 01766            args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
 1767        }
 01768        else if (state.AudioStream?.CodecTag is not null && state.AudioStream.CodecTag.Equals("ac-4", StringComparison.O
 1769        {
 1770            // ac-4 audio tends to have a super weird sample rate that will fail most encoders
 1771            // force resample it to 48KHz
 01772            args += " -ar 48000";
 1773        }
 1774
 01775        args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
 1776
 01777        return args;
 1778    }
 1779
 1780    /// <summary>
 1781    /// Selects the HEVC Dolby Vision sample entry tag.
 1782    /// </summary>
 1783    /// <param name="stream">The video stream.</param>
 1784    /// <returns>The MP4 sample entry tag.</returns>
 1785    internal static string GetDolbyVisionHevcCodecTag(MediaStream stream)
 1786    {
 81787        return stream.DvProfile == 8 ? "hvc1" : "dvh1";
 1788    }
 1789
 1790    /// <summary>
 1791    /// Gets the video arguments for transcoding.
 1792    /// </summary>
 1793    /// <param name="state">The <see cref="StreamState"/>.</param>
 1794    /// <param name="startNumber">The first number in the hls sequence.</param>
 1795    /// <param name="isEventPlaylist">Whether the playlist is EVENT or VOD.</param>
 1796    /// <param name="segmentContainer">The segment container.</param>
 1797    /// <returns>The command line arguments for video transcoding.</returns>
 1798    private string GetVideoArguments(StreamState state, int startNumber, bool isEventPlaylist, string segmentContainer)
 1799    {
 01800        if (state.VideoStream is null)
 1801        {
 01802            return string.Empty;
 1803        }
 1804
 01805        if (!state.IsOutputVideo)
 1806        {
 01807            return string.Empty;
 1808        }
 1809
 01810        var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 1811
 01812        var args = "-codec:v:0 " + codec;
 1813
 01814        var isActualOutputVideoCodecAv1 = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgn
 01815        var isActualOutputVideoCodecHevc = string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalI
 01816                                           || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.Ordin
 1817
 01818        if (isActualOutputVideoCodecHevc || isActualOutputVideoCodecAv1)
 1819        {
 01820            var requestedRange = state.GetRequestedRangeTypes(state.ActualOutputVideoCodec);
 1821            // Clients reporting Dolby Vision capabilities with fallbacks may only support the fallback layer.
 1822            // Only enable Dolby Vision remuxing if the client explicitly declares support for profiles without fallback
 01823            var clientSupportsDoVi = requestedRange.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgn
 01824            var videoIsDoVi = EncodingHelper.IsDovi(state.VideoStream);
 1825
 01826            if (EncodingHelper.IsCopyCodec(codec)
 01827                && (videoIsDoVi && clientSupportsDoVi)
 01828                && !_encodingHelper.IsDoviRemoved(state))
 1829            {
 01830                if (isActualOutputVideoCodecHevc)
 1831                {
 01832                    var codecTag = GetDolbyVisionHevcCodecTag(state.VideoStream);
 01833                    args += $" -tag:v:0 {codecTag} -strict -2";
 1834                }
 01835                else if (isActualOutputVideoCodecAv1)
 1836                {
 01837                    args += " -tag:v:0 dav1 -strict -2";
 1838                }
 1839            }
 01840            else if (isActualOutputVideoCodecHevc)
 1841            {
 1842                // Prefer hvc1 to hev1
 01843                args += " -tag:v:0 hvc1";
 1844            }
 1845        }
 1846
 1847        // if  (state.EnableMpegtsM2TsMode)
 1848        // {
 1849        //     args += " -mpegts_m2ts_mode 1";
 1850        // }
 1851
 1852        // See if we can save come cpu cycles by avoiding encoding.
 01853        if (EncodingHelper.IsCopyCodec(codec))
 1854        {
 1855            // If h264_mp4toannexb is ever added, do not use it for live tv.
 01856            if (state.VideoStream is not null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.O
 1857            {
 01858                string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state, MediaStreamType.Video);
 01859                if (!string.IsNullOrEmpty(bitStreamArgs))
 1860                {
 01861                    args += " " + bitStreamArgs;
 1862                }
 1863            }
 1864
 01865            args += " -start_at_zero";
 1866        }
 1867        else
 1868        {
 01869            args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, isEventPlaylist ? DefaultEventE
 1870
 1871            // Set the key frame params for video encoding to match the hls segment time.
 01872            args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, isEventPlaylist, sta
 1873
 1874            // Currently b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
 01875            if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
 01876                && _mediaEncoder.EncoderVersion < _minFFmpegX265BframeInFmp4)
 1877            {
 01878                args += " -bf 0";
 1879            }
 1880
 1881            // video processing filters.
 01882            var videoProcessParam = _encodingHelper.GetVideoProcessingFilterParam(state, _encodingOptions, codec);
 1883
 01884            var negativeMapArgs = _encodingHelper.GetNegativeMapArgsByFilters(state, videoProcessParam);
 1885
 01886            args = negativeMapArgs + args + videoProcessParam;
 1887
 1888            // -start_at_zero is necessary to use with -ss when seeking,
 1889            // otherwise the target position cannot be determined.
 01890            if (state.SubtitleStream is not null)
 1891            {
 1892                // Disable start_at_zero for external graphical subs
 01893                if (!(state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
 1894                {
 01895                    args += " -start_at_zero";
 1896                }
 1897            }
 1898        }
 1899
 1900        // TODO why was this not enabled for VOD?
 01901        if (isEventPlaylist && string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1902        {
 01903            args += " -flags -global_header";
 1904        }
 1905
 01906        if (!string.IsNullOrEmpty(state.OutputVideoSync))
 1907        {
 01908            args += EncodingHelper.GetVideoSyncOption(state.OutputVideoSync, _mediaEncoder.EncoderVersion);
 1909        }
 1910
 01911        args += _encodingHelper.GetOutputFFlags(state);
 1912
 01913        return args;
 1914    }
 1915
 1916    private string GetSegmentPath(StreamState state, string playlist, int index)
 1917    {
 01918        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not 
 01919        var filename = Path.GetFileNameWithoutExtension(playlist);
 1920
 01921        return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + EncodingHelper.GetSegmentF
 1922    }
 1923
 1924    private async Task<ActionResult> GetSegmentResult(
 1925        StreamState state,
 1926        string playlistPath,
 1927        string segmentPath,
 1928        string segmentExtension,
 1929        int segmentIndex,
 1930        TranscodingJob? transcodingJob,
 1931        CancellationToken cancellationToken)
 1932    {
 01933        var segmentExists = System.IO.File.Exists(segmentPath);
 01934        if (segmentExists)
 1935        {
 01936            if (transcodingJob is not null && transcodingJob.HasExited)
 1937            {
 1938                // Transcoding job is over, so assume all existing files are ready
 01939                _logger.LogDebug("serving up {0} as transcode is over", segmentPath);
 01940                return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
 1941            }
 1942
 01943            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 1944
 1945            // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's read
 01946            if (segmentIndex < currentTranscodingIndex)
 1947            {
 01948                _logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, curre
 01949                return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
 1950            }
 1951        }
 1952
 01953        var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1);
 01954        if (transcodingJob is not null)
 1955        {
 01956            while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited)
 1957            {
 1958                // To be considered ready, the segment file has to exist AND
 1959                // either the transcoding job should be done or next segment should also exist
 01960                if (segmentExists)
 1961                {
 01962                    if (transcodingJob.HasExited || System.IO.File.Exists(nextSegmentPath))
 1963                    {
 01964                        _logger.LogDebug("Serving up {SegmentPath} as it deemed ready", segmentPath);
 01965                        return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
 1966                    }
 1967                }
 1968                else
 1969                {
 01970                    segmentExists = System.IO.File.Exists(segmentPath);
 01971                    if (segmentExists)
 1972                    {
 1973                        continue; // avoid unnecessary waiting if segment just became available
 1974                    }
 1975                }
 1976
 01977                await Task.Delay(100, cancellationToken).ConfigureAwait(false);
 1978            }
 1979
 01980            if (!System.IO.File.Exists(segmentPath))
 1981            {
 01982                _logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath);
 1983            }
 1984            else
 1985            {
 01986                _logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath);
 1987            }
 1988
 01989            cancellationToken.ThrowIfCancellationRequested();
 1990        }
 1991        else
 1992        {
 01993            _logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath);
 1994        }
 1995
 01996        return GetSegmentResult(state, segmentPath, segmentIndex, transcodingJob);
 01997    }
 1998
 1999    private ActionResult GetSegmentResult(StreamState state, string segmentPath, int segmentIndex, TranscodingJob? trans
 2000    {
 02001        var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks;
 2002
 02003        Response.OnCompleted(() =>
 02004        {
 02005            _logger.LogDebug("Finished serving {SegmentPath}", segmentPath);
 02006            if (transcodingJob is not null)
 02007            {
 02008                transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPos
 02009                transcodingJob.ReportSegmentDownloaded(segmentIndex, segmentEndingPositionTicks);
 02010                _transcodeManager.OnTranscodeEndRequest(transcodingJob);
 02011            }
 02012
 02013            return Task.CompletedTask;
 02014        });
 2015
 02016        return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
 2017    }
 2018
 2019    private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
 2020    {
 02021        var job = _transcodeManager.GetTranscodingJob(playlist, TranscodingJobType);
 2022
 02023        if (job is null || job.HasExited)
 2024        {
 02025            return null;
 2026        }
 2027
 02028        var file = GetLastTranscodingFile(playlist, segmentExtension, _fileSystem);
 2029
 02030        if (file is null)
 2031        {
 02032            return null;
 2033        }
 2034
 02035        var playlistFilename = Path.GetFileNameWithoutExtension(playlist.AsSpan());
 2036
 02037        var indexString = Path.GetFileNameWithoutExtension(file.Name.AsSpan()).Slice(playlistFilename.Length);
 2038
 02039        return int.Parse(indexString, NumberStyles.Integer, CultureInfo.InvariantCulture);
 2040    }
 2041
 2042    private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem file
 2043    {
 02044        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", n
 2045
 02046        var filePrefix = Path.GetFileNameWithoutExtension(playlist);
 2047
 2048        try
 2049        {
 02050            return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
 02051                .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgno
 02052                .MaxBy(fileSystem.GetLastWriteTimeUtc);
 2053        }
 02054        catch (IOException)
 2055        {
 02056            return null;
 2057        }
 02058    }
 2059
 2060    private async Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
 2061    {
 02062        var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
 2063
 02064        if (file is null)
 2065        {
 02066            return;
 2067        }
 2068
 02069        await DeleteFile(file.FullName, retryCount).ConfigureAwait(false);
 02070    }
 2071
 2072    private async Task DeleteFile(string path, int retryCount)
 2073    {
 02074        if (retryCount >= 5)
 2075        {
 02076            return;
 2077        }
 2078
 02079        _logger.LogDebug("Deleting partial HLS file {Path}", path);
 2080
 2081        try
 2082        {
 02083            _fileSystem.DeleteFile(path);
 02084        }
 2085        catch (IOException ex)
 2086        {
 02087            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 2088
 02089            await Task.Delay(100).ConfigureAwait(false);
 02090            await DeleteFile(path, retryCount + 1).ConfigureAwait(false);
 2091        }
 02092        catch (Exception ex)
 2093        {
 02094            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 02095        }
 02096    }
 2097}

Methods/Properties

.ctor(MediaBrowser.Controller.Library.ILibraryManager,MediaBrowser.Controller.Library.IUserManager,MediaBrowser.Controller.Library.IMediaSourceManager,MediaBrowser.Controller.Configuration.IServerConfigurationManager,MediaBrowser.Controller.MediaEncoding.IMediaEncoder,MediaBrowser.Model.IO.IFileSystem,MediaBrowser.Controller.MediaEncoding.ITranscodeManager,Microsoft.Extensions.Logging.ILogger`1<Jellyfin.Api.Controllers.DynamicHlsController>,Jellyfin.Api.Helpers.DynamicHlsHelper,MediaBrowser.Controller.MediaEncoding.EncodingHelper,Jellyfin.MediaEncoding.Hls.Playlist.IDynamicHlsPlaylistGenerator)
GetLiveHlsStream()
GetMasterHlsVideoPlaylist()
GetMasterHlsAudioPlaylist()
GetVariantHlsVideoPlaylist()
GetVariantHlsAudioPlaylist()
GetHlsVideoSegment()
GetHlsAudioSegment()
GetVariantPlaylistInternal()
GetDynamicSegment()
WaitForActiveTranscodingRequests()
GetSegmentLengths(MediaBrowser.Controller.Streaming.StreamState)
GetSegmentLengthsInternal(System.Int64,System.Int32)
GetCommandLineArguments(System.String,MediaBrowser.Controller.Streaming.StreamState,System.Boolean,System.Int32)
GetAudioArguments(MediaBrowser.Controller.Streaming.StreamState)
GetDolbyVisionHevcCodecTag(MediaBrowser.Model.Entities.MediaStream)
GetVideoArguments(MediaBrowser.Controller.Streaming.StreamState,System.Int32,System.Boolean,System.String)
GetSegmentPath(MediaBrowser.Controller.Streaming.StreamState,System.String,System.Int32)
GetSegmentResult()
GetSegmentResult(MediaBrowser.Controller.Streaming.StreamState,System.String,System.Int32,MediaBrowser.Controller.MediaEncoding.TranscodingJob)
GetCurrentTranscodingIndex(System.String,System.String)
GetLastTranscodingFile(System.String,System.String,MediaBrowser.Model.IO.IFileSystem)
DeleteLastFile()
DeleteFile()