< Summary - Jellyfin

Information
Class: Jellyfin.Api.Controllers.DynamicHlsController
Assembly: Jellyfin.Api
File(s): /srv/git/jellyfin/Jellyfin.Api/Controllers/DynamicHlsController.cs
Line coverage
4%
Covered lines: 10
Uncovered lines: 215
Coverable lines: 225
Total lines: 2081
Line coverage: 4.4%
Branch coverage
2%
Covered branches: 4
Total branches: 144
Branch coverage: 2.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 10/25/2025 - 12:09:58 AM Line coverage: 4.3% (10/228) Branch coverage: 2.7% (4/144) Total lines: 210311/4/2025 - 12:11:59 AM Line coverage: 4.3% (10/229) Branch coverage: 2.7% (4/148) Total lines: 210612/29/2025 - 12:13:19 AM Line coverage: 4.3% (10/230) Branch coverage: 2.6% (4/150) Total lines: 21071/19/2026 - 12:13:54 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: 2081 10/25/2025 - 12:09:58 AM Line coverage: 4.3% (10/228) Branch coverage: 2.7% (4/144) Total lines: 210311/4/2025 - 12:11:59 AM Line coverage: 4.3% (10/229) Branch coverage: 2.7% (4/148) Total lines: 210612/29/2025 - 12:13:19 AM Line coverage: 4.3% (10/230) Branch coverage: 2.6% (4/150) Total lines: 21071/19/2026 - 12:13:54 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: 2081

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
GetSegmentLengths(...)100%210%
GetSegmentLengthsInternal(...)100%44100%
GetCommandLineArguments(...)0%506220%
GetAudioArguments(...)0%3660600%
GetVideoArguments(...)0%2352480%
GetSegmentPath(...)0%620%
GetSegmentResult(...)100%210%
GetCurrentTranscodingIndex(...)0%4260%
GetLastTranscodingFile(...)0%620%

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]
 41public class DynamicHlsController : BaseJellyfinApiController
 42{
 43    private const EncoderPreset DefaultVodEncoderPreset = EncoderPreset.veryfast;
 44    private const EncoderPreset DefaultEventEncoderPreset = EncoderPreset.superfast;
 45    private const TranscodingJobType TranscodingJobType = MediaBrowser.Controller.MediaEncoding.TranscodingJobType.Hls;
 46
 047    private readonly Version _minFFmpegFlacInMp4 = new Version(6, 0);
 048    private readonly Version _minFFmpegX265BframeInFmp4 = new Version(7, 0, 1);
 049    private readonly Version _minFFmpegHlsSegmentOptions = new Version(5, 0);
 50
 51    private readonly ILibraryManager _libraryManager;
 52    private readonly IUserManager _userManager;
 53    private readonly IMediaSourceManager _mediaSourceManager;
 54    private readonly IServerConfigurationManager _serverConfigurationManager;
 55    private readonly IMediaEncoder _mediaEncoder;
 56    private readonly IFileSystem _fileSystem;
 57    private readonly ITranscodeManager _transcodeManager;
 58    private readonly ILogger<DynamicHlsController> _logger;
 59    private readonly EncodingHelper _encodingHelper;
 60    private readonly IDynamicHlsPlaylistGenerator _dynamicHlsPlaylistGenerator;
 61    private readonly DynamicHlsHelper _dynamicHlsHelper;
 62    private readonly EncodingOptions _encodingOptions;
 63
 64    /// <summary>
 65    /// Initializes a new instance of the <see cref="DynamicHlsController"/> class.
 66    /// </summary>
 67    /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
 68    /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
 69    /// <param name="mediaSourceManager">Instance of the <see cref="IMediaSourceManager"/> interface.</param>
 70    /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</p
 71    /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param>
 72    /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
 73    /// <param name="transcodeManager">Instance of the <see cref="ITranscodeManager"/> interface.</param>
 74    /// <param name="logger">Instance of the <see cref="ILogger{DynamicHlsController}"/> interface.</param>
 75    /// <param name="dynamicHlsHelper">Instance of <see cref="DynamicHlsHelper"/>.</param>
 76    /// <param name="encodingHelper">Instance of <see cref="EncodingHelper"/>.</param>
 77    /// <param name="dynamicHlsPlaylistGenerator">Instance of <see cref="IDynamicHlsPlaylistGenerator"/>.</param>
 078    public DynamicHlsController(
 079        ILibraryManager libraryManager,
 080        IUserManager userManager,
 081        IMediaSourceManager mediaSourceManager,
 082        IServerConfigurationManager serverConfigurationManager,
 083        IMediaEncoder mediaEncoder,
 084        IFileSystem fileSystem,
 085        ITranscodeManager transcodeManager,
 086        ILogger<DynamicHlsController> logger,
 087        DynamicHlsHelper dynamicHlsHelper,
 088        EncodingHelper encodingHelper,
 089        IDynamicHlsPlaylistGenerator dynamicHlsPlaylistGenerator)
 90    {
 091        _libraryManager = libraryManager;
 092        _userManager = userManager;
 093        _mediaSourceManager = mediaSourceManager;
 094        _serverConfigurationManager = serverConfigurationManager;
 095        _mediaEncoder = mediaEncoder;
 096        _fileSystem = fileSystem;
 097        _transcodeManager = transcodeManager;
 098        _logger = logger;
 099        _dynamicHlsHelper = dynamicHlsHelper;
 0100        _encodingHelper = encodingHelper;
 0101        _dynamicHlsPlaylistGenerator = dynamicHlsPlaylistGenerator;
 102
 0103        _encodingOptions = serverConfigurationManager.GetEncodingOptions();
 0104    }
 105
 106    /// <summary>
 107    /// Gets a hls live stream.
 108    /// </summary>
 109    /// <param name="itemId">The item id.</param>
 110    /// <param name="container">The audio container.</param>
 111    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 112    /// <param name="params">The streaming parameters.</param>
 113    /// <param name="tag">The tag.</param>
 114    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 115    /// <param name="playSessionId">The play session id.</param>
 116    /// <param name="segmentContainer">The segment container.</param>
 117    /// <param name="segmentLength">The segment length.</param>
 118    /// <param name="minSegments">The minimum number of segments.</param>
 119    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 120    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 121    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 122    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 123    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 124    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 125    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 126    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 127    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 128    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 129    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 130    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 131    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 132    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 133    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 134    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 135    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 136    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 137    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 138    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 139    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 140    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 141    /// <param name="maxRefFrames">Optional.</param>
 142    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 143    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 144    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 145    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 146    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 147    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 148    /// <param name="liveStreamId">The live stream id.</param>
 149    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 150    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 151    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 152    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 153    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 154    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 155    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 156    /// <param name="streamOptions">Optional. The streaming options.</param>
 157    /// <param name="maxWidth">Optional. The max width.</param>
 158    /// <param name="maxHeight">Optional. The max height.</param>
 159    /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
 160    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 161    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 162    /// <response code="200">Hls live stream retrieved.</response>
 163    /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
 164    [HttpGet("Videos/{itemId}/live.m3u8")]
 165    [ProducesResponseType(StatusCodes.Status200OK)]
 166    [ProducesPlaylistFile]
 167    public async Task<ActionResult> GetLiveHlsStream(
 168        [FromRoute, Required] Guid itemId,
 169        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? container,
 170        [FromQuery] bool? @static,
 171        [FromQuery] string? @params,
 172        [FromQuery] string? tag,
 173        [FromQuery, ParameterObsolete] string? deviceProfileId,
 174        [FromQuery] string? playSessionId,
 175        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 176        [FromQuery] int? segmentLength,
 177        [FromQuery] int? minSegments,
 178        [FromQuery] string? mediaSourceId,
 179        [FromQuery] string? deviceId,
 180        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 181        [FromQuery] bool? enableAutoStreamCopy,
 182        [FromQuery] bool? allowVideoStreamCopy,
 183        [FromQuery] bool? allowAudioStreamCopy,
 184        [FromQuery] int? audioSampleRate,
 185        [FromQuery] int? maxAudioBitDepth,
 186        [FromQuery] int? audioBitRate,
 187        [FromQuery] int? audioChannels,
 188        [FromQuery] int? maxAudioChannels,
 189        [FromQuery] string? profile,
 190        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 191        [FromQuery] float? framerate,
 192        [FromQuery] float? maxFramerate,
 193        [FromQuery] bool? copyTimestamps,
 194        [FromQuery] long? startTimeTicks,
 195        [FromQuery] int? width,
 196        [FromQuery] int? height,
 197        [FromQuery] int? videoBitRate,
 198        [FromQuery] int? subtitleStreamIndex,
 199        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 200        [FromQuery] int? maxRefFrames,
 201        [FromQuery] int? maxVideoBitDepth,
 202        [FromQuery] bool? requireAvc,
 203        [FromQuery] bool? deInterlace,
 204        [FromQuery] bool? requireNonAnamorphic,
 205        [FromQuery] int? transcodingMaxAudioChannels,
 206        [FromQuery] int? cpuCoreLimit,
 207        [FromQuery] string? liveStreamId,
 208        [FromQuery] bool? enableMpegtsM2TsMode,
 209        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 210        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 211        [FromQuery] string? transcodeReasons,
 212        [FromQuery] int? audioStreamIndex,
 213        [FromQuery] int? videoStreamIndex,
 214        [FromQuery] EncodingContext? context,
 215        [FromQuery] Dictionary<string, string> streamOptions,
 216        [FromQuery] int? maxWidth,
 217        [FromQuery] int? maxHeight,
 218        [FromQuery] bool? enableSubtitlesInManifest,
 219        [FromQuery] bool enableAudioVbrEncoding = true,
 220        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 221    {
 222        VideoRequestDto streamingRequest = new VideoRequestDto
 223        {
 224            Id = itemId,
 225            Container = container,
 226            Static = @static ?? false,
 227            Params = @params,
 228            Tag = tag,
 229            PlaySessionId = playSessionId,
 230            SegmentContainer = segmentContainer,
 231            SegmentLength = segmentLength,
 232            MinSegments = minSegments,
 233            MediaSourceId = mediaSourceId,
 234            DeviceId = deviceId,
 235            AudioCodec = audioCodec,
 236            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 237            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 238            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 239            AudioSampleRate = audioSampleRate,
 240            MaxAudioChannels = maxAudioChannels,
 241            AudioBitRate = audioBitRate,
 242            MaxAudioBitDepth = maxAudioBitDepth,
 243            AudioChannels = audioChannels,
 244            Profile = profile,
 245            Level = level,
 246            Framerate = framerate,
 247            MaxFramerate = maxFramerate,
 248            CopyTimestamps = copyTimestamps ?? false,
 249            StartTimeTicks = startTimeTicks,
 250            Width = width,
 251            Height = height,
 252            VideoBitRate = videoBitRate,
 253            SubtitleStreamIndex = subtitleStreamIndex,
 254            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 255            MaxRefFrames = maxRefFrames,
 256            MaxVideoBitDepth = maxVideoBitDepth,
 257            RequireAvc = requireAvc ?? false,
 258            DeInterlace = deInterlace ?? false,
 259            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 260            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 261            CpuCoreLimit = cpuCoreLimit,
 262            LiveStreamId = liveStreamId,
 263            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 264            VideoCodec = videoCodec,
 265            SubtitleCodec = subtitleCodec,
 266            TranscodeReasons = transcodeReasons,
 267            AudioStreamIndex = audioStreamIndex,
 268            VideoStreamIndex = videoStreamIndex,
 269            Context = context ?? EncodingContext.Streaming,
 270            StreamOptions = streamOptions,
 271            MaxHeight = maxHeight,
 272            MaxWidth = maxWidth,
 273            EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true,
 274            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 275            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 276        };
 277
 278        // CTS lifecycle is managed internally.
 279        var cancellationTokenSource = new CancellationTokenSource();
 280        // Due to CTS.Token calling ThrowIfDisposed (https://github.com/dotnet/runtime/issues/29970) we have to "cache" 
 281        // since it gets disposed when ffmpeg exits
 282        var cancellationToken = cancellationTokenSource.Token;
 283        var state = await StreamingHelpers.GetStreamingState(
 284                streamingRequest,
 285                HttpContext,
 286                _mediaSourceManager,
 287                _userManager,
 288                _libraryManager,
 289                _serverConfigurationManager,
 290                _mediaEncoder,
 291                _encodingHelper,
 292                _transcodeManager,
 293                TranscodingJobType,
 294                cancellationToken)
 295            .ConfigureAwait(false);
 296
 297        TranscodingJob? job = null;
 298        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 299
 300        if (!System.IO.File.Exists(playlistPath))
 301        {
 302            using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 303            {
 304                if (!System.IO.File.Exists(playlistPath))
 305                {
 306                    // If the playlist doesn't already exist, startup ffmpeg
 307                    try
 308                    {
 309                        job = await _transcodeManager.StartFfMpeg(
 310                                state,
 311                                playlistPath,
 312                                GetCommandLineArguments(playlistPath, state, true, 0),
 313                                Request.HttpContext.User.GetUserId(),
 314                                TranscodingJobType,
 315                                cancellationTokenSource)
 316                            .ConfigureAwait(false);
 317                        job.IsLiveOutput = true;
 318                    }
 319                    catch
 320                    {
 321                        state.Dispose();
 322                        throw;
 323                    }
 324
 325                    minSegments = state.MinSegments;
 326                    if (minSegments > 0)
 327                    {
 328                        await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationToke
 329                    }
 330                }
 331            }
 332        }
 333
 334        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 335
 336        if (job is not null)
 337        {
 338            _transcodeManager.OnTranscodeEndRequest(job);
 339        }
 340
 341        var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);
 342
 343        return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
 344    }
 345
 346    /// <summary>
 347    /// Gets a video hls playlist stream.
 348    /// </summary>
 349    /// <param name="itemId">The item id.</param>
 350    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 351    /// <param name="params">The streaming parameters.</param>
 352    /// <param name="tag">The tag.</param>
 353    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 354    /// <param name="playSessionId">The play session id.</param>
 355    /// <param name="segmentContainer">The segment container.</param>
 356    /// <param name="segmentLength">The segment length.</param>
 357    /// <param name="minSegments">The minimum number of segments.</param>
 358    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 359    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 360    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 361    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 362    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 363    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 364    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 365    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 366    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 367    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 368    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 369    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 370    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 371    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 372    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 373    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 374    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 375    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 376    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 377    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 378    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 379    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 380    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 381    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 382    /// <param name="maxRefFrames">Optional.</param>
 383    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 384    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 385    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 386    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 387    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 388    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 389    /// <param name="liveStreamId">The live stream id.</param>
 390    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 391    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 392    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 393    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 394    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 395    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 396    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 397    /// <param name="streamOptions">Optional. The streaming options.</param>
 398    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 399    /// <param name="enableTrickplay">Enable trickplay image playlists being added to master playlist.</param>
 400    /// <param name="enableAudioVbrEncoding">Whether to enable Audio Encoding.</param>
 401    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 402    /// <response code="200">Video stream returned.</response>
 403    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 404    [HttpGet("Videos/{itemId}/master.m3u8")]
 405    [HttpHead("Videos/{itemId}/master.m3u8", Name = "HeadMasterHlsVideoPlaylist")]
 406    [ProducesResponseType(StatusCodes.Status200OK)]
 407    [ProducesPlaylistFile]
 408    public async Task<ActionResult> GetMasterHlsVideoPlaylist(
 409        [FromRoute, Required] Guid itemId,
 410        [FromQuery] bool? @static,
 411        [FromQuery] string? @params,
 412        [FromQuery] string? tag,
 413        [FromQuery, ParameterObsolete] string? deviceProfileId,
 414        [FromQuery] string? playSessionId,
 415        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 416        [FromQuery] int? segmentLength,
 417        [FromQuery] int? minSegments,
 418        [FromQuery, Required] string mediaSourceId,
 419        [FromQuery] string? deviceId,
 420        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 421        [FromQuery] bool? enableAutoStreamCopy,
 422        [FromQuery] bool? allowVideoStreamCopy,
 423        [FromQuery] bool? allowAudioStreamCopy,
 424        [FromQuery] int? audioSampleRate,
 425        [FromQuery] int? maxAudioBitDepth,
 426        [FromQuery] int? audioBitRate,
 427        [FromQuery] int? audioChannels,
 428        [FromQuery] int? maxAudioChannels,
 429        [FromQuery] string? profile,
 430        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 431        [FromQuery] float? framerate,
 432        [FromQuery] float? maxFramerate,
 433        [FromQuery] bool? copyTimestamps,
 434        [FromQuery] long? startTimeTicks,
 435        [FromQuery] int? width,
 436        [FromQuery] int? height,
 437        [FromQuery] int? maxWidth,
 438        [FromQuery] int? maxHeight,
 439        [FromQuery] int? videoBitRate,
 440        [FromQuery] int? subtitleStreamIndex,
 441        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 442        [FromQuery] int? maxRefFrames,
 443        [FromQuery] int? maxVideoBitDepth,
 444        [FromQuery] bool? requireAvc,
 445        [FromQuery] bool? deInterlace,
 446        [FromQuery] bool? requireNonAnamorphic,
 447        [FromQuery] int? transcodingMaxAudioChannels,
 448        [FromQuery] int? cpuCoreLimit,
 449        [FromQuery] string? liveStreamId,
 450        [FromQuery] bool? enableMpegtsM2TsMode,
 451        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 452        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 453        [FromQuery] string? transcodeReasons,
 454        [FromQuery] int? audioStreamIndex,
 455        [FromQuery] int? videoStreamIndex,
 456        [FromQuery] EncodingContext? context,
 457        [FromQuery] Dictionary<string, string> streamOptions,
 458        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 459        [FromQuery] bool enableTrickplay = true,
 460        [FromQuery] bool enableAudioVbrEncoding = true,
 461        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 462    {
 463        var streamingRequest = new HlsVideoRequestDto
 464        {
 465            Id = itemId,
 466            Static = @static ?? false,
 467            Params = @params,
 468            Tag = tag,
 469            PlaySessionId = playSessionId,
 470            SegmentContainer = segmentContainer,
 471            SegmentLength = segmentLength,
 472            MinSegments = minSegments,
 473            MediaSourceId = mediaSourceId,
 474            DeviceId = deviceId,
 475            AudioCodec = audioCodec,
 476            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 477            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 478            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 479            AudioSampleRate = audioSampleRate,
 480            MaxAudioChannels = maxAudioChannels,
 481            AudioBitRate = audioBitRate,
 482            MaxAudioBitDepth = maxAudioBitDepth,
 483            AudioChannels = audioChannels,
 484            Profile = profile,
 485            Level = level,
 486            Framerate = framerate,
 487            MaxFramerate = maxFramerate,
 488            CopyTimestamps = copyTimestamps ?? false,
 489            StartTimeTicks = startTimeTicks,
 490            Width = width,
 491            Height = height,
 492            MaxWidth = maxWidth,
 493            MaxHeight = maxHeight,
 494            VideoBitRate = videoBitRate,
 495            SubtitleStreamIndex = subtitleStreamIndex,
 496            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 497            MaxRefFrames = maxRefFrames,
 498            MaxVideoBitDepth = maxVideoBitDepth,
 499            RequireAvc = requireAvc ?? false,
 500            DeInterlace = deInterlace ?? false,
 501            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 502            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 503            CpuCoreLimit = cpuCoreLimit,
 504            LiveStreamId = liveStreamId,
 505            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 506            VideoCodec = videoCodec,
 507            SubtitleCodec = subtitleCodec,
 508            TranscodeReasons = transcodeReasons,
 509            AudioStreamIndex = audioStreamIndex,
 510            VideoStreamIndex = videoStreamIndex,
 511            Context = context ?? EncodingContext.Streaming,
 512            StreamOptions = streamOptions,
 513            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 514            EnableTrickplay = enableTrickplay,
 515            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 516            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 517        };
 518
 519        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 520    }
 521
 522    /// <summary>
 523    /// Gets an audio hls playlist stream.
 524    /// </summary>
 525    /// <param name="itemId">The item id.</param>
 526    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 527    /// <param name="params">The streaming parameters.</param>
 528    /// <param name="tag">The tag.</param>
 529    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 530    /// <param name="playSessionId">The play session id.</param>
 531    /// <param name="segmentContainer">The segment container.</param>
 532    /// <param name="segmentLength">The segment length.</param>
 533    /// <param name="minSegments">The minimum number of segments.</param>
 534    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 535    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 536    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 537    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 538    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 539    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 540    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 541    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 542    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 543    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 544    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 545    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 546    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 547    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 548    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 549    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 550    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 551    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 552    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 553    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 554    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 555    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 556    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 557    /// <param name="maxRefFrames">Optional.</param>
 558    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 559    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 560    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 561    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 562    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 563    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 564    /// <param name="liveStreamId">The live stream id.</param>
 565    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 566    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 567    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 568    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 569    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 570    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 571    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 572    /// <param name="streamOptions">Optional. The streaming options.</param>
 573    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 574    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 575    /// <response code="200">Audio stream returned.</response>
 576    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 577    [HttpGet("Audio/{itemId}/master.m3u8")]
 578    [HttpHead("Audio/{itemId}/master.m3u8", Name = "HeadMasterHlsAudioPlaylist")]
 579    [ProducesResponseType(StatusCodes.Status200OK)]
 580    [ProducesPlaylistFile]
 581    public async Task<ActionResult> GetMasterHlsAudioPlaylist(
 582        [FromRoute, Required] Guid itemId,
 583        [FromQuery] bool? @static,
 584        [FromQuery] string? @params,
 585        [FromQuery] string? tag,
 586        [FromQuery, ParameterObsolete] string? deviceProfileId,
 587        [FromQuery] string? playSessionId,
 588        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 589        [FromQuery] int? segmentLength,
 590        [FromQuery] int? minSegments,
 591        [FromQuery, Required] string mediaSourceId,
 592        [FromQuery] string? deviceId,
 593        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 594        [FromQuery] bool? enableAutoStreamCopy,
 595        [FromQuery] bool? allowVideoStreamCopy,
 596        [FromQuery] bool? allowAudioStreamCopy,
 597        [FromQuery] int? audioSampleRate,
 598        [FromQuery] int? maxAudioBitDepth,
 599        [FromQuery] int? maxStreamingBitrate,
 600        [FromQuery] int? audioBitRate,
 601        [FromQuery] int? audioChannels,
 602        [FromQuery] int? maxAudioChannels,
 603        [FromQuery] string? profile,
 604        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 605        [FromQuery] float? framerate,
 606        [FromQuery] float? maxFramerate,
 607        [FromQuery] bool? copyTimestamps,
 608        [FromQuery] long? startTimeTicks,
 609        [FromQuery] int? width,
 610        [FromQuery] int? height,
 611        [FromQuery] int? videoBitRate,
 612        [FromQuery] int? subtitleStreamIndex,
 613        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 614        [FromQuery] int? maxRefFrames,
 615        [FromQuery] int? maxVideoBitDepth,
 616        [FromQuery] bool? requireAvc,
 617        [FromQuery] bool? deInterlace,
 618        [FromQuery] bool? requireNonAnamorphic,
 619        [FromQuery] int? transcodingMaxAudioChannels,
 620        [FromQuery] int? cpuCoreLimit,
 621        [FromQuery] string? liveStreamId,
 622        [FromQuery] bool? enableMpegtsM2TsMode,
 623        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 624        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 625        [FromQuery] string? transcodeReasons,
 626        [FromQuery] int? audioStreamIndex,
 627        [FromQuery] int? videoStreamIndex,
 628        [FromQuery] EncodingContext? context,
 629        [FromQuery] Dictionary<string, string> streamOptions,
 630        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 631        [FromQuery] bool enableAudioVbrEncoding = true)
 632    {
 633        var streamingRequest = new HlsAudioRequestDto
 634        {
 635            Id = itemId,
 636            Static = @static ?? false,
 637            Params = @params,
 638            Tag = tag,
 639            PlaySessionId = playSessionId,
 640            SegmentContainer = segmentContainer,
 641            SegmentLength = segmentLength,
 642            MinSegments = minSegments,
 643            MediaSourceId = mediaSourceId,
 644            DeviceId = deviceId,
 645            AudioCodec = audioCodec,
 646            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 647            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 648            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 649            AudioSampleRate = audioSampleRate,
 650            MaxAudioChannels = maxAudioChannels,
 651            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 652            MaxAudioBitDepth = maxAudioBitDepth,
 653            AudioChannels = audioChannels,
 654            Profile = profile,
 655            Level = level,
 656            Framerate = framerate,
 657            MaxFramerate = maxFramerate,
 658            CopyTimestamps = copyTimestamps ?? false,
 659            StartTimeTicks = startTimeTicks,
 660            Width = width,
 661            Height = height,
 662            VideoBitRate = videoBitRate,
 663            SubtitleStreamIndex = subtitleStreamIndex,
 664            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 665            MaxRefFrames = maxRefFrames,
 666            MaxVideoBitDepth = maxVideoBitDepth,
 667            RequireAvc = requireAvc ?? false,
 668            DeInterlace = deInterlace ?? false,
 669            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 670            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 671            CpuCoreLimit = cpuCoreLimit,
 672            LiveStreamId = liveStreamId,
 673            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 674            VideoCodec = videoCodec,
 675            SubtitleCodec = subtitleCodec,
 676            TranscodeReasons = transcodeReasons,
 677            AudioStreamIndex = audioStreamIndex,
 678            VideoStreamIndex = videoStreamIndex,
 679            Context = context ?? EncodingContext.Streaming,
 680            StreamOptions = streamOptions,
 681            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 682            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 683            AlwaysBurnInSubtitleWhenTranscoding = false
 684        };
 685
 686        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 687    }
 688
 689    /// <summary>
 690    /// Gets a video stream using HTTP live streaming.
 691    /// </summary>
 692    /// <param name="itemId">The item id.</param>
 693    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 694    /// <param name="params">The streaming parameters.</param>
 695    /// <param name="tag">The tag.</param>
 696    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 697    /// <param name="playSessionId">The play session id.</param>
 698    /// <param name="segmentContainer">The segment container.</param>
 699    /// <param name="segmentLength">The segment length.</param>
 700    /// <param name="minSegments">The minimum number of segments.</param>
 701    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 702    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 703    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 704    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 705    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 706    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 707    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 708    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 709    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 710    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 711    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 712    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 713    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 714    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 715    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 716    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 717    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 718    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 719    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 720    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 721    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 722    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 723    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 724    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 725    /// <param name="maxRefFrames">Optional.</param>
 726    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 727    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 728    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 729    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 730    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 731    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 732    /// <param name="liveStreamId">The live stream id.</param>
 733    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 734    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 735    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 736    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 737    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 738    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 739    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 740    /// <param name="streamOptions">Optional. The streaming options.</param>
 741    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 742    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 743    /// <response code="200">Video stream returned.</response>
 744    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 745    [HttpGet("Videos/{itemId}/main.m3u8")]
 746    [ProducesResponseType(StatusCodes.Status200OK)]
 747    [ProducesPlaylistFile]
 748    public async Task<ActionResult> GetVariantHlsVideoPlaylist(
 749        [FromRoute, Required] Guid itemId,
 750        [FromQuery] bool? @static,
 751        [FromQuery] string? @params,
 752        [FromQuery] string? tag,
 753        [FromQuery, ParameterObsolete] string? deviceProfileId,
 754        [FromQuery] string? playSessionId,
 755        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 756        [FromQuery] int? segmentLength,
 757        [FromQuery] int? minSegments,
 758        [FromQuery] string? mediaSourceId,
 759        [FromQuery] string? deviceId,
 760        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 761        [FromQuery] bool? enableAutoStreamCopy,
 762        [FromQuery] bool? allowVideoStreamCopy,
 763        [FromQuery] bool? allowAudioStreamCopy,
 764        [FromQuery] int? audioSampleRate,
 765        [FromQuery] int? maxAudioBitDepth,
 766        [FromQuery] int? audioBitRate,
 767        [FromQuery] int? audioChannels,
 768        [FromQuery] int? maxAudioChannels,
 769        [FromQuery] string? profile,
 770        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 771        [FromQuery] float? framerate,
 772        [FromQuery] float? maxFramerate,
 773        [FromQuery] bool? copyTimestamps,
 774        [FromQuery] long? startTimeTicks,
 775        [FromQuery] int? width,
 776        [FromQuery] int? height,
 777        [FromQuery] int? maxWidth,
 778        [FromQuery] int? maxHeight,
 779        [FromQuery] int? videoBitRate,
 780        [FromQuery] int? subtitleStreamIndex,
 781        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 782        [FromQuery] int? maxRefFrames,
 783        [FromQuery] int? maxVideoBitDepth,
 784        [FromQuery] bool? requireAvc,
 785        [FromQuery] bool? deInterlace,
 786        [FromQuery] bool? requireNonAnamorphic,
 787        [FromQuery] int? transcodingMaxAudioChannels,
 788        [FromQuery] int? cpuCoreLimit,
 789        [FromQuery] string? liveStreamId,
 790        [FromQuery] bool? enableMpegtsM2TsMode,
 791        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 792        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 793        [FromQuery] string? transcodeReasons,
 794        [FromQuery] int? audioStreamIndex,
 795        [FromQuery] int? videoStreamIndex,
 796        [FromQuery] EncodingContext? context,
 797        [FromQuery] Dictionary<string, string> streamOptions,
 798        [FromQuery] bool enableAudioVbrEncoding = true,
 799        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 800    {
 801        using var cancellationTokenSource = new CancellationTokenSource();
 802        var streamingRequest = new VideoRequestDto
 803        {
 804            Id = itemId,
 805            Static = @static ?? false,
 806            Params = @params,
 807            Tag = tag,
 808            PlaySessionId = playSessionId,
 809            SegmentContainer = segmentContainer,
 810            SegmentLength = segmentLength,
 811            MinSegments = minSegments,
 812            MediaSourceId = mediaSourceId,
 813            DeviceId = deviceId,
 814            AudioCodec = audioCodec,
 815            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 816            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 817            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 818            AudioSampleRate = audioSampleRate,
 819            MaxAudioChannels = maxAudioChannels,
 820            AudioBitRate = audioBitRate,
 821            MaxAudioBitDepth = maxAudioBitDepth,
 822            AudioChannels = audioChannels,
 823            Profile = profile,
 824            Level = level,
 825            Framerate = framerate,
 826            MaxFramerate = maxFramerate,
 827            CopyTimestamps = copyTimestamps ?? false,
 828            StartTimeTicks = startTimeTicks,
 829            Width = width,
 830            Height = height,
 831            MaxWidth = maxWidth,
 832            MaxHeight = maxHeight,
 833            VideoBitRate = videoBitRate,
 834            SubtitleStreamIndex = subtitleStreamIndex,
 835            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 836            MaxRefFrames = maxRefFrames,
 837            MaxVideoBitDepth = maxVideoBitDepth,
 838            RequireAvc = requireAvc ?? false,
 839            DeInterlace = deInterlace ?? false,
 840            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 841            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 842            CpuCoreLimit = cpuCoreLimit,
 843            LiveStreamId = liveStreamId,
 844            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 845            VideoCodec = videoCodec,
 846            SubtitleCodec = subtitleCodec,
 847            TranscodeReasons = transcodeReasons,
 848            AudioStreamIndex = audioStreamIndex,
 849            VideoStreamIndex = videoStreamIndex,
 850            Context = context ?? EncodingContext.Streaming,
 851            StreamOptions = streamOptions,
 852            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 853            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 854        };
 855
 856        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 857            .ConfigureAwait(false);
 858    }
 859
 860    /// <summary>
 861    /// Gets an audio stream using HTTP live streaming.
 862    /// </summary>
 863    /// <param name="itemId">The item id.</param>
 864    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 865    /// <param name="params">The streaming parameters.</param>
 866    /// <param name="tag">The tag.</param>
 867    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 868    /// <param name="playSessionId">The play session id.</param>
 869    /// <param name="segmentContainer">The segment container.</param>
 870    /// <param name="segmentLength">The segment length.</param>
 871    /// <param name="minSegments">The minimum number of segments.</param>
 872    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 873    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 874    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 875    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 876    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 877    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 878    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 879    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 880    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 881    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 882    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 883    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 884    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 885    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 886    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 887    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 888    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 889    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 890    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 891    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 892    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 893    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 894    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 895    /// <param name="maxRefFrames">Optional.</param>
 896    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 897    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 898    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 899    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 900    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 901    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 902    /// <param name="liveStreamId">The live stream id.</param>
 903    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 904    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 905    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 906    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 907    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 908    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 909    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 910    /// <param name="streamOptions">Optional. The streaming options.</param>
 911    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 912    /// <response code="200">Audio stream returned.</response>
 913    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 914    [HttpGet("Audio/{itemId}/main.m3u8")]
 915    [ProducesResponseType(StatusCodes.Status200OK)]
 916    [ProducesPlaylistFile]
 917    public async Task<ActionResult> GetVariantHlsAudioPlaylist(
 918        [FromRoute, Required] Guid itemId,
 919        [FromQuery] bool? @static,
 920        [FromQuery] string? @params,
 921        [FromQuery] string? tag,
 922        [FromQuery, ParameterObsolete] string? deviceProfileId,
 923        [FromQuery] string? playSessionId,
 924        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 925        [FromQuery] int? segmentLength,
 926        [FromQuery] int? minSegments,
 927        [FromQuery] string? mediaSourceId,
 928        [FromQuery] string? deviceId,
 929        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 930        [FromQuery] bool? enableAutoStreamCopy,
 931        [FromQuery] bool? allowVideoStreamCopy,
 932        [FromQuery] bool? allowAudioStreamCopy,
 933        [FromQuery] int? audioSampleRate,
 934        [FromQuery] int? maxAudioBitDepth,
 935        [FromQuery] int? maxStreamingBitrate,
 936        [FromQuery] int? audioBitRate,
 937        [FromQuery] int? audioChannels,
 938        [FromQuery] int? maxAudioChannels,
 939        [FromQuery] string? profile,
 940        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 941        [FromQuery] float? framerate,
 942        [FromQuery] float? maxFramerate,
 943        [FromQuery] bool? copyTimestamps,
 944        [FromQuery] long? startTimeTicks,
 945        [FromQuery] int? width,
 946        [FromQuery] int? height,
 947        [FromQuery] int? videoBitRate,
 948        [FromQuery] int? subtitleStreamIndex,
 949        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 950        [FromQuery] int? maxRefFrames,
 951        [FromQuery] int? maxVideoBitDepth,
 952        [FromQuery] bool? requireAvc,
 953        [FromQuery] bool? deInterlace,
 954        [FromQuery] bool? requireNonAnamorphic,
 955        [FromQuery] int? transcodingMaxAudioChannels,
 956        [FromQuery] int? cpuCoreLimit,
 957        [FromQuery] string? liveStreamId,
 958        [FromQuery] bool? enableMpegtsM2TsMode,
 959        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 960        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 961        [FromQuery] string? transcodeReasons,
 962        [FromQuery] int? audioStreamIndex,
 963        [FromQuery] int? videoStreamIndex,
 964        [FromQuery] EncodingContext? context,
 965        [FromQuery] Dictionary<string, string> streamOptions,
 966        [FromQuery] bool enableAudioVbrEncoding = true)
 967    {
 968        using var cancellationTokenSource = new CancellationTokenSource();
 969        var streamingRequest = new StreamingRequestDto
 970        {
 971            Id = itemId,
 972            Static = @static ?? false,
 973            Params = @params,
 974            Tag = tag,
 975            PlaySessionId = playSessionId,
 976            SegmentContainer = segmentContainer,
 977            SegmentLength = segmentLength,
 978            MinSegments = minSegments,
 979            MediaSourceId = mediaSourceId,
 980            DeviceId = deviceId,
 981            AudioCodec = audioCodec,
 982            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 983            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 984            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 985            AudioSampleRate = audioSampleRate,
 986            MaxAudioChannels = maxAudioChannels,
 987            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 988            MaxAudioBitDepth = maxAudioBitDepth,
 989            AudioChannels = audioChannels,
 990            Profile = profile,
 991            Level = level,
 992            Framerate = framerate,
 993            MaxFramerate = maxFramerate,
 994            CopyTimestamps = copyTimestamps ?? false,
 995            StartTimeTicks = startTimeTicks,
 996            Width = width,
 997            Height = height,
 998            VideoBitRate = videoBitRate,
 999            SubtitleStreamIndex = subtitleStreamIndex,
 1000            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 1001            MaxRefFrames = maxRefFrames,
 1002            MaxVideoBitDepth = maxVideoBitDepth,
 1003            RequireAvc = requireAvc ?? false,
 1004            DeInterlace = deInterlace ?? false,
 1005            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 1006            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 1007            CpuCoreLimit = cpuCoreLimit,
 1008            LiveStreamId = liveStreamId,
 1009            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 1010            VideoCodec = videoCodec,
 1011            SubtitleCodec = subtitleCodec,
 1012            TranscodeReasons = transcodeReasons,
 1013            AudioStreamIndex = audioStreamIndex,
 1014            VideoStreamIndex = videoStreamIndex,
 1015            Context = context ?? EncodingContext.Streaming,
 1016            StreamOptions = streamOptions,
 1017            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 1018            AlwaysBurnInSubtitleWhenTranscoding = false
 1019        };
 1020
 1021        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 1022            .ConfigureAwait(false);
 1023    }
 1024
 1025    /// <summary>
 1026    /// Gets a video stream using HTTP live streaming.
 1027    /// </summary>
 1028    /// <param name="itemId">The item id.</param>
 1029    /// <param name="playlistId">The playlist id.</param>
 1030    /// <param name="segmentId">The segment id.</param>
 1031    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1032    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1033    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1034    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1035    /// <param name="params">The streaming parameters.</param>
 1036    /// <param name="tag">The tag.</param>
 1037    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1038    /// <param name="playSessionId">The play session id.</param>
 1039    /// <param name="segmentContainer">The segment container.</param>
 1040    /// <param name="segmentLength">The desired segment length.</param>
 1041    /// <param name="minSegments">The minimum number of segments.</param>
 1042    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1043    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1044    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1045    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1046    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1047    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1048    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1049    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1050    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1051    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1052    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1053    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1054    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1055    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1056    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1057    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1058    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1059    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1060    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1061    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 1062    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 1063    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1064    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1065    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1066    /// <param name="maxRefFrames">Optional.</param>
 1067    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1068    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1069    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1070    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1071    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1072    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1073    /// <param name="liveStreamId">The live stream id.</param>
 1074    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1075    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1076    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1077    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1078    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1079    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1080    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1081    /// <param name="streamOptions">Optional. The streaming options.</param>
 1082    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1083    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 1084    /// <response code="200">Video stream returned.</response>
 1085    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1086    [HttpGet("Videos/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1087    [ProducesResponseType(StatusCodes.Status200OK)]
 1088    [ProducesVideoFile]
 1089    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1090    public async Task<ActionResult> GetHlsVideoSegment(
 1091        [FromRoute, Required] Guid itemId,
 1092        [FromRoute, Required] string playlistId,
 1093        [FromRoute, Required] int segmentId,
 1094        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
 1095        [FromQuery, Required] long runtimeTicks,
 1096        [FromQuery, Required] long actualSegmentLengthTicks,
 1097        [FromQuery] bool? @static,
 1098        [FromQuery] string? @params,
 1099        [FromQuery] string? tag,
 1100        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1101        [FromQuery] string? playSessionId,
 1102        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 1103        [FromQuery] int? segmentLength,
 1104        [FromQuery] int? minSegments,
 1105        [FromQuery] string? mediaSourceId,
 1106        [FromQuery] string? deviceId,
 1107        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 1108        [FromQuery] bool? enableAutoStreamCopy,
 1109        [FromQuery] bool? allowVideoStreamCopy,
 1110        [FromQuery] bool? allowAudioStreamCopy,
 1111        [FromQuery] int? audioSampleRate,
 1112        [FromQuery] int? maxAudioBitDepth,
 1113        [FromQuery] int? audioBitRate,
 1114        [FromQuery] int? audioChannels,
 1115        [FromQuery] int? maxAudioChannels,
 1116        [FromQuery] string? profile,
 1117        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 1118        [FromQuery] float? framerate,
 1119        [FromQuery] float? maxFramerate,
 1120        [FromQuery] bool? copyTimestamps,
 1121        [FromQuery] long? startTimeTicks,
 1122        [FromQuery] int? width,
 1123        [FromQuery] int? height,
 1124        [FromQuery] int? maxWidth,
 1125        [FromQuery] int? maxHeight,
 1126        [FromQuery] int? videoBitRate,
 1127        [FromQuery] int? subtitleStreamIndex,
 1128        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1129        [FromQuery] int? maxRefFrames,
 1130        [FromQuery] int? maxVideoBitDepth,
 1131        [FromQuery] bool? requireAvc,
 1132        [FromQuery] bool? deInterlace,
 1133        [FromQuery] bool? requireNonAnamorphic,
 1134        [FromQuery] int? transcodingMaxAudioChannels,
 1135        [FromQuery] int? cpuCoreLimit,
 1136        [FromQuery] string? liveStreamId,
 1137        [FromQuery] bool? enableMpegtsM2TsMode,
 1138        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 1139        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 1140        [FromQuery] string? transcodeReasons,
 1141        [FromQuery] int? audioStreamIndex,
 1142        [FromQuery] int? videoStreamIndex,
 1143        [FromQuery] EncodingContext? context,
 1144        [FromQuery] Dictionary<string, string> streamOptions,
 1145        [FromQuery] bool enableAudioVbrEncoding = true,
 1146        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 1147    {
 1148        var streamingRequest = new VideoRequestDto
 1149        {
 1150            Id = itemId,
 1151            CurrentRuntimeTicks = runtimeTicks,
 1152            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 1153            Container = container,
 1154            Static = @static ?? false,
 1155            Params = @params,
 1156            Tag = tag,
 1157            PlaySessionId = playSessionId,
 1158            SegmentContainer = segmentContainer,
 1159            SegmentLength = segmentLength,
 1160            MinSegments = minSegments,
 1161            MediaSourceId = mediaSourceId,
 1162            DeviceId = deviceId,
 1163            AudioCodec = audioCodec,
 1164            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 1165            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 1166            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 1167            AudioSampleRate = audioSampleRate,
 1168            MaxAudioChannels = maxAudioChannels,
 1169            AudioBitRate = audioBitRate,
 1170            MaxAudioBitDepth = maxAudioBitDepth,
 1171            AudioChannels = audioChannels,
 1172            Profile = profile,
 1173            Level = level,
 1174            Framerate = framerate,
 1175            MaxFramerate = maxFramerate,
 1176            CopyTimestamps = copyTimestamps ?? false,
 1177            StartTimeTicks = startTimeTicks,
 1178            Width = width,
 1179            Height = height,
 1180            MaxWidth = maxWidth,
 1181            MaxHeight = maxHeight,
 1182            VideoBitRate = videoBitRate,
 1183            SubtitleStreamIndex = subtitleStreamIndex,
 1184            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 1185            MaxRefFrames = maxRefFrames,
 1186            MaxVideoBitDepth = maxVideoBitDepth,
 1187            RequireAvc = requireAvc ?? false,
 1188            DeInterlace = deInterlace ?? false,
 1189            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 1190            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 1191            CpuCoreLimit = cpuCoreLimit,
 1192            LiveStreamId = liveStreamId,
 1193            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 1194            VideoCodec = videoCodec,
 1195            SubtitleCodec = subtitleCodec,
 1196            TranscodeReasons = transcodeReasons,
 1197            AudioStreamIndex = audioStreamIndex,
 1198            VideoStreamIndex = videoStreamIndex,
 1199            Context = context ?? EncodingContext.Streaming,
 1200            StreamOptions = streamOptions,
 1201            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 1202            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 1203        };
 1204
 1205        return await GetDynamicSegment(streamingRequest, segmentId)
 1206            .ConfigureAwait(false);
 1207    }
 1208
 1209    /// <summary>
 1210    /// Gets a video stream using HTTP live streaming.
 1211    /// </summary>
 1212    /// <param name="itemId">The item id.</param>
 1213    /// <param name="playlistId">The playlist id.</param>
 1214    /// <param name="segmentId">The segment id.</param>
 1215    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1216    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1217    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1218    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1219    /// <param name="params">The streaming parameters.</param>
 1220    /// <param name="tag">The tag.</param>
 1221    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1222    /// <param name="playSessionId">The play session id.</param>
 1223    /// <param name="segmentContainer">The segment container.</param>
 1224    /// <param name="segmentLength">The segment length.</param>
 1225    /// <param name="minSegments">The minimum number of segments.</param>
 1226    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1227    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1228    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1229    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1230    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1231    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1232    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1233    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1234    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 1235    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1236    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1237    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1238    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1239    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1240    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1241    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1242    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1243    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1244    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1245    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1246    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1247    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1248    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1249    /// <param name="maxRefFrames">Optional.</param>
 1250    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1251    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1252    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1253    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1254    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1255    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1256    /// <param name="liveStreamId">The live stream id.</param>
 1257    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1258    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1259    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1260    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1261    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1262    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1263    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1264    /// <param name="streamOptions">Optional. The streaming options.</param>
 1265    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1266    /// <response code="200">Video stream returned.</response>
 1267    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1268    [HttpGet("Audio/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1269    [ProducesResponseType(StatusCodes.Status200OK)]
 1270    [ProducesAudioFile]
 1271    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1272    public async Task<ActionResult> GetHlsAudioSegment(
 1273        [FromRoute, Required] Guid itemId,
 1274        [FromRoute, Required] string playlistId,
 1275        [FromRoute, Required] int segmentId,
 1276        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
 1277        [FromQuery, Required] long runtimeTicks,
 1278        [FromQuery, Required] long actualSegmentLengthTicks,
 1279        [FromQuery] bool? @static,
 1280        [FromQuery] string? @params,
 1281        [FromQuery] string? tag,
 1282        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1283        [FromQuery] string? playSessionId,
 1284        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 1285        [FromQuery] int? segmentLength,
 1286        [FromQuery] int? minSegments,
 1287        [FromQuery] string? mediaSourceId,
 1288        [FromQuery] string? deviceId,
 1289        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 1290        [FromQuery] bool? enableAutoStreamCopy,
 1291        [FromQuery] bool? allowVideoStreamCopy,
 1292        [FromQuery] bool? allowAudioStreamCopy,
 1293        [FromQuery] int? audioSampleRate,
 1294        [FromQuery] int? maxAudioBitDepth,
 1295        [FromQuery] int? maxStreamingBitrate,
 1296        [FromQuery] int? audioBitRate,
 1297        [FromQuery] int? audioChannels,
 1298        [FromQuery] int? maxAudioChannels,
 1299        [FromQuery] string? profile,
 1300        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 1301        [FromQuery] float? framerate,
 1302        [FromQuery] float? maxFramerate,
 1303        [FromQuery] bool? copyTimestamps,
 1304        [FromQuery] long? startTimeTicks,
 1305        [FromQuery] int? width,
 1306        [FromQuery] int? height,
 1307        [FromQuery] int? videoBitRate,
 1308        [FromQuery] int? subtitleStreamIndex,
 1309        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1310        [FromQuery] int? maxRefFrames,
 1311        [FromQuery] int? maxVideoBitDepth,
 1312        [FromQuery] bool? requireAvc,
 1313        [FromQuery] bool? deInterlace,
 1314        [FromQuery] bool? requireNonAnamorphic,
 1315        [FromQuery] int? transcodingMaxAudioChannels,
 1316        [FromQuery] int? cpuCoreLimit,
 1317        [FromQuery] string? liveStreamId,
 1318        [FromQuery] bool? enableMpegtsM2TsMode,
 1319        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 1320        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 1321        [FromQuery] string? transcodeReasons,
 1322        [FromQuery] int? audioStreamIndex,
 1323        [FromQuery] int? videoStreamIndex,
 1324        [FromQuery] EncodingContext? context,
 1325        [FromQuery] Dictionary<string, string> streamOptions,
 1326        [FromQuery] bool enableAudioVbrEncoding = true)
 1327    {
 1328        var streamingRequest = new StreamingRequestDto
 1329        {
 1330            Id = itemId,
 1331            Container = container,
 1332            CurrentRuntimeTicks = runtimeTicks,
 1333            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 1334            Static = @static ?? false,
 1335            Params = @params,
 1336            Tag = tag,
 1337            PlaySessionId = playSessionId,
 1338            SegmentContainer = segmentContainer,
 1339            SegmentLength = segmentLength,
 1340            MinSegments = minSegments,
 1341            MediaSourceId = mediaSourceId,
 1342            DeviceId = deviceId,
 1343            AudioCodec = audioCodec,
 1344            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 1345            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 1346            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 1347            AudioSampleRate = audioSampleRate,
 1348            MaxAudioChannels = maxAudioChannels,
 1349            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 1350            MaxAudioBitDepth = maxAudioBitDepth,
 1351            AudioChannels = audioChannels,
 1352            Profile = profile,
 1353            Level = level,
 1354            Framerate = framerate,
 1355            MaxFramerate = maxFramerate,
 1356            CopyTimestamps = copyTimestamps ?? false,
 1357            StartTimeTicks = startTimeTicks,
 1358            Width = width,
 1359            Height = height,
 1360            VideoBitRate = videoBitRate,
 1361            SubtitleStreamIndex = subtitleStreamIndex,
 1362            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 1363            MaxRefFrames = maxRefFrames,
 1364            MaxVideoBitDepth = maxVideoBitDepth,
 1365            RequireAvc = requireAvc ?? false,
 1366            DeInterlace = deInterlace ?? false,
 1367            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 1368            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 1369            CpuCoreLimit = cpuCoreLimit,
 1370            LiveStreamId = liveStreamId,
 1371            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 1372            VideoCodec = videoCodec,
 1373            SubtitleCodec = subtitleCodec,
 1374            TranscodeReasons = transcodeReasons,
 1375            AudioStreamIndex = audioStreamIndex,
 1376            VideoStreamIndex = videoStreamIndex,
 1377            Context = context ?? EncodingContext.Streaming,
 1378            StreamOptions = streamOptions,
 1379            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 1380            AlwaysBurnInSubtitleWhenTranscoding = false
 1381        };
 1382
 1383        return await GetDynamicSegment(streamingRequest, segmentId)
 1384            .ConfigureAwait(false);
 1385    }
 1386
 1387    private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto streamingRequest, CancellationTokenS
 1388    {
 1389        using var state = await StreamingHelpers.GetStreamingState(
 1390                streamingRequest,
 1391                HttpContext,
 1392                _mediaSourceManager,
 1393                _userManager,
 1394                _libraryManager,
 1395                _serverConfigurationManager,
 1396                _mediaEncoder,
 1397                _encodingHelper,
 1398                _transcodeManager,
 1399                TranscodingJobType,
 1400                cancellationTokenSource.Token)
 1401            .ConfigureAwait(false);
 1402        var mediaSourceId = state.BaseRequest.MediaSourceId;
 1403        double fps = state.TargetFramerate ?? 0.0f;
 1404        int segmentLength = state.SegmentLength * 1000;
 1405
 1406        // If framerate is fractional (i.e. 23.976), we need to slightly adjust segment length
 1407        if (Math.Abs(fps - Math.Floor(fps + 0.001f)) > 0.001)
 1408        {
 1409            double nearestIntFramerate = Math.Ceiling(fps);
 1410            segmentLength = (int)Math.Ceiling(segmentLength * (nearestIntFramerate / fps));
 1411        }
 1412
 1413        var request = new CreateMainPlaylistRequest(
 1414            mediaSourceId is null ? null : Guid.Parse(mediaSourceId),
 1415            state.MediaPath,
 1416            segmentLength,
 1417            state.RunTimeTicks ?? 0,
 1418            state.Request.SegmentContainer ?? string.Empty,
 1419            "hls1/main/",
 1420            Request.QueryString.ToString(),
 1421            EncodingHelper.IsCopyCodec(state.OutputVideoCodec));
 1422        var playlist = _dynamicHlsPlaylistGenerator.CreateMainPlaylist(request);
 1423
 1424        return new FileContentResult(Encoding.UTF8.GetBytes(playlist), MimeTypes.GetMimeType("playlist.m3u8"));
 1425    }
 1426
 1427    private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streamingRequest, int segmentId)
 1428    {
 1429        if ((streamingRequest.StartTimeTicks ?? 0) > 0)
 1430        {
 1431            throw new ArgumentException("StartTimeTicks is not allowed.");
 1432        }
 1433
 1434        // CTS lifecycle is managed internally.
 1435        var cancellationTokenSource = new CancellationTokenSource();
 1436        var cancellationToken = cancellationTokenSource.Token;
 1437
 1438        var state = await StreamingHelpers.GetStreamingState(
 1439                streamingRequest,
 1440                HttpContext,
 1441                _mediaSourceManager,
 1442                _userManager,
 1443                _libraryManager,
 1444                _serverConfigurationManager,
 1445                _mediaEncoder,
 1446                _encodingHelper,
 1447                _transcodeManager,
 1448                TranscodingJobType,
 1449                cancellationToken)
 1450            .ConfigureAwait(false);
 1451
 1452        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 1453
 1454        var segmentPath = GetSegmentPath(state, playlistPath, segmentId);
 1455
 1456        var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 1457
 1458        TranscodingJob? job;
 1459
 1460        if (System.IO.File.Exists(segmentPath))
 1461        {
 1462            job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1463            _logger.LogDebug("returning {0} [it exists, try 1]", segmentPath);
 1464            return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellati
 1465        }
 1466
 1467        using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 1468        {
 1469            var startTranscoding = false;
 1470            if (System.IO.File.Exists(segmentPath))
 1471            {
 1472                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1473                _logger.LogDebug("returning {0} [it exists, try 2]", segmentPath);
 1474                return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancel
 1475            }
 1476
 1477            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 1478            var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
 1479
 1480            if (segmentId == -1)
 1481            {
 1482                _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
 1483                startTranscoding = true;
 1484                segmentId = 0;
 1485            }
 1486            else if (currentTranscodingIndex is null)
 1487            {
 1488                _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
 1489                startTranscoding = true;
 1490            }
 1491            else if (segmentId < currentTranscodingIndex.Value)
 1492            {
 1493                _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segm
 1494                startTranscoding = true;
 1495            }
 1496            else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
 1497            {
 1498                _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIn
 1499                startTranscoding = true;
 1500            }
 1501
 1502            if (startTranscoding)
 1503            {
 1504                // If the playlist doesn't already exist, startup ffmpeg
 1505                try
 1506                {
 1507                    await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionI
 1508                        .ConfigureAwait(false);
 1509
 1510                    if (currentTranscodingIndex.HasValue)
 1511                    {
 1512                        await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
 1513                    }
 1514
 1515                    streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
 1516
 1517                    state.WaitForPath = segmentPath;
 1518                    job = await _transcodeManager.StartFfMpeg(
 1519                        state,
 1520                        playlistPath,
 1521                        GetCommandLineArguments(playlistPath, state, false, segmentId),
 1522                        Request.HttpContext.User.GetUserId(),
 1523                        TranscodingJobType,
 1524                        cancellationTokenSource).ConfigureAwait(false);
 1525                }
 1526                catch
 1527                {
 1528                    state.Dispose();
 1529                    throw;
 1530                }
 1531
 1532                // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false
 1533            }
 1534            else
 1535            {
 1536                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1537                if (job?.TranscodingThrottler is not null)
 1538                {
 1539                    await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
 1540                }
 1541            }
 1542        }
 1543
 1544        _logger.LogDebug("returning {0} [general case]", segmentPath);
 1545        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1546        return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationTo
 1547    }
 1548
 1549    private static double[] GetSegmentLengths(StreamState state)
 01550        => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength);
 1551
 1552    internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength)
 1553    {
 51554        var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks;
 51555        var wholeSegments = runtimeTicks / segmentLengthTicks;
 51556        var remainingTicks = runtimeTicks % segmentLengthTicks;
 1557
 51558        var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
 51559        var segments = new double[segmentsLen];
 141560        for (int i = 0; i < wholeSegments; i++)
 1561        {
 21562            segments[i] = segmentlength;
 1563        }
 1564
 51565        if (remainingTicks != 0)
 1566        {
 31567            segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
 1568        }
 1569
 51570        return segments;
 1571    }
 1572
 1573    private string GetCommandLineArguments(string outputPath, StreamState state, bool isEventPlaylist, int startNumber)
 1574    {
 01575        var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01576        var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
 1577
 01578        var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
 1579
 01580        var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) 
 01581        var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
 01582        var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
 01583        var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 01584        var outputTsArg = outputPrefix + "%d" + outputExtension;
 1585
 01586        var segmentFormat = string.Empty;
 01587        var segmentContainer = outputExtension.TrimStart('.');
 01588        var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions, segmentContainer);
 01589        var hlsArguments = $"-hls_playlist_type {(isEventPlaylist ? "event" : "vod")} -hls_list_size 0";
 1590
 01591        if (string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1592        {
 01593            segmentFormat = "mpegts";
 1594        }
 01595        else if (string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase))
 1596        {
 01597            var outputFmp4HeaderArg = OperatingSystem.IsWindows() switch
 01598            {
 01599                // on Windows, the path of fmp4 header file needs to be configured
 01600                true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"",
 01601                // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
 01602                false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""
 01603            };
 1604
 01605            var useLegacySegmentOption = _mediaEncoder.EncoderVersion < _minFFmpegHlsSegmentOptions;
 1606
 01607            if (state.VideoStream is not null && state.IsOutputVideo)
 1608            {
 1609                // fMP4 needs this flag to write the audio packet DTS/PTS including the initial delay into MOOF::TRAF::T
 01610                hlsArguments += $" {(useLegacySegmentOption ? "-hls_ts_options" : "-hls_segment_options")} movflags=+fra
 1611            }
 1612
 01613            segmentFormat = "fmp4" + outputFmp4HeaderArg;
 1614        }
 1615        else
 1616        {
 01617            _logger.LogError("Invalid HLS segment container: {SegmentContainer}, default to mpegts", segmentContainer);
 01618            segmentFormat = "mpegts";
 1619        }
 1620
 01621        var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
 01622            ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
 01623            : "128";
 1624
 01625        var baseUrlParam = string.Empty;
 01626        if (isEventPlaylist)
 1627        {
 01628            baseUrlParam = string.Format(
 01629                CultureInfo.InvariantCulture,
 01630                " -hls_base_url \"hls/{0}/\"",
 01631                Path.GetFileNameWithoutExtension(outputPath));
 1632        }
 1633
 01634        return string.Format(
 01635            CultureInfo.InvariantCulture,
 01636            "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max
 01637            inputModifier,
 01638            _encodingHelper.GetInputArgument(state, _encodingOptions, segmentContainer),
 01639            threads,
 01640            mapArgs,
 01641            GetVideoArguments(state, startNumber, isEventPlaylist, segmentContainer),
 01642            GetAudioArguments(state),
 01643            maxMuxingQueueSize,
 01644            state.SegmentLength.ToString(CultureInfo.InvariantCulture),
 01645            segmentFormat,
 01646            startNumber.ToString(CultureInfo.InvariantCulture),
 01647            baseUrlParam,
 01648            EncodingUtils.NormalizePath(outputTsArg),
 01649            hlsArguments,
 01650            EncodingUtils.NormalizePath(outputPath)).Trim();
 1651    }
 1652
 1653    /// <summary>
 1654    /// Gets the audio arguments for transcoding.
 1655    /// </summary>
 1656    /// <param name="state">The <see cref="StreamState"/>.</param>
 1657    /// <returns>The command line arguments for audio transcoding.</returns>
 1658    private string GetAudioArguments(StreamState state)
 1659    {
 01660        if (state.AudioStream is null)
 1661        {
 01662            return string.Empty;
 1663        }
 1664
 01665        var audioCodec = _encodingHelper.GetAudioEncoder(state);
 01666        var bitStreamArgs = _encodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.Medi
 1667
 1668        // opus, dts, truehd and flac (in FFmpeg 5 and older) are experimental in mp4 muxer
 01669        var strictArgs = string.Empty;
 01670        var actualOutputAudioCodec = state.ActualOutputAudioCodec;
 01671        if (string.Equals(actualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase)
 01672            || string.Equals(actualOutputAudioCodec, "dts", StringComparison.OrdinalIgnoreCase)
 01673            || string.Equals(actualOutputAudioCodec, "truehd", StringComparison.OrdinalIgnoreCase)
 01674            || (string.Equals(actualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase)
 01675                && _mediaEncoder.EncoderVersion < _minFFmpegFlacInMp4))
 1676        {
 01677            strictArgs = " -strict -2";
 1678        }
 1679
 01680        if (!state.IsOutputVideo)
 1681        {
 01682            var audioTranscodeParams = string.Empty;
 1683
 1684            // -vn to drop any video streams
 01685            audioTranscodeParams += "-vn";
 1686
 01687            if (EncodingHelper.IsCopyCodec(audioCodec))
 1688            {
 01689                return audioTranscodeParams + " -acodec copy" + bitStreamArgs + strictArgs;
 1690            }
 1691
 01692            audioTranscodeParams += " -acodec " + audioCodec + bitStreamArgs + strictArgs;
 1693
 01694            var audioBitrate = state.OutputAudioBitrate;
 01695            var audioChannels = state.OutputAudioChannels;
 1696
 01697            if (audioBitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(state.ActualOutputAudioCodec, Stri
 1698            {
 01699                var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, audioBitrate.Value, audioChannels ?? 2);
 01700                if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1701                {
 01702                    audioTranscodeParams += vbrParam;
 1703                }
 1704                else
 1705                {
 01706                    audioTranscodeParams += " -ab " + audioBitrate.Value.ToString(CultureInfo.InvariantCulture);
 1707                }
 1708            }
 1709
 01710            if (audioChannels.HasValue)
 1711            {
 01712                audioTranscodeParams += " -ac " + audioChannels.Value.ToString(CultureInfo.InvariantCulture);
 1713            }
 1714
 01715            if (state.OutputAudioSampleRate.HasValue)
 1716            {
 01717                audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCultur
 1718            }
 1719
 01720            return audioTranscodeParams;
 1721        }
 1722
 01723        if (EncodingHelper.IsCopyCodec(audioCodec))
 1724        {
 01725            var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01726            var copyArgs = "-codec:a:0 copy" + bitStreamArgs + strictArgs;
 1727
 01728            return copyArgs;
 1729        }
 1730
 01731        var args = "-codec:a:0 " + audioCodec + bitStreamArgs + strictArgs;
 1732
 01733        var channels = state.OutputAudioChannels;
 1734
 01735        var useDownMixAlgorithm = DownMixAlgorithmsHelper.AlgorithmFilterStrings.ContainsKey((_encodingOptions.DownMixSt
 1736
 01737        if (channels.HasValue
 01738            && (channels.Value != 2
 01739                || (state.AudioStream?.Channels is not null && !useDownMixAlgorithm)))
 1740        {
 01741            args += " -ac " + channels.Value;
 1742        }
 1743
 01744        var bitrate = state.OutputAudioBitrate;
 01745        if (bitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(actualOutputAudioCodec, StringComparison.Or
 1746        {
 01747            var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, bitrate.Value, channels ?? 2);
 01748            if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1749            {
 01750                args += vbrParam;
 1751            }
 1752            else
 1753            {
 01754                args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
 1755            }
 1756        }
 1757
 01758        if (state.OutputAudioSampleRate.HasValue)
 1759        {
 01760            args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
 1761        }
 01762        else if (state.AudioStream?.CodecTag is not null && state.AudioStream.CodecTag.Equals("ac-4", StringComparison.O
 1763        {
 1764            // ac-4 audio tends to have a super weird sample rate that will fail most encoders
 1765            // force resample it to 48KHz
 01766            args += " -ar 48000";
 1767        }
 1768
 01769        args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
 1770
 01771        return args;
 1772    }
 1773
 1774    /// <summary>
 1775    /// Gets the video arguments for transcoding.
 1776    /// </summary>
 1777    /// <param name="state">The <see cref="StreamState"/>.</param>
 1778    /// <param name="startNumber">The first number in the hls sequence.</param>
 1779    /// <param name="isEventPlaylist">Whether the playlist is EVENT or VOD.</param>
 1780    /// <param name="segmentContainer">The segment container.</param>
 1781    /// <returns>The command line arguments for video transcoding.</returns>
 1782    private string GetVideoArguments(StreamState state, int startNumber, bool isEventPlaylist, string segmentContainer)
 1783    {
 01784        if (state.VideoStream is null)
 1785        {
 01786            return string.Empty;
 1787        }
 1788
 01789        if (!state.IsOutputVideo)
 1790        {
 01791            return string.Empty;
 1792        }
 1793
 01794        var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 1795
 01796        var args = "-codec:v:0 " + codec;
 1797
 01798        var isActualOutputVideoCodecAv1 = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgn
 01799        var isActualOutputVideoCodecHevc = string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalI
 01800                                           || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.Ordin
 1801
 01802        if (isActualOutputVideoCodecHevc || isActualOutputVideoCodecAv1)
 1803        {
 01804            var requestedRange = state.GetRequestedRangeTypes(state.ActualOutputVideoCodec);
 1805            // Clients reporting Dolby Vision capabilities with fallbacks may only support the fallback layer.
 1806            // Only enable Dolby Vision remuxing if the client explicitly declares support for profiles without fallback
 01807            var clientSupportsDoVi = requestedRange.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgn
 01808            var videoIsDoVi = EncodingHelper.IsDovi(state.VideoStream);
 1809
 01810            if (EncodingHelper.IsCopyCodec(codec)
 01811                && (videoIsDoVi && clientSupportsDoVi)
 01812                && !_encodingHelper.IsDoviRemoved(state))
 1813            {
 01814                if (isActualOutputVideoCodecHevc)
 1815                {
 1816                    // Use hvc1 for 8.4. This is what Dolby uses for its official sample streams. Tagging with dvh1 woul
 01817                    var codecTag = state.VideoStream.VideoRangeType == VideoRangeType.DOVIWithHLG ? "hvc1" : "dvh1";
 01818                    args += $" -tag:v:0 {codecTag} -strict -2";
 1819                }
 01820                else if (isActualOutputVideoCodecAv1)
 1821                {
 01822                    args += " -tag:v:0 dav1 -strict -2";
 1823                }
 1824            }
 01825            else if (isActualOutputVideoCodecHevc)
 1826            {
 1827                // Prefer hvc1 to hev1
 01828                args += " -tag:v:0 hvc1";
 1829            }
 1830        }
 1831
 1832        // if  (state.EnableMpegtsM2TsMode)
 1833        // {
 1834        //     args += " -mpegts_m2ts_mode 1";
 1835        // }
 1836
 1837        // See if we can save come cpu cycles by avoiding encoding.
 01838        if (EncodingHelper.IsCopyCodec(codec))
 1839        {
 1840            // If h264_mp4toannexb is ever added, do not use it for live tv.
 01841            if (state.VideoStream is not null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.O
 1842            {
 01843                string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state, MediaStreamType.Video);
 01844                if (!string.IsNullOrEmpty(bitStreamArgs))
 1845                {
 01846                    args += " " + bitStreamArgs;
 1847                }
 1848            }
 1849
 01850            args += " -start_at_zero";
 1851        }
 1852        else
 1853        {
 01854            args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, isEventPlaylist ? DefaultEventE
 1855
 1856            // Set the key frame params for video encoding to match the hls segment time.
 01857            args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, isEventPlaylist, sta
 1858
 1859            // Currently b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
 01860            if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
 01861                && _mediaEncoder.EncoderVersion < _minFFmpegX265BframeInFmp4)
 1862            {
 01863                args += " -bf 0";
 1864            }
 1865
 1866            // video processing filters.
 01867            var videoProcessParam = _encodingHelper.GetVideoProcessingFilterParam(state, _encodingOptions, codec);
 1868
 01869            var negativeMapArgs = _encodingHelper.GetNegativeMapArgsByFilters(state, videoProcessParam);
 1870
 01871            args = negativeMapArgs + args + videoProcessParam;
 1872
 1873            // -start_at_zero is necessary to use with -ss when seeking,
 1874            // otherwise the target position cannot be determined.
 01875            if (state.SubtitleStream is not null)
 1876            {
 1877                // Disable start_at_zero for external graphical subs
 01878                if (!(state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
 1879                {
 01880                    args += " -start_at_zero";
 1881                }
 1882            }
 1883        }
 1884
 1885        // TODO why was this not enabled for VOD?
 01886        if (isEventPlaylist && string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1887        {
 01888            args += " -flags -global_header";
 1889        }
 1890
 01891        if (!string.IsNullOrEmpty(state.OutputVideoSync))
 1892        {
 01893            args += EncodingHelper.GetVideoSyncOption(state.OutputVideoSync, _mediaEncoder.EncoderVersion);
 1894        }
 1895
 01896        args += _encodingHelper.GetOutputFFlags(state);
 1897
 01898        return args;
 1899    }
 1900
 1901    private string GetSegmentPath(StreamState state, string playlist, int index)
 1902    {
 01903        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not 
 01904        var filename = Path.GetFileNameWithoutExtension(playlist);
 1905
 01906        return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + EncodingHelper.GetSegmentF
 1907    }
 1908
 1909    private async Task<ActionResult> GetSegmentResult(
 1910        StreamState state,
 1911        string playlistPath,
 1912        string segmentPath,
 1913        string segmentExtension,
 1914        int segmentIndex,
 1915        TranscodingJob? transcodingJob,
 1916        CancellationToken cancellationToken)
 1917    {
 1918        var segmentExists = System.IO.File.Exists(segmentPath);
 1919        if (segmentExists)
 1920        {
 1921            if (transcodingJob is not null && transcodingJob.HasExited)
 1922            {
 1923                // Transcoding job is over, so assume all existing files are ready
 1924                _logger.LogDebug("serving up {0} as transcode is over", segmentPath);
 1925                return GetSegmentResult(state, segmentPath, transcodingJob);
 1926            }
 1927
 1928            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 1929
 1930            // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's read
 1931            if (segmentIndex < currentTranscodingIndex)
 1932            {
 1933                _logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, curre
 1934                return GetSegmentResult(state, segmentPath, transcodingJob);
 1935            }
 1936        }
 1937
 1938        var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1);
 1939        if (transcodingJob is not null)
 1940        {
 1941            while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited)
 1942            {
 1943                // To be considered ready, the segment file has to exist AND
 1944                // either the transcoding job should be done or next segment should also exist
 1945                if (segmentExists)
 1946                {
 1947                    if (transcodingJob.HasExited || System.IO.File.Exists(nextSegmentPath))
 1948                    {
 1949                        _logger.LogDebug("Serving up {SegmentPath} as it deemed ready", segmentPath);
 1950                        return GetSegmentResult(state, segmentPath, transcodingJob);
 1951                    }
 1952                }
 1953                else
 1954                {
 1955                    segmentExists = System.IO.File.Exists(segmentPath);
 1956                    if (segmentExists)
 1957                    {
 1958                        continue; // avoid unnecessary waiting if segment just became available
 1959                    }
 1960                }
 1961
 1962                await Task.Delay(100, cancellationToken).ConfigureAwait(false);
 1963            }
 1964
 1965            if (!System.IO.File.Exists(segmentPath))
 1966            {
 1967                _logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath);
 1968            }
 1969            else
 1970            {
 1971                _logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath);
 1972            }
 1973
 1974            cancellationToken.ThrowIfCancellationRequested();
 1975        }
 1976        else
 1977        {
 1978            _logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath);
 1979        }
 1980
 1981        return GetSegmentResult(state, segmentPath, transcodingJob);
 1982    }
 1983
 1984    private ActionResult GetSegmentResult(StreamState state, string segmentPath, TranscodingJob? transcodingJob)
 1985    {
 01986        var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks;
 1987
 01988        Response.OnCompleted(() =>
 01989        {
 01990            _logger.LogDebug("Finished serving {SegmentPath}", segmentPath);
 01991            if (transcodingJob is not null)
 01992            {
 01993                transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPos
 01994                _transcodeManager.OnTranscodeEndRequest(transcodingJob);
 01995            }
 01996
 01997            return Task.CompletedTask;
 01998        });
 1999
 02000        return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
 2001    }
 2002
 2003    private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
 2004    {
 02005        var job = _transcodeManager.GetTranscodingJob(playlist, TranscodingJobType);
 2006
 02007        if (job is null || job.HasExited)
 2008        {
 02009            return null;
 2010        }
 2011
 02012        var file = GetLastTranscodingFile(playlist, segmentExtension, _fileSystem);
 2013
 02014        if (file is null)
 2015        {
 02016            return null;
 2017        }
 2018
 02019        var playlistFilename = Path.GetFileNameWithoutExtension(playlist.AsSpan());
 2020
 02021        var indexString = Path.GetFileNameWithoutExtension(file.Name.AsSpan()).Slice(playlistFilename.Length);
 2022
 02023        return int.Parse(indexString, NumberStyles.Integer, CultureInfo.InvariantCulture);
 2024    }
 2025
 2026    private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem file
 2027    {
 02028        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", n
 2029
 02030        var filePrefix = Path.GetFileNameWithoutExtension(playlist);
 2031
 2032        try
 2033        {
 02034            return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
 02035                .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgno
 02036                .MaxBy(fileSystem.GetLastWriteTimeUtc);
 2037        }
 02038        catch (IOException)
 2039        {
 02040            return null;
 2041        }
 02042    }
 2043
 2044    private async Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
 2045    {
 2046        var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
 2047
 2048        if (file is null)
 2049        {
 2050            return;
 2051        }
 2052
 2053        await DeleteFile(file.FullName, retryCount).ConfigureAwait(false);
 2054    }
 2055
 2056    private async Task DeleteFile(string path, int retryCount)
 2057    {
 2058        if (retryCount >= 5)
 2059        {
 2060            return;
 2061        }
 2062
 2063        _logger.LogDebug("Deleting partial HLS file {Path}", path);
 2064
 2065        try
 2066        {
 2067            _fileSystem.DeleteFile(path);
 2068        }
 2069        catch (IOException ex)
 2070        {
 2071            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 2072
 2073            await Task.Delay(100).ConfigureAwait(false);
 2074            await DeleteFile(path, retryCount + 1).ConfigureAwait(false);
 2075        }
 2076        catch (Exception ex)
 2077        {
 2078            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 2079        }
 2080    }
 2081}