< 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: 10
Uncovered lines: 797
Coverable lines: 807
Total lines: 2082
Line coverage: 1.2%
Branch coverage
1%
Covered branches: 4
Total branches: 220
Branch coverage: 1.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 1/23/2026 - 12:11:06 AM Line coverage: 4.4% (10/225) Branch coverage: 2.7% (4/144) Total lines: 20711/29/2026 - 12:13:32 AM Line coverage: 4.4% (10/225) Branch coverage: 2.7% (4/144) Total lines: 20814/19/2026 - 12:14:27 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 20814/30/2026 - 12:14:58 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 2082 1/23/2026 - 12:11:06 AM Line coverage: 4.4% (10/225) Branch coverage: 2.7% (4/144) Total lines: 20711/29/2026 - 12:13:32 AM Line coverage: 4.4% (10/225) Branch coverage: 2.7% (4/144) Total lines: 20814/19/2026 - 12:14:27 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 20814/30/2026 - 12:14:58 AM Line coverage: 1.2% (10/807) Branch coverage: 1.8% (4/220) Total lines: 2082

Coverage delta

Coverage delta 4 -4

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.MediaEncoding.Encoder;
 24using MediaBrowser.Model.Configuration;
 25using MediaBrowser.Model.Dlna;
 26using MediaBrowser.Model.Entities;
 27using MediaBrowser.Model.IO;
 28using MediaBrowser.Model.Net;
 29using Microsoft.AspNetCore.Authorization;
 30using Microsoft.AspNetCore.Http;
 31using Microsoft.AspNetCore.Mvc;
 32using Microsoft.Extensions.Logging;
 33
 34namespace Jellyfin.Api.Controllers;
 35
 36/// <summary>
 37/// Dynamic hls controller.
 38/// </summary>
 39[Route("")]
 40[Authorize]
 41[ApiExplorerSettings(IgnoreApi = true)]
 42public class DynamicHlsController : BaseJellyfinApiController
 43{
 44    private const EncoderPreset DefaultVodEncoderPreset = EncoderPreset.veryfast;
 45    private const EncoderPreset DefaultEventEncoderPreset = EncoderPreset.superfast;
 46    private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
 47
 048    private readonly Version _minFFmpegFlacInMp4 = new Version(6, 0);
 049    private readonly Version _minFFmpegX265BframeInFmp4 = new Version(7, 0, 1);
 050    private readonly Version _minFFmpegHlsSegmentOptions = new Version(5, 0);
 51
 52    private readonly ILibraryManager _libraryManager;
 53    private readonly IUserManager _userManager;
 54    private readonly IMediaSourceManager _mediaSourceManager;
 55    private readonly IServerConfigurationManager _serverConfigurationManager;
 56    private readonly IMediaEncoder _mediaEncoder;
 57    private readonly IFileSystem _fileSystem;
 58    private readonly ITranscodeManager _transcodeManager;
 59    private readonly ILogger<DynamicHlsController> _logger;
 60    private readonly EncodingHelper _encodingHelper;
 61    private readonly IDynamicHlsPlaylistGenerator _dynamicHlsPlaylistGenerator;
 62    private readonly DynamicHlsHelper _dynamicHlsHelper;
 63    private readonly EncodingOptions _encodingOptions;
 64
 65    /// <summary>
 66    /// Initializes a new instance of the <see cref="DynamicHlsController"/> class.
 67    /// </summary>
 68    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 69    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 70    /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
 71    /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</p
 72    /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
 73    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 74    /// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
 75    /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsController}"/> interface.</param>
 76    /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
 77    /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
 78    /// <param name="dynamicHlsPlaylistGenerator">Instance of <see cref="IDynamicHlsPlaylistGenerator"/>.</param>
 079    public DynamicHlsController(
 080        ILibraryManager libraryManager,
 081        IUserManager userManager,
 082        IMediaSourceManager mediaSourceManager,
 083        IServerConfigurationManager serverConfigurationManager,
 084        IMediaEncoder mediaEncoder,
 085        IFileSystem fileSystem,
 086        ITranscodeManager transcodeManager,
 087        ILogger<DynamicHlsController> logger,
 088        DynamicHlsHelper dynamicHlsHelper,
 089        EncodingHelper encodingHelper,
 090        IDynamicHlsPlaylistGenerator dynamicHlsPlaylistGenerator)
 91    {
 092        _libraryManager = libraryManager;
 093        _userManager = userManager;
 094        _mediaSourceManager = mediaSourceManager;
 095        _serverConfigurationManager = serverConfigurationManager;
 096        _mediaEncoder = mediaEncoder;
 097        _fileSystem = fileSystem;
 098        _transcodeManager = transcodeManager;
 099        _logger = logger;
 0100        _dynamicHlsHelper = dynamicHlsHelper;
 0101        _encodingHelper = encodingHelper;
 0102        _dynamicHlsPlaylistGenerator = dynamicHlsPlaylistGenerator;
 103
 0104        _encodingOptions = serverConfigurationManager.GetEncodingOptions();
 0105    }
 106
 107    /// <summary>
 108    /// Gets a hls live stream.
 109    /// </summary>
 110    /// <param name="itemId">The item id.</param>
 111    /// <param name="container">The audio container.</param>
 112    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 113    /// <param name="params">The streaming parameters.</param>
 114    /// <param name="tag">The tag.</param>
 115    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 116    /// <param name="playSessionId">The play session id.</param>
 117    /// <param name="segmentContainer">The segment container.</param>
 118    /// <param name="segmentLength">The segment length.</param>
 119    /// <param name="minSegments">The minimum number of segments.</param>
 120    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 121    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 122    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 123    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 124    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 125    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 126    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 127    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 128    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 129    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 130    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 131    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 132    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 133    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 134    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 135    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 136    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 137    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 138    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 139    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 140    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 141    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 142    /// <param name="maxRefFrames">Optional.</param>
 143    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 144    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 145    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 146    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 147    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 148    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 149    /// <param name="liveStreamId">The live stream id.</param>
 150    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 151    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 152    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 153    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 154    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 155    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 156    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 157    /// <param name="streamOptions">Optional. The streaming options.</param>
 158    /// <param name="maxWidth">Optional. The max width.</param>
 159    /// <param name="maxHeight">Optional. The max height.</param>
 160    /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
 161    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 162    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 163    /// <response code="200">Hls live stream retrieved.</response>
 164    /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
 165    [HttpGet("Videos/{itemId}/live.m3u8")]
 166    [ProducesResponseType(StatusCodes.Status200OK)]
 167    [ProducesPlaylistFile]
 168    public async Task<ActionResult> GetLiveHlsStream(
 169        [FromRoute, Required] Guid itemId,
 170        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? container,
 171        [FromQuery] bool? @static,
 172        [FromQuery] string? @params,
 173        [FromQuery] string? tag,
 174        [FromQuery, ParameterObsolete] string? deviceProfileId,
 175        [FromQuery] string? playSessionId,
 176        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 177        [FromQuery] int? segmentLength,
 178        [FromQuery] int? minSegments,
 179        [FromQuery] string? mediaSourceId,
 180        [FromQuery] string? deviceId,
 181        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 182        [FromQuery] bool? enableAutoStreamCopy,
 183        [FromQuery] bool? allowVideoStreamCopy,
 184        [FromQuery] bool? allowAudioStreamCopy,
 185        [FromQuery] int? audioSampleRate,
 186        [FromQuery] int? maxAudioBitDepth,
 187        [FromQuery] int? audioBitRate,
 188        [FromQuery] int? audioChannels,
 189        [FromQuery] int? maxAudioChannels,
 190        [FromQuery] string? profile,
 191        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 192        [FromQuery] float? framerate,
 193        [FromQuery] float? maxFramerate,
 194        [FromQuery] bool? copyTimestamps,
 195        [FromQuery] long? startTimeTicks,
 196        [FromQuery] int? width,
 197        [FromQuery] int? height,
 198        [FromQuery] int? videoBitRate,
 199        [FromQuery] int? subtitleStreamIndex,
 200        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 201        [FromQuery] int? maxRefFrames,
 202        [FromQuery] int? maxVideoBitDepth,
 203        [FromQuery] bool? requireAvc,
 204        [FromQuery] bool? deInterlace,
 205        [FromQuery] bool? requireNonAnamorphic,
 206        [FromQuery] int? transcodingMaxAudioChannels,
 207        [FromQuery] int? cpuCoreLimit,
 208        [FromQuery] string? liveStreamId,
 209        [FromQuery] bool? enableMpegtsM2TsMode,
 210        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 211        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 212        [FromQuery] string? transcodeReasons,
 213        [FromQuery] int? audioStreamIndex,
 214        [FromQuery] int? videoStreamIndex,
 215        [FromQuery] EncodingContext? context,
 216        [FromQuery] Dictionary<string, string> streamOptions,
 217        [FromQuery] int? maxWidth,
 218        [FromQuery] int? maxHeight,
 219        [FromQuery] bool? enableSubtitlesInManifest,
 220        [FromQuery] bool enableAudioVbrEncoding = true,
 221        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 222    {
 0223        VideoRequestDto streamingRequest = new VideoRequestDto
 0224        {
 0225            Id = itemId,
 0226            Container = container,
 0227            Static = @static ?? false,
 0228            Params = @params,
 0229            Tag = tag,
 0230            PlaySessionId = playSessionId,
 0231            SegmentContainer = segmentContainer,
 0232            SegmentLength = segmentLength,
 0233            MinSegments = minSegments,
 0234            MediaSourceId = mediaSourceId,
 0235            DeviceId = deviceId,
 0236            AudioCodec = audioCodec,
 0237            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0238            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0239            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0240            AudioSampleRate = audioSampleRate,
 0241            MaxAudioChannels = maxAudioChannels,
 0242            AudioBitRate = audioBitRate,
 0243            MaxAudioBitDepth = maxAudioBitDepth,
 0244            AudioChannels = audioChannels,
 0245            Profile = profile,
 0246            Level = level,
 0247            Framerate = framerate,
 0248            MaxFramerate = maxFramerate,
 0249            CopyTimestamps = copyTimestamps ?? false,
 0250            StartTimeTicks = startTimeTicks,
 0251            Width = width,
 0252            Height = height,
 0253            VideoBitRate = videoBitRate,
 0254            SubtitleStreamIndex = subtitleStreamIndex,
 0255            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0256            MaxRefFrames = maxRefFrames,
 0257            MaxVideoBitDepth = maxVideoBitDepth,
 0258            RequireAvc = requireAvc ?? false,
 0259            DeInterlace = deInterlace ?? false,
 0260            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0261            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0262            CpuCoreLimit = cpuCoreLimit,
 0263            LiveStreamId = liveStreamId,
 0264            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0265            VideoCodec = videoCodec,
 0266            SubtitleCodec = subtitleCodec,
 0267            TranscodeReasons = transcodeReasons,
 0268            AudioStreamIndex = audioStreamIndex,
 0269            VideoStreamIndex = videoStreamIndex,
 0270            Context = context ?? EncodingContext.Streaming,
 0271            StreamOptions = streamOptions,
 0272            MaxHeight = maxHeight,
 0273            MaxWidth = maxWidth,
 0274            EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true,
 0275            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0276            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 0277        };
 278
 279        // CTS lifecycle is managed internally.
 0280        var cancellationTokenSource = new CancellationTokenSource();
 281        // Due to CTS.Token calling ThrowIfDisposed (https://github.com/dotnet/runtime/issues/29970) we have to "cache" 
 282        // since it gets disposed when ffmpeg exits
 0283        var cancellationToken = cancellationTokenSource.Token;
 0284        var state = await StreamingHelpers.GetStreamingState(
 0285                streamingRequest,
 0286                HttpContext,
 0287                _mediaSourceManager,
 0288                _userManager,
 0289                _libraryManager,
 0290                _serverConfigurationManager,
 0291                _mediaEncoder,
 0292                _encodingHelper,
 0293                _transcodeManager,
 0294                TranscodingJobType,
 0295                cancellationToken)
 0296            .ConfigureAwait(false);
 297
 0298        TranscodingJob? job = null;
 0299        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 300
 0301        if (!System.IO.File.Exists(playlistPath))
 302        {
 0303            using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 304            {
 0305                if (!System.IO.File.Exists(playlistPath))
 306                {
 307                    // If the playlist doesn't already exist, startup ffmpeg
 308                    try
 309                    {
 0310                        job = await _transcodeManager.StartFfMpeg(
 0311                                state,
 0312                                playlistPath,
 0313                                GetCommandLineArguments(playlistPath, state, true, 0),
 0314                                Request.HttpContext.User.GetUserId(),
 0315                                TranscodingJobType,
 0316                                cancellationTokenSource)
 0317                            .ConfigureAwait(false);
 0318                        job.IsLiveOutput = true;
 0319                    }
 0320                    catch
 321                    {
 0322                        state.Dispose();
 0323                        throw;
 324                    }
 325
 0326                    minSegments = state.MinSegments;
 0327                    if (minSegments > 0)
 328                    {
 0329                        await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationToke
 330                    }
 331                }
 0332            }
 333        }
 334
 0335        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 336
 0337        if (job is not null)
 338        {
 0339            _transcodeManager.OnTranscodeEndRequest(job);
 340        }
 341
 0342        var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);
 343
 0344        return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
 0345    }
 346
 347    /// <summary>
 348    /// Gets a video hls playlist stream.
 349    /// </summary>
 350    /// <param name="itemId">The item id.</param>
 351    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 352    /// <param name="params">The streaming parameters.</param>
 353    /// <param name="tag">The tag.</param>
 354    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 355    /// <param name="playSessionId">The play session id.</param>
 356    /// <param name="segmentContainer">The segment container.</param>
 357    /// <param name="segmentLength">The segment length.</param>
 358    /// <param name="minSegments">The minimum number of segments.</param>
 359    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 360    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 361    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 362    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 363    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 364    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 365    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 366    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 367    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 368    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 369    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 370    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 371    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 372    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 373    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 374    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 375    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 376    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 377    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 378    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 379    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 380    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 381    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 382    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 383    /// <param name="maxRefFrames">Optional.</param>
 384    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 385    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 386    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 387    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 388    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 389    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 390    /// <param name="liveStreamId">The live stream id.</param>
 391    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 392    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 393    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 394    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 395    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 396    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 397    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 398    /// <param name="streamOptions">Optional. The streaming options.</param>
 399    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 400    /// <param name="enableTrickplay">Enable trickplay image playlists being added to master playlist.</param>
 401    /// <param name="enableAudioVbrEncoding">Whether to enable Audio Encoding.</param>
 402    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 403    /// <response code="200">Video stream returned.</response>
 404    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 405    [HttpGet("Videos/{itemId}/master.m3u8")]
 406    [HttpHead("Videos/{itemId}/master.m3u8", Name = "HeadMasterHlsVideoPlaylist")]
 407    [ProducesResponseType(StatusCodes.Status200OK)]
 408    [ProducesPlaylistFile]
 409    public async Task<ActionResult> GetMasterHlsVideoPlaylist(
 410        [FromRoute, Required] Guid itemId,
 411        [FromQuery] bool? @static,
 412        [FromQuery] string? @params,
 413        [FromQuery] string? tag,
 414        [FromQuery, ParameterObsolete] string? deviceProfileId,
 415        [FromQuery] string? playSessionId,
 416        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 417        [FromQuery] int? segmentLength,
 418        [FromQuery] int? minSegments,
 419        [FromQuery, Required] string mediaSourceId,
 420        [FromQuery] string? deviceId,
 421        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 422        [FromQuery] bool? enableAutoStreamCopy,
 423        [FromQuery] bool? allowVideoStreamCopy,
 424        [FromQuery] bool? allowAudioStreamCopy,
 425        [FromQuery] int? audioSampleRate,
 426        [FromQuery] int? maxAudioBitDepth,
 427        [FromQuery] int? audioBitRate,
 428        [FromQuery] int? audioChannels,
 429        [FromQuery] int? maxAudioChannels,
 430        [FromQuery] string? profile,
 431        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 432        [FromQuery] float? framerate,
 433        [FromQuery] float? maxFramerate,
 434        [FromQuery] bool? copyTimestamps,
 435        [FromQuery] long? startTimeTicks,
 436        [FromQuery] int? width,
 437        [FromQuery] int? height,
 438        [FromQuery] int? maxWidth,
 439        [FromQuery] int? maxHeight,
 440        [FromQuery] int? videoBitRate,
 441        [FromQuery] int? subtitleStreamIndex,
 442        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 443        [FromQuery] int? maxRefFrames,
 444        [FromQuery] int? maxVideoBitDepth,
 445        [FromQuery] bool? requireAvc,
 446        [FromQuery] bool? deInterlace,
 447        [FromQuery] bool? requireNonAnamorphic,
 448        [FromQuery] int? transcodingMaxAudioChannels,
 449        [FromQuery] int? cpuCoreLimit,
 450        [FromQuery] string? liveStreamId,
 451        [FromQuery] bool? enableMpegtsM2TsMode,
 452        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 453        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 454        [FromQuery] string? transcodeReasons,
 455        [FromQuery] int? audioStreamIndex,
 456        [FromQuery] int? videoStreamIndex,
 457        [FromQuery] EncodingContext? context,
 458        [FromQuery] Dictionary<string, string> streamOptions,
 459        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 460        [FromQuery] bool enableTrickplay = true,
 461        [FromQuery] bool enableAudioVbrEncoding = true,
 462        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 463    {
 0464        var streamingRequest = new HlsVideoRequestDto
 0465        {
 0466            Id = itemId,
 0467            Static = @static ?? false,
 0468            Params = @params,
 0469            Tag = tag,
 0470            PlaySessionId = playSessionId,
 0471            SegmentContainer = segmentContainer,
 0472            SegmentLength = segmentLength,
 0473            MinSegments = minSegments,
 0474            MediaSourceId = mediaSourceId,
 0475            DeviceId = deviceId,
 0476            AudioCodec = audioCodec,
 0477            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0478            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0479            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0480            AudioSampleRate = audioSampleRate,
 0481            MaxAudioChannels = maxAudioChannels,
 0482            AudioBitRate = audioBitRate,
 0483            MaxAudioBitDepth = maxAudioBitDepth,
 0484            AudioChannels = audioChannels,
 0485            Profile = profile,
 0486            Level = level,
 0487            Framerate = framerate,
 0488            MaxFramerate = maxFramerate,
 0489            CopyTimestamps = copyTimestamps ?? false,
 0490            StartTimeTicks = startTimeTicks,
 0491            Width = width,
 0492            Height = height,
 0493            MaxWidth = maxWidth,
 0494            MaxHeight = maxHeight,
 0495            VideoBitRate = videoBitRate,
 0496            SubtitleStreamIndex = subtitleStreamIndex,
 0497            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0498            MaxRefFrames = maxRefFrames,
 0499            MaxVideoBitDepth = maxVideoBitDepth,
 0500            RequireAvc = requireAvc ?? false,
 0501            DeInterlace = deInterlace ?? false,
 0502            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0503            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0504            CpuCoreLimit = cpuCoreLimit,
 0505            LiveStreamId = liveStreamId,
 0506            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0507            VideoCodec = videoCodec,
 0508            SubtitleCodec = subtitleCodec,
 0509            TranscodeReasons = transcodeReasons,
 0510            AudioStreamIndex = audioStreamIndex,
 0511            VideoStreamIndex = videoStreamIndex,
 0512            Context = context ?? EncodingContext.Streaming,
 0513            StreamOptions = streamOptions,
 0514            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 0515            EnableTrickplay = enableTrickplay,
 0516            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0517            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 0518        };
 519
 0520        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 0521    }
 522
 523    /// <summary>
 524    /// Gets an audio hls playlist stream.
 525    /// </summary>
 526    /// <param name="itemId">The item id.</param>
 527    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 528    /// <param name="params">The streaming parameters.</param>
 529    /// <param name="tag">The tag.</param>
 530    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 531    /// <param name="playSessionId">The play session id.</param>
 532    /// <param name="segmentContainer">The segment container.</param>
 533    /// <param name="segmentLength">The segment length.</param>
 534    /// <param name="minSegments">The minimum number of segments.</param>
 535    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 536    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 537    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 538    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 539    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 540    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 541    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 542    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 543    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 544    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 545    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 546    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 547    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 548    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 549    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 550    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 551    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 552    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 553    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 554    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 555    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 556    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 557    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 558    /// <param name="maxRefFrames">Optional.</param>
 559    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 560    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 561    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 562    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 563    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 564    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 565    /// <param name="liveStreamId">The live stream id.</param>
 566    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 567    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 568    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 569    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 570    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 571    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 572    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 573    /// <param name="streamOptions">Optional. The streaming options.</param>
 574    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 575    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 576    /// <response code="200">Audio stream returned.</response>
 577    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 578    [HttpGet("Audio/{itemId}/master.m3u8")]
 579    [HttpHead("Audio/{itemId}/master.m3u8", Name = "HeadMasterHlsAudioPlaylist")]
 580    [ProducesResponseType(StatusCodes.Status200OK)]
 581    [ProducesPlaylistFile]
 582    public async Task<ActionResult> GetMasterHlsAudioPlaylist(
 583        [FromRoute, Required] Guid itemId,
 584        [FromQuery] bool? @static,
 585        [FromQuery] string? @params,
 586        [FromQuery] string? tag,
 587        [FromQuery, ParameterObsolete] string? deviceProfileId,
 588        [FromQuery] string? playSessionId,
 589        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 590        [FromQuery] int? segmentLength,
 591        [FromQuery] int? minSegments,
 592        [FromQuery, Required] string mediaSourceId,
 593        [FromQuery] string? deviceId,
 594        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 595        [FromQuery] bool? enableAutoStreamCopy,
 596        [FromQuery] bool? allowVideoStreamCopy,
 597        [FromQuery] bool? allowAudioStreamCopy,
 598        [FromQuery] int? audioSampleRate,
 599        [FromQuery] int? maxAudioBitDepth,
 600        [FromQuery] int? maxStreamingBitrate,
 601        [FromQuery] int? audioBitRate,
 602        [FromQuery] int? audioChannels,
 603        [FromQuery] int? maxAudioChannels,
 604        [FromQuery] string? profile,
 605        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 606        [FromQuery] float? framerate,
 607        [FromQuery] float? maxFramerate,
 608        [FromQuery] bool? copyTimestamps,
 609        [FromQuery] long? startTimeTicks,
 610        [FromQuery] int? width,
 611        [FromQuery] int? height,
 612        [FromQuery] int? videoBitRate,
 613        [FromQuery] int? subtitleStreamIndex,
 614        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 615        [FromQuery] int? maxRefFrames,
 616        [FromQuery] int? maxVideoBitDepth,
 617        [FromQuery] bool? requireAvc,
 618        [FromQuery] bool? deInterlace,
 619        [FromQuery] bool? requireNonAnamorphic,
 620        [FromQuery] int? transcodingMaxAudioChannels,
 621        [FromQuery] int? cpuCoreLimit,
 622        [FromQuery] string? liveStreamId,
 623        [FromQuery] bool? enableMpegtsM2TsMode,
 624        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 625        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 626        [FromQuery] string? transcodeReasons,
 627        [FromQuery] int? audioStreamIndex,
 628        [FromQuery] int? videoStreamIndex,
 629        [FromQuery] EncodingContext? context,
 630        [FromQuery] Dictionary<string, string> streamOptions,
 631        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 632        [FromQuery] bool enableAudioVbrEncoding = true)
 633    {
 0634        var streamingRequest = new HlsAudioRequestDto
 0635        {
 0636            Id = itemId,
 0637            Static = @static ?? false,
 0638            Params = @params,
 0639            Tag = tag,
 0640            PlaySessionId = playSessionId,
 0641            SegmentContainer = segmentContainer,
 0642            SegmentLength = segmentLength,
 0643            MinSegments = minSegments,
 0644            MediaSourceId = mediaSourceId,
 0645            DeviceId = deviceId,
 0646            AudioCodec = audioCodec,
 0647            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0648            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0649            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0650            AudioSampleRate = audioSampleRate,
 0651            MaxAudioChannels = maxAudioChannels,
 0652            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 0653            MaxAudioBitDepth = maxAudioBitDepth,
 0654            AudioChannels = audioChannels,
 0655            Profile = profile,
 0656            Level = level,
 0657            Framerate = framerate,
 0658            MaxFramerate = maxFramerate,
 0659            CopyTimestamps = copyTimestamps ?? false,
 0660            StartTimeTicks = startTimeTicks,
 0661            Width = width,
 0662            Height = height,
 0663            VideoBitRate = videoBitRate,
 0664            SubtitleStreamIndex = subtitleStreamIndex,
 0665            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0666            MaxRefFrames = maxRefFrames,
 0667            MaxVideoBitDepth = maxVideoBitDepth,
 0668            RequireAvc = requireAvc ?? false,
 0669            DeInterlace = deInterlace ?? false,
 0670            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0671            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0672            CpuCoreLimit = cpuCoreLimit,
 0673            LiveStreamId = liveStreamId,
 0674            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0675            VideoCodec = videoCodec,
 0676            SubtitleCodec = subtitleCodec,
 0677            TranscodeReasons = transcodeReasons,
 0678            AudioStreamIndex = audioStreamIndex,
 0679            VideoStreamIndex = videoStreamIndex,
 0680            Context = context ?? EncodingContext.Streaming,
 0681            StreamOptions = streamOptions,
 0682            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 0683            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0684            AlwaysBurnInSubtitleWhenTranscoding = false
 0685        };
 686
 0687        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 0688    }
 689
 690    /// <summary>
 691    /// Gets a video stream using HTTP live streaming.
 692    /// </summary>
 693    /// <param name="itemId">The item id.</param>
 694    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 695    /// <param name="params">The streaming parameters.</param>
 696    /// <param name="tag">The tag.</param>
 697    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 698    /// <param name="playSessionId">The play session id.</param>
 699    /// <param name="segmentContainer">The segment container.</param>
 700    /// <param name="segmentLength">The segment length.</param>
 701    /// <param name="minSegments">The minimum number of segments.</param>
 702    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 703    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 704    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 705    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 706    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 707    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 708    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 709    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 710    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 711    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 712    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 713    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 714    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 715    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 716    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 717    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 718    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 719    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 720    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 721    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 722    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 723    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 724    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 725    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 726    /// <param name="maxRefFrames">Optional.</param>
 727    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 728    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 729    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 730    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 731    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 732    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 733    /// <param name="liveStreamId">The live stream id.</param>
 734    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 735    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 736    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 737    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 738    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 739    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 740    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 741    /// <param name="streamOptions">Optional. The streaming options.</param>
 742    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 743    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 744    /// <response code="200">Video stream returned.</response>
 745    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 746    [HttpGet("Videos/{itemId}/main.m3u8")]
 747    [ProducesResponseType(StatusCodes.Status200OK)]
 748    [ProducesPlaylistFile]
 749    public async Task<ActionResult> GetVariantHlsVideoPlaylist(
 750        [FromRoute, Required] Guid itemId,
 751        [FromQuery] bool? @static,
 752        [FromQuery] string? @params,
 753        [FromQuery] string? tag,
 754        [FromQuery, ParameterObsolete] string? deviceProfileId,
 755        [FromQuery] string? playSessionId,
 756        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 757        [FromQuery] int? segmentLength,
 758        [FromQuery] int? minSegments,
 759        [FromQuery] string? mediaSourceId,
 760        [FromQuery] string? deviceId,
 761        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 762        [FromQuery] bool? enableAutoStreamCopy,
 763        [FromQuery] bool? allowVideoStreamCopy,
 764        [FromQuery] bool? allowAudioStreamCopy,
 765        [FromQuery] int? audioSampleRate,
 766        [FromQuery] int? maxAudioBitDepth,
 767        [FromQuery] int? audioBitRate,
 768        [FromQuery] int? audioChannels,
 769        [FromQuery] int? maxAudioChannels,
 770        [FromQuery] string? profile,
 771        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 772        [FromQuery] float? framerate,
 773        [FromQuery] float? maxFramerate,
 774        [FromQuery] bool? copyTimestamps,
 775        [FromQuery] long? startTimeTicks,
 776        [FromQuery] int? width,
 777        [FromQuery] int? height,
 778        [FromQuery] int? maxWidth,
 779        [FromQuery] int? maxHeight,
 780        [FromQuery] int? videoBitRate,
 781        [FromQuery] int? subtitleStreamIndex,
 782        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 783        [FromQuery] int? maxRefFrames,
 784        [FromQuery] int? maxVideoBitDepth,
 785        [FromQuery] bool? requireAvc,
 786        [FromQuery] bool? deInterlace,
 787        [FromQuery] bool? requireNonAnamorphic,
 788        [FromQuery] int? transcodingMaxAudioChannels,
 789        [FromQuery] int? cpuCoreLimit,
 790        [FromQuery] string? liveStreamId,
 791        [FromQuery] bool? enableMpegtsM2TsMode,
 792        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 793        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 794        [FromQuery] string? transcodeReasons,
 795        [FromQuery] int? audioStreamIndex,
 796        [FromQuery] int? videoStreamIndex,
 797        [FromQuery] EncodingContext? context,
 798        [FromQuery] Dictionary<string, string> streamOptions,
 799        [FromQuery] bool enableAudioVbrEncoding = true,
 800        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 801    {
 0802        using var cancellationTokenSource = new CancellationTokenSource();
 0803        var streamingRequest = new VideoRequestDto
 0804        {
 0805            Id = itemId,
 0806            Static = @static ?? false,
 0807            Params = @params,
 0808            Tag = tag,
 0809            PlaySessionId = playSessionId,
 0810            SegmentContainer = segmentContainer,
 0811            SegmentLength = segmentLength,
 0812            MinSegments = minSegments,
 0813            MediaSourceId = mediaSourceId,
 0814            DeviceId = deviceId,
 0815            AudioCodec = audioCodec,
 0816            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0817            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0818            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0819            AudioSampleRate = audioSampleRate,
 0820            MaxAudioChannels = maxAudioChannels,
 0821            AudioBitRate = audioBitRate,
 0822            MaxAudioBitDepth = maxAudioBitDepth,
 0823            AudioChannels = audioChannels,
 0824            Profile = profile,
 0825            Level = level,
 0826            Framerate = framerate,
 0827            MaxFramerate = maxFramerate,
 0828            CopyTimestamps = copyTimestamps ?? false,
 0829            StartTimeTicks = startTimeTicks,
 0830            Width = width,
 0831            Height = height,
 0832            MaxWidth = maxWidth,
 0833            MaxHeight = maxHeight,
 0834            VideoBitRate = videoBitRate,
 0835            SubtitleStreamIndex = subtitleStreamIndex,
 0836            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 0837            MaxRefFrames = maxRefFrames,
 0838            MaxVideoBitDepth = maxVideoBitDepth,
 0839            RequireAvc = requireAvc ?? false,
 0840            DeInterlace = deInterlace ?? false,
 0841            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 0842            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 0843            CpuCoreLimit = cpuCoreLimit,
 0844            LiveStreamId = liveStreamId,
 0845            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 0846            VideoCodec = videoCodec,
 0847            SubtitleCodec = subtitleCodec,
 0848            TranscodeReasons = transcodeReasons,
 0849            AudioStreamIndex = audioStreamIndex,
 0850            VideoStreamIndex = videoStreamIndex,
 0851            Context = context ?? EncodingContext.Streaming,
 0852            StreamOptions = streamOptions,
 0853            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 0854            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 0855        };
 856
 0857        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 0858            .ConfigureAwait(false);
 0859    }
 860
 861    /// <summary>
 862    /// Gets an audio stream using HTTP live streaming.
 863    /// </summary>
 864    /// <param name="itemId">The item id.</param>
 865    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 866    /// <param name="params">The streaming parameters.</param>
 867    /// <param name="tag">The tag.</param>
 868    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 869    /// <param name="playSessionId">The play session id.</param>
 870    /// <param name="segmentContainer">The segment container.</param>
 871    /// <param name="segmentLength">The segment length.</param>
 872    /// <param name="minSegments">The minimum number of segments.</param>
 873    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 874    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 875    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 876    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 877    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 878    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 879    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 880    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 881    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 882    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 883    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 884    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 885    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 886    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 887    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 888    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 889    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 890    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 891    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 892    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 893    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 894    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 895    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 896    /// <param name="maxRefFrames">Optional.</param>
 897    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 898    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 899    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 900    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 901    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 902    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 903    /// <param name="liveStreamId">The live stream id.</param>
 904    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 905    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 906    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 907    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 908    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 909    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 910    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 911    /// <param name="streamOptions">Optional. The streaming options.</param>
 912    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 913    /// <response code="200">Audio stream returned.</response>
 914    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 915    [HttpGet("Audio/{itemId}/main.m3u8")]
 916    [ProducesResponseType(StatusCodes.Status200OK)]
 917    [ProducesPlaylistFile]
 918    public async Task<ActionResult> GetVariantHlsAudioPlaylist(
 919        [FromRoute, Required] Guid itemId,
 920        [FromQuery] bool? @static,
 921        [FromQuery] string? @params,
 922        [FromQuery] string? tag,
 923        [FromQuery, ParameterObsolete] string? deviceProfileId,
 924        [FromQuery] string? playSessionId,
 925        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 926        [FromQuery] int? segmentLength,
 927        [FromQuery] int? minSegments,
 928        [FromQuery] string? mediaSourceId,
 929        [FromQuery] string? deviceId,
 930        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 931        [FromQuery] bool? enableAutoStreamCopy,
 932        [FromQuery] bool? allowVideoStreamCopy,
 933        [FromQuery] bool? allowAudioStreamCopy,
 934        [FromQuery] int? audioSampleRate,
 935        [FromQuery] int? maxAudioBitDepth,
 936        [FromQuery] int? maxStreamingBitrate,
 937        [FromQuery] int? audioBitRate,
 938        [FromQuery] int? audioChannels,
 939        [FromQuery] int? maxAudioChannels,
 940        [FromQuery] string? profile,
 941        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 942        [FromQuery] float? framerate,
 943        [FromQuery] float? maxFramerate,
 944        [FromQuery] bool? copyTimestamps,
 945        [FromQuery] long? startTimeTicks,
 946        [FromQuery] int? width,
 947        [FromQuery] int? height,
 948        [FromQuery] int? videoBitRate,
 949        [FromQuery] int? subtitleStreamIndex,
 950        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 951        [FromQuery] int? maxRefFrames,
 952        [FromQuery] int? maxVideoBitDepth,
 953        [FromQuery] bool? requireAvc,
 954        [FromQuery] bool? deInterlace,
 955        [FromQuery] bool? requireNonAnamorphic,
 956        [FromQuery] int? transcodingMaxAudioChannels,
 957        [FromQuery] int? cpuCoreLimit,
 958        [FromQuery] string? liveStreamId,
 959        [FromQuery] bool? enableMpegtsM2TsMode,
 960        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 961        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 962        [FromQuery] string? transcodeReasons,
 963        [FromQuery] int? audioStreamIndex,
 964        [FromQuery] int? videoStreamIndex,
 965        [FromQuery] EncodingContext? context,
 966        [FromQuery] Dictionary<string, string> streamOptions,
 967        [FromQuery] bool enableAudioVbrEncoding = true)
 968    {
 0969        using var cancellationTokenSource = new CancellationTokenSource();
 0970        var streamingRequest = new StreamingRequestDto
 0971        {
 0972            Id = itemId,
 0973            Static = @static ?? false,
 0974            Params = @params,
 0975            Tag = tag,
 0976            PlaySessionId = playSessionId,
 0977            SegmentContainer = segmentContainer,
 0978            SegmentLength = segmentLength,
 0979            MinSegments = minSegments,
 0980            MediaSourceId = mediaSourceId,
 0981            DeviceId = deviceId,
 0982            AudioCodec = audioCodec,
 0983            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 0984            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 0985            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 0986            AudioSampleRate = audioSampleRate,
 0987            MaxAudioChannels = maxAudioChannels,
 0988            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 0989            MaxAudioBitDepth = maxAudioBitDepth,
 0990            AudioChannels = audioChannels,
 0991            Profile = profile,
 0992            Level = level,
 0993            Framerate = framerate,
 0994            MaxFramerate = maxFramerate,
 0995            CopyTimestamps = copyTimestamps ?? false,
 0996            StartTimeTicks = startTimeTicks,
 0997            Width = width,
 0998            Height = height,
 0999            VideoBitRate = videoBitRate,
 01000            SubtitleStreamIndex = subtitleStreamIndex,
 01001            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 01002            MaxRefFrames = maxRefFrames,
 01003            MaxVideoBitDepth = maxVideoBitDepth,
 01004            RequireAvc = requireAvc ?? false,
 01005            DeInterlace = deInterlace ?? false,
 01006            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 01007            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 01008            CpuCoreLimit = cpuCoreLimit,
 01009            LiveStreamId = liveStreamId,
 01010            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 01011            VideoCodec = videoCodec,
 01012            SubtitleCodec = subtitleCodec,
 01013            TranscodeReasons = transcodeReasons,
 01014            AudioStreamIndex = audioStreamIndex,
 01015            VideoStreamIndex = videoStreamIndex,
 01016            Context = context ?? EncodingContext.Streaming,
 01017            StreamOptions = streamOptions,
 01018            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 01019            AlwaysBurnInSubtitleWhenTranscoding = false
 01020        };
 1021
 01022        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 01023            .ConfigureAwait(false);
 01024    }
 1025
 1026    /// <summary>
 1027    /// Gets a video stream using HTTP live streaming.
 1028    /// </summary>
 1029    /// <param name="itemId">The item id.</param>
 1030    /// <param name="playlistId">The playlist id.</param>
 1031    /// <param name="segmentId">The segment id.</param>
 1032    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1033    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1034    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1035    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1036    /// <param name="params">The streaming parameters.</param>
 1037    /// <param name="tag">The tag.</param>
 1038    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1039    /// <param name="playSessionId">The play session id.</param>
 1040    /// <param name="segmentContainer">The segment container.</param>
 1041    /// <param name="segmentLength">The desired segment length.</param>
 1042    /// <param name="minSegments">The minimum number of segments.</param>
 1043    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1044    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1045    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1046    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1047    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1048    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1049    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1050    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1051    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1052    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1053    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1054    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1055    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1056    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1057    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1058    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1059    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1060    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1061    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1062    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 1063    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 1064    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1065    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1066    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1067    /// <param name="maxRefFrames">Optional.</param>
 1068    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1069    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1070    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1071    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1072    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1073    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1074    /// <param name="liveStreamId">The live stream id.</param>
 1075    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1076    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1077    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1078    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1079    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1080    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1081    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1082    /// <param name="streamOptions">Optional. The streaming options.</param>
 1083    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1084    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 1085    /// <response code="200">Video stream returned.</response>
 1086    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1087    [HttpGet("Videos/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1088    [ProducesResponseType(StatusCodes.Status200OK)]
 1089    [ProducesVideoFile]
 1090    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1091    public async Task<ActionResult> GetHlsVideoSegment(
 1092        [FromRoute, Required] Guid itemId,
 1093        [FromRoute, Required] string playlistId,
 1094        [FromRoute, Required] int segmentId,
 1095        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string container,
 1096        [FromQuery, Required] long runtimeTicks,
 1097        [FromQuery, Required] long actualSegmentLengthTicks,
 1098        [FromQuery] bool? @static,
 1099        [FromQuery] string? @params,
 1100        [FromQuery] string? tag,
 1101        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1102        [FromQuery] string? playSessionId,
 1103        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 1104        [FromQuery] int? segmentLength,
 1105        [FromQuery] int? minSegments,
 1106        [FromQuery] string? mediaSourceId,
 1107        [FromQuery] string? deviceId,
 1108        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 1109        [FromQuery] bool? enableAutoStreamCopy,
 1110        [FromQuery] bool? allowVideoStreamCopy,
 1111        [FromQuery] bool? allowAudioStreamCopy,
 1112        [FromQuery] int? audioSampleRate,
 1113        [FromQuery] int? maxAudioBitDepth,
 1114        [FromQuery] int? audioBitRate,
 1115        [FromQuery] int? audioChannels,
 1116        [FromQuery] int? maxAudioChannels,
 1117        [FromQuery] string? profile,
 1118        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 1119        [FromQuery] float? framerate,
 1120        [FromQuery] float? maxFramerate,
 1121        [FromQuery] bool? copyTimestamps,
 1122        [FromQuery] long? startTimeTicks,
 1123        [FromQuery] int? width,
 1124        [FromQuery] int? height,
 1125        [FromQuery] int? maxWidth,
 1126        [FromQuery] int? maxHeight,
 1127        [FromQuery] int? videoBitRate,
 1128        [FromQuery] int? subtitleStreamIndex,
 1129        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1130        [FromQuery] int? maxRefFrames,
 1131        [FromQuery] int? maxVideoBitDepth,
 1132        [FromQuery] bool? requireAvc,
 1133        [FromQuery] bool? deInterlace,
 1134        [FromQuery] bool? requireNonAnamorphic,
 1135        [FromQuery] int? transcodingMaxAudioChannels,
 1136        [FromQuery] int? cpuCoreLimit,
 1137        [FromQuery] string? liveStreamId,
 1138        [FromQuery] bool? enableMpegtsM2TsMode,
 1139        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 1140        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 1141        [FromQuery] string? transcodeReasons,
 1142        [FromQuery] int? audioStreamIndex,
 1143        [FromQuery] int? videoStreamIndex,
 1144        [FromQuery] EncodingContext? context,
 1145        [FromQuery] Dictionary<string, string> streamOptions,
 1146        [FromQuery] bool enableAudioVbrEncoding = true,
 1147        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 1148    {
 01149        var streamingRequest = new VideoRequestDto
 01150        {
 01151            Id = itemId,
 01152            CurrentRuntimeTicks = runtimeTicks,
 01153            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 01154            Container = container,
 01155            Static = @static ?? false,
 01156            Params = @params,
 01157            Tag = tag,
 01158            PlaySessionId = playSessionId,
 01159            SegmentContainer = segmentContainer,
 01160            SegmentLength = segmentLength,
 01161            MinSegments = minSegments,
 01162            MediaSourceId = mediaSourceId,
 01163            DeviceId = deviceId,
 01164            AudioCodec = audioCodec,
 01165            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 01166            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 01167            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 01168            AudioSampleRate = audioSampleRate,
 01169            MaxAudioChannels = maxAudioChannels,
 01170            AudioBitRate = audioBitRate,
 01171            MaxAudioBitDepth = maxAudioBitDepth,
 01172            AudioChannels = audioChannels,
 01173            Profile = profile,
 01174            Level = level,
 01175            Framerate = framerate,
 01176            MaxFramerate = maxFramerate,
 01177            CopyTimestamps = copyTimestamps ?? false,
 01178            StartTimeTicks = startTimeTicks,
 01179            Width = width,
 01180            Height = height,
 01181            MaxWidth = maxWidth,
 01182            MaxHeight = maxHeight,
 01183            VideoBitRate = videoBitRate,
 01184            SubtitleStreamIndex = subtitleStreamIndex,
 01185            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 01186            MaxRefFrames = maxRefFrames,
 01187            MaxVideoBitDepth = maxVideoBitDepth,
 01188            RequireAvc = requireAvc ?? false,
 01189            DeInterlace = deInterlace ?? false,
 01190            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 01191            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 01192            CpuCoreLimit = cpuCoreLimit,
 01193            LiveStreamId = liveStreamId,
 01194            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 01195            VideoCodec = videoCodec,
 01196            SubtitleCodec = subtitleCodec,
 01197            TranscodeReasons = transcodeReasons,
 01198            AudioStreamIndex = audioStreamIndex,
 01199            VideoStreamIndex = videoStreamIndex,
 01200            Context = context ?? EncodingContext.Streaming,
 01201            StreamOptions = streamOptions,
 01202            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 01203            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 01204        };
 1205
 01206        return await GetDynamicSegment(streamingRequest, segmentId)
 01207            .ConfigureAwait(false);
 01208    }
 1209
 1210    /// <summary>
 1211    /// Gets a video stream using HTTP live streaming.
 1212    /// </summary>
 1213    /// <param name="itemId">The item id.</param>
 1214    /// <param name="playlistId">The playlist id.</param>
 1215    /// <param name="segmentId">The segment id.</param>
 1216    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1217    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1218    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1219    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1220    /// <param name="params">The streaming parameters.</param>
 1221    /// <param name="tag">The tag.</param>
 1222    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1223    /// <param name="playSessionId">The play session id.</param>
 1224    /// <param name="segmentContainer">The segment container.</param>
 1225    /// <param name="segmentLength">The segment length.</param>
 1226    /// <param name="minSegments">The minimum number of segments.</param>
 1227    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1228    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1229    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1230    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1231    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1232    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1233    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1234    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1235    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 1236    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1237    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1238    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1239    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1240    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1241    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1242    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1243    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1244    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1245    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1246    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1247    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1248    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1249    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1250    /// <param name="maxRefFrames">Optional.</param>
 1251    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1252    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1253    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1254    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1255    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1256    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1257    /// <param name="liveStreamId">The live stream id.</param>
 1258    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1259    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1260    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1261    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1262    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1263    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1264    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1265    /// <param name="streamOptions">Optional. The streaming options.</param>
 1266    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1267    /// <response code="200">Video stream returned.</response>
 1268    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1269    [HttpGet("Audio/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1270    [ProducesResponseType(StatusCodes.Status200OK)]
 1271    [ProducesAudioFile]
 1272    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1273    public async Task<ActionResult> GetHlsAudioSegment(
 1274        [FromRoute, Required] Guid itemId,
 1275        [FromRoute, Required] string playlistId,
 1276        [FromRoute, Required] int segmentId,
 1277        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string container,
 1278        [FromQuery, Required] long runtimeTicks,
 1279        [FromQuery, Required] long actualSegmentLengthTicks,
 1280        [FromQuery] bool? @static,
 1281        [FromQuery] string? @params,
 1282        [FromQuery] string? tag,
 1283        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1284        [FromQuery] string? playSessionId,
 1285        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? segmentContainer,
 1286        [FromQuery] int? segmentLength,
 1287        [FromQuery] int? minSegments,
 1288        [FromQuery] string? mediaSourceId,
 1289        [FromQuery] string? deviceId,
 1290        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? audioCodec,
 1291        [FromQuery] bool? enableAutoStreamCopy,
 1292        [FromQuery] bool? allowVideoStreamCopy,
 1293        [FromQuery] bool? allowAudioStreamCopy,
 1294        [FromQuery] int? audioSampleRate,
 1295        [FromQuery] int? maxAudioBitDepth,
 1296        [FromQuery] int? maxStreamingBitrate,
 1297        [FromQuery] int? audioBitRate,
 1298        [FromQuery] int? audioChannels,
 1299        [FromQuery] int? maxAudioChannels,
 1300        [FromQuery] string? profile,
 1301        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegexStr)] string? level,
 1302        [FromQuery] float? framerate,
 1303        [FromQuery] float? maxFramerate,
 1304        [FromQuery] bool? copyTimestamps,
 1305        [FromQuery] long? startTimeTicks,
 1306        [FromQuery] int? width,
 1307        [FromQuery] int? height,
 1308        [FromQuery] int? videoBitRate,
 1309        [FromQuery] int? subtitleStreamIndex,
 1310        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1311        [FromQuery] int? maxRefFrames,
 1312        [FromQuery] int? maxVideoBitDepth,
 1313        [FromQuery] bool? requireAvc,
 1314        [FromQuery] bool? deInterlace,
 1315        [FromQuery] bool? requireNonAnamorphic,
 1316        [FromQuery] int? transcodingMaxAudioChannels,
 1317        [FromQuery] int? cpuCoreLimit,
 1318        [FromQuery] string? liveStreamId,
 1319        [FromQuery] bool? enableMpegtsM2TsMode,
 1320        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? videoCodec,
 1321        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegexStr)] string? subtitleCodec,
 1322        [FromQuery] string? transcodeReasons,
 1323        [FromQuery] int? audioStreamIndex,
 1324        [FromQuery] int? videoStreamIndex,
 1325        [FromQuery] EncodingContext? context,
 1326        [FromQuery] Dictionary<string, string> streamOptions,
 1327        [FromQuery] bool enableAudioVbrEncoding = true)
 1328    {
 01329        var streamingRequest = new StreamingRequestDto
 01330        {
 01331            Id = itemId,
 01332            Container = container,
 01333            CurrentRuntimeTicks = runtimeTicks,
 01334            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 01335            Static = @static ?? false,
 01336            Params = @params,
 01337            Tag = tag,
 01338            PlaySessionId = playSessionId,
 01339            SegmentContainer = segmentContainer,
 01340            SegmentLength = segmentLength,
 01341            MinSegments = minSegments,
 01342            MediaSourceId = mediaSourceId,
 01343            DeviceId = deviceId,
 01344            AudioCodec = audioCodec,
 01345            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 01346            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 01347            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 01348            AudioSampleRate = audioSampleRate,
 01349            MaxAudioChannels = maxAudioChannels,
 01350            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 01351            MaxAudioBitDepth = maxAudioBitDepth,
 01352            AudioChannels = audioChannels,
 01353            Profile = profile,
 01354            Level = level,
 01355            Framerate = framerate,
 01356            MaxFramerate = maxFramerate,
 01357            CopyTimestamps = copyTimestamps ?? false,
 01358            StartTimeTicks = startTimeTicks,
 01359            Width = width,
 01360            Height = height,
 01361            VideoBitRate = videoBitRate,
 01362            SubtitleStreamIndex = subtitleStreamIndex,
 01363            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 01364            MaxRefFrames = maxRefFrames,
 01365            MaxVideoBitDepth = maxVideoBitDepth,
 01366            RequireAvc = requireAvc ?? false,
 01367            DeInterlace = deInterlace ?? false,
 01368            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 01369            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 01370            CpuCoreLimit = cpuCoreLimit,
 01371            LiveStreamId = liveStreamId,
 01372            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 01373            VideoCodec = videoCodec,
 01374            SubtitleCodec = subtitleCodec,
 01375            TranscodeReasons = transcodeReasons,
 01376            AudioStreamIndex = audioStreamIndex,
 01377            VideoStreamIndex = videoStreamIndex,
 01378            Context = context ?? EncodingContext.Streaming,
 01379            StreamOptions = streamOptions,
 01380            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 01381            AlwaysBurnInSubtitleWhenTranscoding = false
 01382        };
 1383
 01384        return await GetDynamicSegment(streamingRequest, segmentId)
 01385            .ConfigureAwait(false);
 01386    }
 1387
 1388    private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto streamingRequest, CancellationTokenS
 1389    {
 01390        using var state = await StreamingHelpers.GetStreamingState(
 01391                streamingRequest,
 01392                HttpContext,
 01393                _mediaSourceManager,
 01394                _userManager,
 01395                _libraryManager,
 01396                _serverConfigurationManager,
 01397                _mediaEncoder,
 01398                _encodingHelper,
 01399                _transcodeManager,
 01400                TranscodingJobType,
 01401                cancellationTokenSource.Token)
 01402            .ConfigureAwait(false);
 01403        var mediaSourceId = state.BaseRequest.MediaSourceId;
 01404        double fps = state.TargetFramerate ?? 0.0f;
 01405        int segmentLength = state.SegmentLength * 1000;
 1406
 1407        // If video is transcoded and framerate is fractional (i.e. 23.976), we need to slightly adjust segment length
 01408        if (!EncodingHelper.IsCopyCodec(state.OutputVideoCodec) && Math.Abs(fps - Math.Floor(fps + 0.001f)) > 0.001)
 1409        {
 01410            double nearestIntFramerate = Math.Ceiling(fps);
 01411            segmentLength = (int)Math.Ceiling(segmentLength * (nearestIntFramerate / fps));
 1412        }
 1413
 01414        var request = new CreateMainPlaylistRequest(
 01415            mediaSourceId is null ? null : Guid.Parse(mediaSourceId),
 01416            state.MediaPath,
 01417            segmentLength,
 01418            state.RunTimeTicks ?? 0,
 01419            state.Request.SegmentContainer ?? string.Empty,
 01420            "hls1/main/",
 01421            Request.QueryString.ToString(),
 01422            EncodingHelper.IsCopyCodec(state.OutputVideoCodec));
 01423        var playlist = _dynamicHlsPlaylistGenerator.CreateMainPlaylist(request);
 1424
 01425        return new FileContentResult(Encoding.UTF8.GetBytes(playlist), MimeTypes.GetMimeType("playlist.m3u8"));
 01426    }
 1427
 1428    private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streamingRequest, int segmentId)
 1429    {
 01430        if ((streamingRequest.StartTimeTicks ?? 0) > 0)
 1431        {
 01432            throw new ArgumentException("StartTimeTicks is not allowed.");
 1433        }
 1434
 1435        // CTS lifecycle is managed internally.
 01436        var cancellationTokenSource = new CancellationTokenSource();
 01437        var cancellationToken = cancellationTokenSource.Token;
 1438
 01439        var state = await StreamingHelpers.GetStreamingState(
 01440                streamingRequest,
 01441                HttpContext,
 01442                _mediaSourceManager,
 01443                _userManager,
 01444                _libraryManager,
 01445                _serverConfigurationManager,
 01446                _mediaEncoder,
 01447                _encodingHelper,
 01448                _transcodeManager,
 01449                TranscodingJobType,
 01450                cancellationToken)
 01451            .ConfigureAwait(false);
 1452
 01453        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 1454
 01455        var segmentPath = GetSegmentPath(state, playlistPath, segmentId);
 1456
 01457        var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 1458
 1459        TranscodingJob? job;
 1460
 01461        if (System.IO.File.Exists(segmentPath))
 1462        {
 01463            job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01464            _logger.LogDebug("returning {0} [it exists, try 1]", segmentPath);
 01465            return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellati
 1466        }
 1467
 01468        using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 1469        {
 01470            var startTranscoding = false;
 01471            if (System.IO.File.Exists(segmentPath))
 1472            {
 01473                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01474                _logger.LogDebug("returning {0} [it exists, try 2]", segmentPath);
 01475                return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancel
 1476            }
 1477
 01478            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 01479            var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
 1480
 01481            if (segmentId == -1)
 1482            {
 01483                _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
 01484                startTranscoding = true;
 01485                segmentId = 0;
 1486            }
 01487            else if (currentTranscodingIndex is null)
 1488            {
 01489                _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
 01490                startTranscoding = true;
 1491            }
 01492            else if (segmentId < currentTranscodingIndex.Value)
 1493            {
 01494                _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segm
 01495                startTranscoding = true;
 1496            }
 01497            else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
 1498            {
 01499                _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIn
 01500                startTranscoding = true;
 1501            }
 1502
 01503            if (startTranscoding)
 1504            {
 1505                // If the playlist doesn't already exist, startup ffmpeg
 1506                try
 1507                {
 01508                    await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionI
 01509                        .ConfigureAwait(false);
 1510
 01511                    if (currentTranscodingIndex.HasValue)
 1512                    {
 01513                        await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
 1514                    }
 1515
 01516                    streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
 1517
 01518                    state.WaitForPath = segmentPath;
 01519                    job = await _transcodeManager.StartFfMpeg(
 01520                        state,
 01521                        playlistPath,
 01522                        GetCommandLineArguments(playlistPath, state, false, segmentId),
 01523                        Request.HttpContext.User.GetUserId(),
 01524                        TranscodingJobType,
 01525                        cancellationTokenSource).ConfigureAwait(false);
 01526                }
 01527                catch
 1528                {
 01529                    state.Dispose();
 01530                    throw;
 1531                }
 1532
 1533                // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false
 1534            }
 1535            else
 1536            {
 01537                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01538                if (job?.TranscodingThrottler is not null)
 1539                {
 01540                    await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
 1541                }
 1542            }
 01543        }
 1544
 01545        _logger.LogDebug("returning {0} [general case]", segmentPath);
 01546        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 01547        return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationTo
 01548    }
 1549
 1550    private static double[] GetSegmentLengths(StreamState state)
 01551        => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength);
 1552
 1553    internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength)
 1554    {
 51555        var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks;
 51556        var wholeSegments = runtimeTicks / segmentLengthTicks;
 51557        var remainingTicks = runtimeTicks % segmentLengthTicks;
 1558
 51559        var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
 51560        var segments = new double[segmentsLen];
 141561        for (int i = 0; i < wholeSegments; i++)
 1562        {
 21563            segments[i] = segmentlength;
 1564        }
 1565
 51566        if (remainingTicks != 0)
 1567        {
 31568            segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
 1569        }
 1570
 51571        return segments;
 1572    }
 1573
 1574    private string GetCommandLineArguments(string outputPath, StreamState state, bool isEventPlaylist, int startNumber)
 1575    {
 01576        var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01577        var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
 1578
 01579        var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
 1580
 01581        var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) 
 01582        var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
 01583        var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
 01584        var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 01585        var outputTsArg = outputPrefix + "%d" + outputExtension;
 1586
 01587        var segmentFormat = string.Empty;
 01588        var segmentContainer = outputExtension.TrimStart('.');
 01589        var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions, segmentContainer);
 01590        var hlsArguments = $"-hls_playlist_type {(isEventPlaylist ? "event" : "vod")} -hls_list_size 0";
 1591
 01592        if (string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1593        {
 01594            segmentFormat = "mpegts";
 1595        }
 01596        else if (string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase))
 1597        {
 01598            var outputFmp4HeaderArg = OperatingSystem.IsWindows() switch
 01599            {
 01600                // on Windows, the path of fmp4 header file needs to be configured
 01601                true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"",
 01602                // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
 01603                false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""
 01604            };
 1605
 01606            var useLegacySegmentOption = _mediaEncoder.EncoderVersion < _minFFmpegHlsSegmentOptions;
 1607
 01608            if (state.VideoStream is not null && state.IsOutputVideo)
 1609            {
 1610                // fMP4 needs this flag to write the audio packet DTS/PTS including the initial delay into MOOF::TRAF::T
 01611                hlsArguments += $" {(useLegacySegmentOption ? "-hls_ts_options" : "-hls_segment_options")} movflags=+fra
 1612            }
 1613
 01614            segmentFormat = "fmp4" + outputFmp4HeaderArg;
 1615        }
 1616        else
 1617        {
 01618            _logger.LogError("Invalid HLS segment container: {SegmentContainer}, default to mpegts", segmentContainer);
 01619            segmentFormat = "mpegts";
 1620        }
 1621
 01622        var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
 01623            ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
 01624            : "128";
 1625
 01626        var baseUrlParam = string.Empty;
 01627        if (isEventPlaylist)
 1628        {
 01629            baseUrlParam = string.Format(
 01630                CultureInfo.InvariantCulture,
 01631                " -hls_base_url \"hls/{0}/\"",
 01632                Path.GetFileNameWithoutExtension(outputPath));
 1633        }
 1634
 01635        return string.Format(
 01636            CultureInfo.InvariantCulture,
 01637            "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max
 01638            inputModifier,
 01639            _encodingHelper.GetInputArgument(state, _encodingOptions, segmentContainer),
 01640            threads,
 01641            mapArgs,
 01642            GetVideoArguments(state, startNumber, isEventPlaylist, segmentContainer),
 01643            GetAudioArguments(state),
 01644            maxMuxingQueueSize,
 01645            state.SegmentLength.ToString(CultureInfo.InvariantCulture),
 01646            segmentFormat,
 01647            startNumber.ToString(CultureInfo.InvariantCulture),
 01648            baseUrlParam,
 01649            EncodingUtils.NormalizePath(outputTsArg),
 01650            hlsArguments,
 01651            EncodingUtils.NormalizePath(outputPath)).Trim();
 1652    }
 1653
 1654    /// <summary>
 1655    /// Gets the audio arguments for transcoding.
 1656    /// </summary>
 1657    /// <param name="state">The <see cref="StreamState"/>.</param>
 1658    /// <returns>The command line arguments for audio transcoding.</returns>
 1659    private string GetAudioArguments(StreamState state)
 1660    {
 01661        if (state.AudioStream is null)
 1662        {
 01663            return string.Empty;
 1664        }
 1665
 01666        var audioCodec = _encodingHelper.GetAudioEncoder(state);
 01667        var bitStreamArgs = _encodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.Medi
 1668
 1669        // opus, dts, truehd and flac (in FFmpeg 5 and older) are experimental in mp4 muxer
 01670        var strictArgs = string.Empty;
 01671        var actualOutputAudioCodec = state.ActualOutputAudioCodec;
 01672        if (string.Equals(actualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase)
 01673            || string.Equals(actualOutputAudioCodec, "dts", StringComparison.OrdinalIgnoreCase)
 01674            || string.Equals(actualOutputAudioCodec, "truehd", StringComparison.OrdinalIgnoreCase)
 01675            || (string.Equals(actualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase)
 01676                && _mediaEncoder.EncoderVersion < _minFFmpegFlacInMp4))
 1677        {
 01678            strictArgs = " -strict -2";
 1679        }
 1680
 01681        if (!state.IsOutputVideo)
 1682        {
 01683            var audioTranscodeParams = string.Empty;
 1684
 1685            // -vn to drop any video streams
 01686            audioTranscodeParams += "-vn";
 1687
 01688            if (EncodingHelper.IsCopyCodec(audioCodec))
 1689            {
 01690                return audioTranscodeParams + " -acodec copy" + bitStreamArgs + strictArgs;
 1691            }
 1692
 01693            audioTranscodeParams += " -acodec " + audioCodec + bitStreamArgs + strictArgs;
 1694
 01695            var audioBitrate = state.OutputAudioBitrate;
 01696            var audioChannels = state.OutputAudioChannels;
 1697
 01698            if (audioBitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(state.ActualOutputAudioCodec, Stri
 1699            {
 01700                var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, audioBitrate.Value, audioChannels ?? 2);
 01701                if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1702                {
 01703                    audioTranscodeParams += vbrParam;
 1704                }
 1705                else
 1706                {
 01707                    audioTranscodeParams += " -ab " + audioBitrate.Value.ToString(CultureInfo.InvariantCulture);
 1708                }
 1709            }
 1710
 01711            if (audioChannels.HasValue)
 1712            {
 01713                audioTranscodeParams += " -ac " + audioChannels.Value.ToString(CultureInfo.InvariantCulture);
 1714            }
 1715
 01716            if (state.OutputAudioSampleRate.HasValue)
 1717            {
 01718                audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCultur
 1719            }
 1720
 01721            return audioTranscodeParams;
 1722        }
 1723
 01724        if (EncodingHelper.IsCopyCodec(audioCodec))
 1725        {
 01726            var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01727            var copyArgs = "-codec:a:0 copy" + bitStreamArgs + strictArgs;
 1728
 01729            return copyArgs;
 1730        }
 1731
 01732        var args = "-codec:a:0 " + audioCodec + bitStreamArgs + strictArgs;
 1733
 01734        var channels = state.OutputAudioChannels;
 1735
 01736        var useDownMixAlgorithm = DownMixAlgorithmsHelper.AlgorithmFilterStrings.ContainsKey((_encodingOptions.DownMixSt
 1737
 01738        if (channels.HasValue
 01739            && (channels.Value != 2
 01740                || (state.AudioStream?.Channels is not null && !useDownMixAlgorithm)))
 1741        {
 01742            args += " -ac " + channels.Value;
 1743        }
 1744
 01745        var bitrate = state.OutputAudioBitrate;
 01746        if (bitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(actualOutputAudioCodec, StringComparison.Or
 1747        {
 01748            var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, bitrate.Value, channels ?? 2);
 01749            if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1750            {
 01751                args += vbrParam;
 1752            }
 1753            else
 1754            {
 01755                args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
 1756            }
 1757        }
 1758
 01759        if (state.OutputAudioSampleRate.HasValue)
 1760        {
 01761            args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
 1762        }
 01763        else if (state.AudioStream?.CodecTag is not null && state.AudioStream.CodecTag.Equals("ac-4", StringComparison.O
 1764        {
 1765            // ac-4 audio tends to have a super weird sample rate that will fail most encoders
 1766            // force resample it to 48KHz
 01767            args += " -ar 48000";
 1768        }
 1769
 01770        args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
 1771
 01772        return args;
 1773    }
 1774
 1775    /// <summary>
 1776    /// Gets the video arguments for transcoding.
 1777    /// </summary>
 1778    /// <param name="state">The <see cref="StreamState"/>.</param>
 1779    /// <param name="startNumber">The first number in the hls sequence.</param>
 1780    /// <param name="isEventPlaylist">Whether the playlist is EVENT or VOD.</param>
 1781    /// <param name="segmentContainer">The segment container.</param>
 1782    /// <returns>The command line arguments for video transcoding.</returns>
 1783    private string GetVideoArguments(StreamState state, int startNumber, bool isEventPlaylist, string segmentContainer)
 1784    {
 01785        if (state.VideoStream is null)
 1786        {
 01787            return string.Empty;
 1788        }
 1789
 01790        if (!state.IsOutputVideo)
 1791        {
 01792            return string.Empty;
 1793        }
 1794
 01795        var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 1796
 01797        var args = "-codec:v:0 " + codec;
 1798
 01799        var isActualOutputVideoCodecAv1 = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgn
 01800        var isActualOutputVideoCodecHevc = string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalI
 01801                                           || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.Ordin
 1802
 01803        if (isActualOutputVideoCodecHevc || isActualOutputVideoCodecAv1)
 1804        {
 01805            var requestedRange = state.GetRequestedRangeTypes(state.ActualOutputVideoCodec);
 1806            // Clients reporting Dolby Vision capabilities with fallbacks may only support the fallback layer.
 1807            // Only enable Dolby Vision remuxing if the client explicitly declares support for profiles without fallback
 01808            var clientSupportsDoVi = requestedRange.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgn
 01809            var videoIsDoVi = EncodingHelper.IsDovi(state.VideoStream);
 1810
 01811            if (EncodingHelper.IsCopyCodec(codec)
 01812                && (videoIsDoVi && clientSupportsDoVi)
 01813                && !_encodingHelper.IsDoviRemoved(state))
 1814            {
 01815                if (isActualOutputVideoCodecHevc)
 1816                {
 1817                    // Use hvc1 for 8.4. This is what Dolby uses for its official sample streams. Tagging with dvh1 woul
 01818                    var codecTag = state.VideoStream.VideoRangeType == VideoRangeType.DOVIWithHLG ? "hvc1" : "dvh1";
 01819                    args += $" -tag:v:0 {codecTag} -strict -2";
 1820                }
 01821                else if (isActualOutputVideoCodecAv1)
 1822                {
 01823                    args += " -tag:v:0 dav1 -strict -2";
 1824                }
 1825            }
 01826            else if (isActualOutputVideoCodecHevc)
 1827            {
 1828                // Prefer hvc1 to hev1
 01829                args += " -tag:v:0 hvc1";
 1830            }
 1831        }
 1832
 1833        // if  (state.EnableMpegtsM2TsMode)
 1834        // {
 1835        //     args += " -mpegts_m2ts_mode 1";
 1836        // }
 1837
 1838        // See if we can save come cpu cycles by avoiding encoding.
 01839        if (EncodingHelper.IsCopyCodec(codec))
 1840        {
 1841            // If h264_mp4toannexb is ever added, do not use it for live tv.
 01842            if (state.VideoStream is not null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.O
 1843            {
 01844                string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state, MediaStreamType.Video);
 01845                if (!string.IsNullOrEmpty(bitStreamArgs))
 1846                {
 01847                    args += " " + bitStreamArgs;
 1848                }
 1849            }
 1850
 01851            args += " -start_at_zero";
 1852        }
 1853        else
 1854        {
 01855            args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, isEventPlaylist ? DefaultEventE
 1856
 1857            // Set the key frame params for video encoding to match the hls segment time.
 01858            args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, isEventPlaylist, sta
 1859
 1860            // Currently b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
 01861            if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
 01862                && _mediaEncoder.EncoderVersion < _minFFmpegX265BframeInFmp4)
 1863            {
 01864                args += " -bf 0";
 1865            }
 1866
 1867            // video processing filters.
 01868            var videoProcessParam = _encodingHelper.GetVideoProcessingFilterParam(state, _encodingOptions, codec);
 1869
 01870            var negativeMapArgs = _encodingHelper.GetNegativeMapArgsByFilters(state, videoProcessParam);
 1871
 01872            args = negativeMapArgs + args + videoProcessParam;
 1873
 1874            // -start_at_zero is necessary to use with -ss when seeking,
 1875            // otherwise the target position cannot be determined.
 01876            if (state.SubtitleStream is not null)
 1877            {
 1878                // Disable start_at_zero for external graphical subs
 01879                if (!(state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
 1880                {
 01881                    args += " -start_at_zero";
 1882                }
 1883            }
 1884        }
 1885
 1886        // TODO why was this not enabled for VOD?
 01887        if (isEventPlaylist && string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1888        {
 01889            args += " -flags -global_header";
 1890        }
 1891
 01892        if (!string.IsNullOrEmpty(state.OutputVideoSync))
 1893        {
 01894            args += EncodingHelper.GetVideoSyncOption(state.OutputVideoSync, _mediaEncoder.EncoderVersion);
 1895        }
 1896
 01897        args += _encodingHelper.GetOutputFFlags(state);
 1898
 01899        return args;
 1900    }
 1901
 1902    private string GetSegmentPath(StreamState state, string playlist, int index)
 1903    {
 01904        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not 
 01905        var filename = Path.GetFileNameWithoutExtension(playlist);
 1906
 01907        return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + EncodingHelper.GetSegmentF
 1908    }
 1909
 1910    private async Task<ActionResult> GetSegmentResult(
 1911        StreamState state,
 1912        string playlistPath,
 1913        string segmentPath,
 1914        string segmentExtension,
 1915        int segmentIndex,
 1916        TranscodingJob? transcodingJob,
 1917        CancellationToken cancellationToken)
 1918    {
 01919        var segmentExists = System.IO.File.Exists(segmentPath);
 01920        if (segmentExists)
 1921        {
 01922            if (transcodingJob is not null && transcodingJob.HasExited)
 1923            {
 1924                // Transcoding job is over, so assume all existing files are ready
 01925                _logger.LogDebug("serving up {0} as transcode is over", segmentPath);
 01926                return GetSegmentResult(state, segmentPath, transcodingJob);
 1927            }
 1928
 01929            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 1930
 1931            // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's read
 01932            if (segmentIndex < currentTranscodingIndex)
 1933            {
 01934                _logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, curre
 01935                return GetSegmentResult(state, segmentPath, transcodingJob);
 1936            }
 1937        }
 1938
 01939        var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1);
 01940        if (transcodingJob is not null)
 1941        {
 01942            while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited)
 1943            {
 1944                // To be considered ready, the segment file has to exist AND
 1945                // either the transcoding job should be done or next segment should also exist
 01946                if (segmentExists)
 1947                {
 01948                    if (transcodingJob.HasExited || System.IO.File.Exists(nextSegmentPath))
 1949                    {
 01950                        _logger.LogDebug("Serving up {SegmentPath} as it deemed ready", segmentPath);
 01951                        return GetSegmentResult(state, segmentPath, transcodingJob);
 1952                    }
 1953                }
 1954                else
 1955                {
 01956                    segmentExists = System.IO.File.Exists(segmentPath);
 01957                    if (segmentExists)
 1958                    {
 1959                        continue; // avoid unnecessary waiting if segment just became available
 1960                    }
 1961                }
 1962
 01963                await Task.Delay(100, cancellationToken).ConfigureAwait(false);
 1964            }
 1965
 01966            if (!System.IO.File.Exists(segmentPath))
 1967            {
 01968                _logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath);
 1969            }
 1970            else
 1971            {
 01972                _logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath);
 1973            }
 1974
 01975            cancellationToken.ThrowIfCancellationRequested();
 1976        }
 1977        else
 1978        {
 01979            _logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath);
 1980        }
 1981
 01982        return GetSegmentResult(state, segmentPath, transcodingJob);
 01983    }
 1984
 1985    private ActionResult GetSegmentResult(StreamState state, string segmentPath, TranscodingJob? transcodingJob)
 1986    {
 01987        var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks;
 1988
 01989        Response.OnCompleted(() =>
 01990        {
 01991            _logger.LogDebug("Finished serving {SegmentPath}", segmentPath);
 01992            if (transcodingJob is not null)
 01993            {
 01994                transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPos
 01995                _transcodeManager.OnTranscodeEndRequest(transcodingJob);
 01996            }
 01997
 01998            return Task.CompletedTask;
 01999        });
 2000
 02001        return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
 2002    }
 2003
 2004    private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
 2005    {
 02006        var job = _transcodeManager.GetTranscodingJob(playlist, TranscodingJobType);
 2007
 02008        if (job is null || job.HasExited)
 2009        {
 02010            return null;
 2011        }
 2012
 02013        var file = GetLastTranscodingFile(playlist, segmentExtension, _fileSystem);
 2014
 02015        if (file is null)
 2016        {
 02017            return null;
 2018        }
 2019
 02020        var playlistFilename = Path.GetFileNameWithoutExtension(playlist.AsSpan());
 2021
 02022        var indexString = Path.GetFileNameWithoutExtension(file.Name.AsSpan()).Slice(playlistFilename.Length);
 2023
 02024        return int.Parse(indexString, NumberStyles.Integer, CultureInfo.InvariantCulture);
 2025    }
 2026
 2027    private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem file
 2028    {
 02029        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", n
 2030
 02031        var filePrefix = Path.GetFileNameWithoutExtension(playlist);
 2032
 2033        try
 2034        {
 02035            return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
 02036                .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgno
 02037                .MaxBy(fileSystem.GetLastWriteTimeUtc);
 2038        }
 02039        catch (IOException)
 2040        {
 02041            return null;
 2042        }
 02043    }
 2044
 2045    private async Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
 2046    {
 02047        var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
 2048
 02049        if (file is null)
 2050        {
 02051            return;
 2052        }
 2053
 02054        await DeleteFile(file.FullName, retryCount).ConfigureAwait(false);
 02055    }
 2056
 2057    private async Task DeleteFile(string path, int retryCount)
 2058    {
 02059        if (retryCount >= 5)
 2060        {
 02061            return;
 2062        }
 2063
 02064        _logger.LogDebug("Deleting partial HLS file {Path}", path);
 2065
 2066        try
 2067        {
 02068            _fileSystem.DeleteFile(path);
 02069        }
 2070        catch (IOException ex)
 2071        {
 02072            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 2073
 02074            await Task.Delay(100).ConfigureAwait(false);
 02075            await DeleteFile(path, retryCount + 1).ConfigureAwait(false);
 2076        }
 02077        catch (Exception ex)
 2078        {
 02079            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 02080        }
 02081    }
 2082}

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()
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)
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,MediaBrowser.Controller.MediaEncoding.TranscodingJob)
GetCurrentTranscodingIndex(System.String,System.String)
GetLastTranscodingFile(System.String,System.String,MediaBrowser.Model.IO.IFileSystem)
DeleteLastFile()
DeleteFile()