< 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: 219
Coverable lines: 229
Total lines: 2106
Line coverage: 4.3%
Branch coverage
2%
Covered branches: 4
Total branches: 148
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 8/19/2025 - 12:10:00 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: 2106 8/19/2025 - 12:10:00 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: 2106

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
GetSegmentLengths(...)100%210%
GetSegmentLengthsInternal(...)100%44100%
GetCommandLineArguments(...)0%600240%
GetAudioArguments(...)0%4160640%
GetVideoArguments(...)0%2162460%
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="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 126    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 127    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 128    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 129    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 130    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 131    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 132    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 133    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 134    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 135    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 136    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 137    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 138    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 139    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 140    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 141    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 142    /// <param name="maxRefFrames">Optional.</param>
 143    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 144    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 145    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 146    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 147    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 148    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 149    /// <param name="liveStreamId">The live stream id.</param>
 150    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 151    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 152    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 153    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 154    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 155    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 156    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 157    /// <param name="streamOptions">Optional. The streaming options.</param>
 158    /// <param name="maxWidth">Optional. The max width.</param>
 159    /// <param name="maxHeight">Optional. The max height.</param>
 160    /// <param name="enableSubtitlesInManifest">Optional. Whether to enable subtitles in the manifest.</param>
 161    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 162    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 163    /// <response code="200">Hls live stream retrieved.</response>
 164    /// <returns>A <see cref="FileResult"/> containing the hls file.</returns>
 165    [HttpGet("Videos/{itemId}/live.m3u8")]
 166    [ProducesResponseType(StatusCodes.Status200OK)]
 167    [ProducesPlaylistFile]
 168    public async Task<ActionResult> GetLiveHlsStream(
 169        [FromRoute, Required] Guid itemId,
 170        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? container,
 171        [FromQuery] bool? @static,
 172        [FromQuery] string? @params,
 173        [FromQuery] string? tag,
 174        [FromQuery, ParameterObsolete] string? deviceProfileId,
 175        [FromQuery] string? playSessionId,
 176        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 177        [FromQuery] int? segmentLength,
 178        [FromQuery] int? minSegments,
 179        [FromQuery] string? mediaSourceId,
 180        [FromQuery] string? deviceId,
 181        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 182        [FromQuery] bool? enableAutoStreamCopy,
 183        [FromQuery] bool? allowVideoStreamCopy,
 184        [FromQuery] bool? allowAudioStreamCopy,
 185        [FromQuery] bool? breakOnNonKeyFrames,
 186        [FromQuery] int? audioSampleRate,
 187        [FromQuery] int? maxAudioBitDepth,
 188        [FromQuery] int? audioBitRate,
 189        [FromQuery] int? audioChannels,
 190        [FromQuery] int? maxAudioChannels,
 191        [FromQuery] string? profile,
 192        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 193        [FromQuery] float? framerate,
 194        [FromQuery] float? maxFramerate,
 195        [FromQuery] bool? copyTimestamps,
 196        [FromQuery] long? startTimeTicks,
 197        [FromQuery] int? width,
 198        [FromQuery] int? height,
 199        [FromQuery] int? videoBitRate,
 200        [FromQuery] int? subtitleStreamIndex,
 201        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 202        [FromQuery] int? maxRefFrames,
 203        [FromQuery] int? maxVideoBitDepth,
 204        [FromQuery] bool? requireAvc,
 205        [FromQuery] bool? deInterlace,
 206        [FromQuery] bool? requireNonAnamorphic,
 207        [FromQuery] int? transcodingMaxAudioChannels,
 208        [FromQuery] int? cpuCoreLimit,
 209        [FromQuery] string? liveStreamId,
 210        [FromQuery] bool? enableMpegtsM2TsMode,
 211        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 212        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 213        [FromQuery] string? transcodeReasons,
 214        [FromQuery] int? audioStreamIndex,
 215        [FromQuery] int? videoStreamIndex,
 216        [FromQuery] EncodingContext? context,
 217        [FromQuery] Dictionary<string, string> streamOptions,
 218        [FromQuery] int? maxWidth,
 219        [FromQuery] int? maxHeight,
 220        [FromQuery] bool? enableSubtitlesInManifest,
 221        [FromQuery] bool enableAudioVbrEncoding = true,
 222        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 223    {
 224        VideoRequestDto streamingRequest = new VideoRequestDto
 225        {
 226            Id = itemId,
 227            Container = container,
 228            Static = @static ?? false,
 229            Params = @params,
 230            Tag = tag,
 231            PlaySessionId = playSessionId,
 232            SegmentContainer = segmentContainer,
 233            SegmentLength = segmentLength,
 234            MinSegments = minSegments,
 235            MediaSourceId = mediaSourceId,
 236            DeviceId = deviceId,
 237            AudioCodec = audioCodec,
 238            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 239            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 240            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 241            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 242            AudioSampleRate = audioSampleRate,
 243            MaxAudioChannels = maxAudioChannels,
 244            AudioBitRate = audioBitRate,
 245            MaxAudioBitDepth = maxAudioBitDepth,
 246            AudioChannels = audioChannels,
 247            Profile = profile,
 248            Level = level,
 249            Framerate = framerate,
 250            MaxFramerate = maxFramerate,
 251            CopyTimestamps = copyTimestamps ?? false,
 252            StartTimeTicks = startTimeTicks,
 253            Width = width,
 254            Height = height,
 255            VideoBitRate = videoBitRate,
 256            SubtitleStreamIndex = subtitleStreamIndex,
 257            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 258            MaxRefFrames = maxRefFrames,
 259            MaxVideoBitDepth = maxVideoBitDepth,
 260            RequireAvc = requireAvc ?? false,
 261            DeInterlace = deInterlace ?? false,
 262            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 263            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 264            CpuCoreLimit = cpuCoreLimit,
 265            LiveStreamId = liveStreamId,
 266            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 267            VideoCodec = videoCodec,
 268            SubtitleCodec = subtitleCodec,
 269            TranscodeReasons = transcodeReasons,
 270            AudioStreamIndex = audioStreamIndex,
 271            VideoStreamIndex = videoStreamIndex,
 272            Context = context ?? EncodingContext.Streaming,
 273            StreamOptions = streamOptions,
 274            MaxHeight = maxHeight,
 275            MaxWidth = maxWidth,
 276            EnableSubtitlesInManifest = enableSubtitlesInManifest ?? true,
 277            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 278            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 279        };
 280
 281        // CTS lifecycle is managed internally.
 282        var cancellationTokenSource = new CancellationTokenSource();
 283        // Due to CTS.Token calling ThrowIfDisposed (https://github.com/dotnet/runtime/issues/29970) we have to "cache" 
 284        // since it gets disposed when ffmpeg exits
 285        var cancellationToken = cancellationTokenSource.Token;
 286        var state = await StreamingHelpers.GetStreamingState(
 287                streamingRequest,
 288                HttpContext,
 289                _mediaSourceManager,
 290                _userManager,
 291                _libraryManager,
 292                _serverConfigurationManager,
 293                _mediaEncoder,
 294                _encodingHelper,
 295                _transcodeManager,
 296                TranscodingJobType,
 297                cancellationToken)
 298            .ConfigureAwait(false);
 299
 300        TranscodingJob? job = null;
 301        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 302
 303        if (!System.IO.File.Exists(playlistPath))
 304        {
 305            using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 306            {
 307                if (!System.IO.File.Exists(playlistPath))
 308                {
 309                    // If the playlist doesn't already exist, startup ffmpeg
 310                    try
 311                    {
 312                        job = await _transcodeManager.StartFfMpeg(
 313                                state,
 314                                playlistPath,
 315                                GetCommandLineArguments(playlistPath, state, true, 0),
 316                                Request.HttpContext.User.GetUserId(),
 317                                TranscodingJobType,
 318                                cancellationTokenSource)
 319                            .ConfigureAwait(false);
 320                        job.IsLiveOutput = true;
 321                    }
 322                    catch
 323                    {
 324                        state.Dispose();
 325                        throw;
 326                    }
 327
 328                    minSegments = state.MinSegments;
 329                    if (minSegments > 0)
 330                    {
 331                        await HlsHelpers.WaitForMinimumSegmentCount(playlistPath, minSegments, _logger, cancellationToke
 332                    }
 333                }
 334            }
 335        }
 336
 337        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 338
 339        if (job is not null)
 340        {
 341            _transcodeManager.OnTranscodeEndRequest(job);
 342        }
 343
 344        var playlistText = HlsHelpers.GetLivePlaylistText(playlistPath, state);
 345
 346        return Content(playlistText, MimeTypes.GetMimeType("playlist.m3u8"));
 347    }
 348
 349    /// <summary>
 350    /// Gets a video hls playlist stream.
 351    /// </summary>
 352    /// <param name="itemId">The item id.</param>
 353    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 354    /// <param name="params">The streaming parameters.</param>
 355    /// <param name="tag">The tag.</param>
 356    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 357    /// <param name="playSessionId">The play session id.</param>
 358    /// <param name="segmentContainer">The segment container.</param>
 359    /// <param name="segmentLength">The segment length.</param>
 360    /// <param name="minSegments">The minimum number of segments.</param>
 361    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 362    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 363    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 364    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 365    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 366    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 367    /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 368    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 369    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 370    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 371    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 372    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 373    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 374    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 375    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 376    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 377    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 378    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 379    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 380    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 381    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 382    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 383    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 384    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 385    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 386    /// <param name="maxRefFrames">Optional.</param>
 387    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 388    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 389    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 390    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 391    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 392    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 393    /// <param name="liveStreamId">The live stream id.</param>
 394    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 395    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 396    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 397    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 398    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 399    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 400    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 401    /// <param name="streamOptions">Optional. The streaming options.</param>
 402    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 403    /// <param name="enableTrickplay">Enable trickplay image playlists being added to master playlist.</param>
 404    /// <param name="enableAudioVbrEncoding">Whether to enable Audio Encoding.</param>
 405    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 406    /// <response code="200">Video stream returned.</response>
 407    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 408    [HttpGet("Videos/{itemId}/master.m3u8")]
 409    [HttpHead("Videos/{itemId}/master.m3u8", Name = "HeadMasterHlsVideoPlaylist")]
 410    [ProducesResponseType(StatusCodes.Status200OK)]
 411    [ProducesPlaylistFile]
 412    public async Task<ActionResult> GetMasterHlsVideoPlaylist(
 413        [FromRoute, Required] Guid itemId,
 414        [FromQuery] bool? @static,
 415        [FromQuery] string? @params,
 416        [FromQuery] string? tag,
 417        [FromQuery, ParameterObsolete] string? deviceProfileId,
 418        [FromQuery] string? playSessionId,
 419        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 420        [FromQuery] int? segmentLength,
 421        [FromQuery] int? minSegments,
 422        [FromQuery, Required] string mediaSourceId,
 423        [FromQuery] string? deviceId,
 424        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 425        [FromQuery] bool? enableAutoStreamCopy,
 426        [FromQuery] bool? allowVideoStreamCopy,
 427        [FromQuery] bool? allowAudioStreamCopy,
 428        [FromQuery] bool? breakOnNonKeyFrames,
 429        [FromQuery] int? audioSampleRate,
 430        [FromQuery] int? maxAudioBitDepth,
 431        [FromQuery] int? audioBitRate,
 432        [FromQuery] int? audioChannels,
 433        [FromQuery] int? maxAudioChannels,
 434        [FromQuery] string? profile,
 435        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 436        [FromQuery] float? framerate,
 437        [FromQuery] float? maxFramerate,
 438        [FromQuery] bool? copyTimestamps,
 439        [FromQuery] long? startTimeTicks,
 440        [FromQuery] int? width,
 441        [FromQuery] int? height,
 442        [FromQuery] int? maxWidth,
 443        [FromQuery] int? maxHeight,
 444        [FromQuery] int? videoBitRate,
 445        [FromQuery] int? subtitleStreamIndex,
 446        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 447        [FromQuery] int? maxRefFrames,
 448        [FromQuery] int? maxVideoBitDepth,
 449        [FromQuery] bool? requireAvc,
 450        [FromQuery] bool? deInterlace,
 451        [FromQuery] bool? requireNonAnamorphic,
 452        [FromQuery] int? transcodingMaxAudioChannels,
 453        [FromQuery] int? cpuCoreLimit,
 454        [FromQuery] string? liveStreamId,
 455        [FromQuery] bool? enableMpegtsM2TsMode,
 456        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 457        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 458        [FromQuery] string? transcodeReasons,
 459        [FromQuery] int? audioStreamIndex,
 460        [FromQuery] int? videoStreamIndex,
 461        [FromQuery] EncodingContext? context,
 462        [FromQuery] Dictionary<string, string> streamOptions,
 463        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 464        [FromQuery] bool enableTrickplay = true,
 465        [FromQuery] bool enableAudioVbrEncoding = true,
 466        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 467    {
 468        var streamingRequest = new HlsVideoRequestDto
 469        {
 470            Id = itemId,
 471            Static = @static ?? false,
 472            Params = @params,
 473            Tag = tag,
 474            PlaySessionId = playSessionId,
 475            SegmentContainer = segmentContainer,
 476            SegmentLength = segmentLength,
 477            MinSegments = minSegments,
 478            MediaSourceId = mediaSourceId,
 479            DeviceId = deviceId,
 480            AudioCodec = audioCodec,
 481            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 482            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 483            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 484            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 485            AudioSampleRate = audioSampleRate,
 486            MaxAudioChannels = maxAudioChannels,
 487            AudioBitRate = audioBitRate,
 488            MaxAudioBitDepth = maxAudioBitDepth,
 489            AudioChannels = audioChannels,
 490            Profile = profile,
 491            Level = level,
 492            Framerate = framerate,
 493            MaxFramerate = maxFramerate,
 494            CopyTimestamps = copyTimestamps ?? false,
 495            StartTimeTicks = startTimeTicks,
 496            Width = width,
 497            Height = height,
 498            MaxWidth = maxWidth,
 499            MaxHeight = maxHeight,
 500            VideoBitRate = videoBitRate,
 501            SubtitleStreamIndex = subtitleStreamIndex,
 502            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 503            MaxRefFrames = maxRefFrames,
 504            MaxVideoBitDepth = maxVideoBitDepth,
 505            RequireAvc = requireAvc ?? false,
 506            DeInterlace = deInterlace ?? false,
 507            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 508            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 509            CpuCoreLimit = cpuCoreLimit,
 510            LiveStreamId = liveStreamId,
 511            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 512            VideoCodec = videoCodec,
 513            SubtitleCodec = subtitleCodec,
 514            TranscodeReasons = transcodeReasons,
 515            AudioStreamIndex = audioStreamIndex,
 516            VideoStreamIndex = videoStreamIndex,
 517            Context = context ?? EncodingContext.Streaming,
 518            StreamOptions = streamOptions,
 519            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 520            EnableTrickplay = enableTrickplay,
 521            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 522            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 523        };
 524
 525        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 526    }
 527
 528    /// <summary>
 529    /// Gets an audio hls playlist stream.
 530    /// </summary>
 531    /// <param name="itemId">The item id.</param>
 532    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 533    /// <param name="params">The streaming parameters.</param>
 534    /// <param name="tag">The tag.</param>
 535    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 536    /// <param name="playSessionId">The play session id.</param>
 537    /// <param name="segmentContainer">The segment container.</param>
 538    /// <param name="segmentLength">The segment length.</param>
 539    /// <param name="minSegments">The minimum number of segments.</param>
 540    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 541    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 542    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 543    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 544    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 545    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 546    /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 547    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 548    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 549    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 550    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 551    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 552    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 553    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 554    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 555    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 556    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 557    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 558    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 559    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 560    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 561    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 562    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 563    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 564    /// <param name="maxRefFrames">Optional.</param>
 565    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 566    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 567    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 568    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 569    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 570    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 571    /// <param name="liveStreamId">The live stream id.</param>
 572    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 573    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 574    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 575    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 576    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 577    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 578    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 579    /// <param name="streamOptions">Optional. The streaming options.</param>
 580    /// <param name="enableAdaptiveBitrateStreaming">Enable adaptive bitrate streaming.</param>
 581    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 582    /// <response code="200">Audio stream returned.</response>
 583    /// <returns>A <see cref="FileResult"/> containing the playlist file.</returns>
 584    [HttpGet("Audio/{itemId}/master.m3u8")]
 585    [HttpHead("Audio/{itemId}/master.m3u8", Name = "HeadMasterHlsAudioPlaylist")]
 586    [ProducesResponseType(StatusCodes.Status200OK)]
 587    [ProducesPlaylistFile]
 588    public async Task<ActionResult> GetMasterHlsAudioPlaylist(
 589        [FromRoute, Required] Guid itemId,
 590        [FromQuery] bool? @static,
 591        [FromQuery] string? @params,
 592        [FromQuery] string? tag,
 593        [FromQuery, ParameterObsolete] string? deviceProfileId,
 594        [FromQuery] string? playSessionId,
 595        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 596        [FromQuery] int? segmentLength,
 597        [FromQuery] int? minSegments,
 598        [FromQuery, Required] string mediaSourceId,
 599        [FromQuery] string? deviceId,
 600        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 601        [FromQuery] bool? enableAutoStreamCopy,
 602        [FromQuery] bool? allowVideoStreamCopy,
 603        [FromQuery] bool? allowAudioStreamCopy,
 604        [FromQuery] bool? breakOnNonKeyFrames,
 605        [FromQuery] int? audioSampleRate,
 606        [FromQuery] int? maxAudioBitDepth,
 607        [FromQuery] int? maxStreamingBitrate,
 608        [FromQuery] int? audioBitRate,
 609        [FromQuery] int? audioChannels,
 610        [FromQuery] int? maxAudioChannels,
 611        [FromQuery] string? profile,
 612        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 613        [FromQuery] float? framerate,
 614        [FromQuery] float? maxFramerate,
 615        [FromQuery] bool? copyTimestamps,
 616        [FromQuery] long? startTimeTicks,
 617        [FromQuery] int? width,
 618        [FromQuery] int? height,
 619        [FromQuery] int? videoBitRate,
 620        [FromQuery] int? subtitleStreamIndex,
 621        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 622        [FromQuery] int? maxRefFrames,
 623        [FromQuery] int? maxVideoBitDepth,
 624        [FromQuery] bool? requireAvc,
 625        [FromQuery] bool? deInterlace,
 626        [FromQuery] bool? requireNonAnamorphic,
 627        [FromQuery] int? transcodingMaxAudioChannels,
 628        [FromQuery] int? cpuCoreLimit,
 629        [FromQuery] string? liveStreamId,
 630        [FromQuery] bool? enableMpegtsM2TsMode,
 631        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 632        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 633        [FromQuery] string? transcodeReasons,
 634        [FromQuery] int? audioStreamIndex,
 635        [FromQuery] int? videoStreamIndex,
 636        [FromQuery] EncodingContext? context,
 637        [FromQuery] Dictionary<string, string> streamOptions,
 638        [FromQuery] bool enableAdaptiveBitrateStreaming = false,
 639        [FromQuery] bool enableAudioVbrEncoding = true)
 640    {
 641        var streamingRequest = new HlsAudioRequestDto
 642        {
 643            Id = itemId,
 644            Static = @static ?? false,
 645            Params = @params,
 646            Tag = tag,
 647            PlaySessionId = playSessionId,
 648            SegmentContainer = segmentContainer,
 649            SegmentLength = segmentLength,
 650            MinSegments = minSegments,
 651            MediaSourceId = mediaSourceId,
 652            DeviceId = deviceId,
 653            AudioCodec = audioCodec,
 654            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 655            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 656            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 657            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 658            AudioSampleRate = audioSampleRate,
 659            MaxAudioChannels = maxAudioChannels,
 660            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 661            MaxAudioBitDepth = maxAudioBitDepth,
 662            AudioChannels = audioChannels,
 663            Profile = profile,
 664            Level = level,
 665            Framerate = framerate,
 666            MaxFramerate = maxFramerate,
 667            CopyTimestamps = copyTimestamps ?? false,
 668            StartTimeTicks = startTimeTicks,
 669            Width = width,
 670            Height = height,
 671            VideoBitRate = videoBitRate,
 672            SubtitleStreamIndex = subtitleStreamIndex,
 673            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 674            MaxRefFrames = maxRefFrames,
 675            MaxVideoBitDepth = maxVideoBitDepth,
 676            RequireAvc = requireAvc ?? false,
 677            DeInterlace = deInterlace ?? false,
 678            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 679            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 680            CpuCoreLimit = cpuCoreLimit,
 681            LiveStreamId = liveStreamId,
 682            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 683            VideoCodec = videoCodec,
 684            SubtitleCodec = subtitleCodec,
 685            TranscodeReasons = transcodeReasons,
 686            AudioStreamIndex = audioStreamIndex,
 687            VideoStreamIndex = videoStreamIndex,
 688            Context = context ?? EncodingContext.Streaming,
 689            StreamOptions = streamOptions,
 690            EnableAdaptiveBitrateStreaming = enableAdaptiveBitrateStreaming,
 691            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 692            AlwaysBurnInSubtitleWhenTranscoding = false
 693        };
 694
 695        return await _dynamicHlsHelper.GetMasterHlsPlaylist(TranscodingJobType, streamingRequest, enableAdaptiveBitrateS
 696    }
 697
 698    /// <summary>
 699    /// Gets a video stream using HTTP live streaming.
 700    /// </summary>
 701    /// <param name="itemId">The item id.</param>
 702    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 703    /// <param name="params">The streaming parameters.</param>
 704    /// <param name="tag">The tag.</param>
 705    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 706    /// <param name="playSessionId">The play session id.</param>
 707    /// <param name="segmentContainer">The segment container.</param>
 708    /// <param name="segmentLength">The segment length.</param>
 709    /// <param name="minSegments">The minimum number of segments.</param>
 710    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 711    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 712    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 713    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 714    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 715    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 716    /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 717    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 718    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 719    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 720    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 721    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 722    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 723    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 724    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 725    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 726    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 727    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 728    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 729    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 730    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 731    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 732    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 733    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 734    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 735    /// <param name="maxRefFrames">Optional.</param>
 736    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 737    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 738    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 739    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 740    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 741    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 742    /// <param name="liveStreamId">The live stream id.</param>
 743    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 744    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 745    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 746    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 747    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 748    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 749    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 750    /// <param name="streamOptions">Optional. The streaming options.</param>
 751    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 752    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 753    /// <response code="200">Video stream returned.</response>
 754    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 755    [HttpGet("Videos/{itemId}/main.m3u8")]
 756    [ProducesResponseType(StatusCodes.Status200OK)]
 757    [ProducesPlaylistFile]
 758    public async Task<ActionResult> GetVariantHlsVideoPlaylist(
 759        [FromRoute, Required] Guid itemId,
 760        [FromQuery] bool? @static,
 761        [FromQuery] string? @params,
 762        [FromQuery] string? tag,
 763        [FromQuery, ParameterObsolete] string? deviceProfileId,
 764        [FromQuery] string? playSessionId,
 765        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 766        [FromQuery] int? segmentLength,
 767        [FromQuery] int? minSegments,
 768        [FromQuery] string? mediaSourceId,
 769        [FromQuery] string? deviceId,
 770        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 771        [FromQuery] bool? enableAutoStreamCopy,
 772        [FromQuery] bool? allowVideoStreamCopy,
 773        [FromQuery] bool? allowAudioStreamCopy,
 774        [FromQuery] bool? breakOnNonKeyFrames,
 775        [FromQuery] int? audioSampleRate,
 776        [FromQuery] int? maxAudioBitDepth,
 777        [FromQuery] int? audioBitRate,
 778        [FromQuery] int? audioChannels,
 779        [FromQuery] int? maxAudioChannels,
 780        [FromQuery] string? profile,
 781        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 782        [FromQuery] float? framerate,
 783        [FromQuery] float? maxFramerate,
 784        [FromQuery] bool? copyTimestamps,
 785        [FromQuery] long? startTimeTicks,
 786        [FromQuery] int? width,
 787        [FromQuery] int? height,
 788        [FromQuery] int? maxWidth,
 789        [FromQuery] int? maxHeight,
 790        [FromQuery] int? videoBitRate,
 791        [FromQuery] int? subtitleStreamIndex,
 792        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 793        [FromQuery] int? maxRefFrames,
 794        [FromQuery] int? maxVideoBitDepth,
 795        [FromQuery] bool? requireAvc,
 796        [FromQuery] bool? deInterlace,
 797        [FromQuery] bool? requireNonAnamorphic,
 798        [FromQuery] int? transcodingMaxAudioChannels,
 799        [FromQuery] int? cpuCoreLimit,
 800        [FromQuery] string? liveStreamId,
 801        [FromQuery] bool? enableMpegtsM2TsMode,
 802        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 803        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 804        [FromQuery] string? transcodeReasons,
 805        [FromQuery] int? audioStreamIndex,
 806        [FromQuery] int? videoStreamIndex,
 807        [FromQuery] EncodingContext? context,
 808        [FromQuery] Dictionary<string, string> streamOptions,
 809        [FromQuery] bool enableAudioVbrEncoding = true,
 810        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 811    {
 812        using var cancellationTokenSource = new CancellationTokenSource();
 813        var streamingRequest = new VideoRequestDto
 814        {
 815            Id = itemId,
 816            Static = @static ?? false,
 817            Params = @params,
 818            Tag = tag,
 819            PlaySessionId = playSessionId,
 820            SegmentContainer = segmentContainer,
 821            SegmentLength = segmentLength,
 822            MinSegments = minSegments,
 823            MediaSourceId = mediaSourceId,
 824            DeviceId = deviceId,
 825            AudioCodec = audioCodec,
 826            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 827            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 828            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 829            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 830            AudioSampleRate = audioSampleRate,
 831            MaxAudioChannels = maxAudioChannels,
 832            AudioBitRate = audioBitRate,
 833            MaxAudioBitDepth = maxAudioBitDepth,
 834            AudioChannels = audioChannels,
 835            Profile = profile,
 836            Level = level,
 837            Framerate = framerate,
 838            MaxFramerate = maxFramerate,
 839            CopyTimestamps = copyTimestamps ?? false,
 840            StartTimeTicks = startTimeTicks,
 841            Width = width,
 842            Height = height,
 843            MaxWidth = maxWidth,
 844            MaxHeight = maxHeight,
 845            VideoBitRate = videoBitRate,
 846            SubtitleStreamIndex = subtitleStreamIndex,
 847            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 848            MaxRefFrames = maxRefFrames,
 849            MaxVideoBitDepth = maxVideoBitDepth,
 850            RequireAvc = requireAvc ?? false,
 851            DeInterlace = deInterlace ?? false,
 852            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 853            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 854            CpuCoreLimit = cpuCoreLimit,
 855            LiveStreamId = liveStreamId,
 856            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 857            VideoCodec = videoCodec,
 858            SubtitleCodec = subtitleCodec,
 859            TranscodeReasons = transcodeReasons,
 860            AudioStreamIndex = audioStreamIndex,
 861            VideoStreamIndex = videoStreamIndex,
 862            Context = context ?? EncodingContext.Streaming,
 863            StreamOptions = streamOptions,
 864            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 865            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 866        };
 867
 868        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 869            .ConfigureAwait(false);
 870    }
 871
 872    /// <summary>
 873    /// Gets an audio stream using HTTP live streaming.
 874    /// </summary>
 875    /// <param name="itemId">The item id.</param>
 876    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 877    /// <param name="params">The streaming parameters.</param>
 878    /// <param name="tag">The tag.</param>
 879    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 880    /// <param name="playSessionId">The play session id.</param>
 881    /// <param name="segmentContainer">The segment container.</param>
 882    /// <param name="segmentLength">The segment length.</param>
 883    /// <param name="minSegments">The minimum number of segments.</param>
 884    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 885    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 886    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 887    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 888    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 889    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 890    /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 891    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 892    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 893    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 894    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 895    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 896    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 897    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 898    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 899    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 900    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 901    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 902    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 903    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 904    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 905    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 906    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 907    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 908    /// <param name="maxRefFrames">Optional.</param>
 909    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 910    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 911    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 912    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 913    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 914    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 915    /// <param name="liveStreamId">The live stream id.</param>
 916    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 917    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 918    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 919    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 920    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 921    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 922    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 923    /// <param name="streamOptions">Optional. The streaming options.</param>
 924    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 925    /// <response code="200">Audio stream returned.</response>
 926    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 927    [HttpGet("Audio/{itemId}/main.m3u8")]
 928    [ProducesResponseType(StatusCodes.Status200OK)]
 929    [ProducesPlaylistFile]
 930    public async Task<ActionResult> GetVariantHlsAudioPlaylist(
 931        [FromRoute, Required] Guid itemId,
 932        [FromQuery] bool? @static,
 933        [FromQuery] string? @params,
 934        [FromQuery] string? tag,
 935        [FromQuery, ParameterObsolete] string? deviceProfileId,
 936        [FromQuery] string? playSessionId,
 937        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 938        [FromQuery] int? segmentLength,
 939        [FromQuery] int? minSegments,
 940        [FromQuery] string? mediaSourceId,
 941        [FromQuery] string? deviceId,
 942        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 943        [FromQuery] bool? enableAutoStreamCopy,
 944        [FromQuery] bool? allowVideoStreamCopy,
 945        [FromQuery] bool? allowAudioStreamCopy,
 946        [FromQuery] bool? breakOnNonKeyFrames,
 947        [FromQuery] int? audioSampleRate,
 948        [FromQuery] int? maxAudioBitDepth,
 949        [FromQuery] int? maxStreamingBitrate,
 950        [FromQuery] int? audioBitRate,
 951        [FromQuery] int? audioChannels,
 952        [FromQuery] int? maxAudioChannels,
 953        [FromQuery] string? profile,
 954        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 955        [FromQuery] float? framerate,
 956        [FromQuery] float? maxFramerate,
 957        [FromQuery] bool? copyTimestamps,
 958        [FromQuery] long? startTimeTicks,
 959        [FromQuery] int? width,
 960        [FromQuery] int? height,
 961        [FromQuery] int? videoBitRate,
 962        [FromQuery] int? subtitleStreamIndex,
 963        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 964        [FromQuery] int? maxRefFrames,
 965        [FromQuery] int? maxVideoBitDepth,
 966        [FromQuery] bool? requireAvc,
 967        [FromQuery] bool? deInterlace,
 968        [FromQuery] bool? requireNonAnamorphic,
 969        [FromQuery] int? transcodingMaxAudioChannels,
 970        [FromQuery] int? cpuCoreLimit,
 971        [FromQuery] string? liveStreamId,
 972        [FromQuery] bool? enableMpegtsM2TsMode,
 973        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 974        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 975        [FromQuery] string? transcodeReasons,
 976        [FromQuery] int? audioStreamIndex,
 977        [FromQuery] int? videoStreamIndex,
 978        [FromQuery] EncodingContext? context,
 979        [FromQuery] Dictionary<string, string> streamOptions,
 980        [FromQuery] bool enableAudioVbrEncoding = true)
 981    {
 982        using var cancellationTokenSource = new CancellationTokenSource();
 983        var streamingRequest = new StreamingRequestDto
 984        {
 985            Id = itemId,
 986            Static = @static ?? false,
 987            Params = @params,
 988            Tag = tag,
 989            PlaySessionId = playSessionId,
 990            SegmentContainer = segmentContainer,
 991            SegmentLength = segmentLength,
 992            MinSegments = minSegments,
 993            MediaSourceId = mediaSourceId,
 994            DeviceId = deviceId,
 995            AudioCodec = audioCodec,
 996            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 997            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 998            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 999            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 1000            AudioSampleRate = audioSampleRate,
 1001            MaxAudioChannels = maxAudioChannels,
 1002            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 1003            MaxAudioBitDepth = maxAudioBitDepth,
 1004            AudioChannels = audioChannels,
 1005            Profile = profile,
 1006            Level = level,
 1007            Framerate = framerate,
 1008            MaxFramerate = maxFramerate,
 1009            CopyTimestamps = copyTimestamps ?? false,
 1010            StartTimeTicks = startTimeTicks,
 1011            Width = width,
 1012            Height = height,
 1013            VideoBitRate = videoBitRate,
 1014            SubtitleStreamIndex = subtitleStreamIndex,
 1015            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 1016            MaxRefFrames = maxRefFrames,
 1017            MaxVideoBitDepth = maxVideoBitDepth,
 1018            RequireAvc = requireAvc ?? false,
 1019            DeInterlace = deInterlace ?? false,
 1020            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 1021            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 1022            CpuCoreLimit = cpuCoreLimit,
 1023            LiveStreamId = liveStreamId,
 1024            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 1025            VideoCodec = videoCodec,
 1026            SubtitleCodec = subtitleCodec,
 1027            TranscodeReasons = transcodeReasons,
 1028            AudioStreamIndex = audioStreamIndex,
 1029            VideoStreamIndex = videoStreamIndex,
 1030            Context = context ?? EncodingContext.Streaming,
 1031            StreamOptions = streamOptions,
 1032            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 1033            AlwaysBurnInSubtitleWhenTranscoding = false
 1034        };
 1035
 1036        return await GetVariantPlaylistInternal(streamingRequest, cancellationTokenSource)
 1037            .ConfigureAwait(false);
 1038    }
 1039
 1040    /// <summary>
 1041    /// Gets a video stream using HTTP live streaming.
 1042    /// </summary>
 1043    /// <param name="itemId">The item id.</param>
 1044    /// <param name="playlistId">The playlist id.</param>
 1045    /// <param name="segmentId">The segment id.</param>
 1046    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1047    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1048    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1049    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1050    /// <param name="params">The streaming parameters.</param>
 1051    /// <param name="tag">The tag.</param>
 1052    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1053    /// <param name="playSessionId">The play session id.</param>
 1054    /// <param name="segmentContainer">The segment container.</param>
 1055    /// <param name="segmentLength">The desired segment length.</param>
 1056    /// <param name="minSegments">The minimum number of segments.</param>
 1057    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1058    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1059    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1060    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1061    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1062    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1063    /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 1064    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1065    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1066    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1067    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1068    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1069    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1070    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1071    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1072    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1073    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1074    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1075    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1076    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1077    /// <param name="maxWidth">Optional. The maximum horizontal resolution of the encoded video.</param>
 1078    /// <param name="maxHeight">Optional. The maximum vertical resolution of the encoded video.</param>
 1079    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1080    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1081    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1082    /// <param name="maxRefFrames">Optional.</param>
 1083    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1084    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1085    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1086    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1087    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1088    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1089    /// <param name="liveStreamId">The live stream id.</param>
 1090    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1091    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1092    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1093    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1094    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1095    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1096    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1097    /// <param name="streamOptions">Optional. The streaming options.</param>
 1098    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1099    /// <param name="alwaysBurnInSubtitleWhenTranscoding">Whether to always burn in subtitles when transcoding.</param>
 1100    /// <response code="200">Video stream returned.</response>
 1101    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1102    [HttpGet("Videos/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1103    [ProducesResponseType(StatusCodes.Status200OK)]
 1104    [ProducesVideoFile]
 1105    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1106    public async Task<ActionResult> GetHlsVideoSegment(
 1107        [FromRoute, Required] Guid itemId,
 1108        [FromRoute, Required] string playlistId,
 1109        [FromRoute, Required] int segmentId,
 1110        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
 1111        [FromQuery, Required] long runtimeTicks,
 1112        [FromQuery, Required] long actualSegmentLengthTicks,
 1113        [FromQuery] bool? @static,
 1114        [FromQuery] string? @params,
 1115        [FromQuery] string? tag,
 1116        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1117        [FromQuery] string? playSessionId,
 1118        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 1119        [FromQuery] int? segmentLength,
 1120        [FromQuery] int? minSegments,
 1121        [FromQuery] string? mediaSourceId,
 1122        [FromQuery] string? deviceId,
 1123        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 1124        [FromQuery] bool? enableAutoStreamCopy,
 1125        [FromQuery] bool? allowVideoStreamCopy,
 1126        [FromQuery] bool? allowAudioStreamCopy,
 1127        [FromQuery] bool? breakOnNonKeyFrames,
 1128        [FromQuery] int? audioSampleRate,
 1129        [FromQuery] int? maxAudioBitDepth,
 1130        [FromQuery] int? audioBitRate,
 1131        [FromQuery] int? audioChannels,
 1132        [FromQuery] int? maxAudioChannels,
 1133        [FromQuery] string? profile,
 1134        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 1135        [FromQuery] float? framerate,
 1136        [FromQuery] float? maxFramerate,
 1137        [FromQuery] bool? copyTimestamps,
 1138        [FromQuery] long? startTimeTicks,
 1139        [FromQuery] int? width,
 1140        [FromQuery] int? height,
 1141        [FromQuery] int? maxWidth,
 1142        [FromQuery] int? maxHeight,
 1143        [FromQuery] int? videoBitRate,
 1144        [FromQuery] int? subtitleStreamIndex,
 1145        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1146        [FromQuery] int? maxRefFrames,
 1147        [FromQuery] int? maxVideoBitDepth,
 1148        [FromQuery] bool? requireAvc,
 1149        [FromQuery] bool? deInterlace,
 1150        [FromQuery] bool? requireNonAnamorphic,
 1151        [FromQuery] int? transcodingMaxAudioChannels,
 1152        [FromQuery] int? cpuCoreLimit,
 1153        [FromQuery] string? liveStreamId,
 1154        [FromQuery] bool? enableMpegtsM2TsMode,
 1155        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 1156        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 1157        [FromQuery] string? transcodeReasons,
 1158        [FromQuery] int? audioStreamIndex,
 1159        [FromQuery] int? videoStreamIndex,
 1160        [FromQuery] EncodingContext? context,
 1161        [FromQuery] Dictionary<string, string> streamOptions,
 1162        [FromQuery] bool enableAudioVbrEncoding = true,
 1163        [FromQuery] bool alwaysBurnInSubtitleWhenTranscoding = false)
 1164    {
 1165        var streamingRequest = new VideoRequestDto
 1166        {
 1167            Id = itemId,
 1168            CurrentRuntimeTicks = runtimeTicks,
 1169            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 1170            Container = container,
 1171            Static = @static ?? false,
 1172            Params = @params,
 1173            Tag = tag,
 1174            PlaySessionId = playSessionId,
 1175            SegmentContainer = segmentContainer,
 1176            SegmentLength = segmentLength,
 1177            MinSegments = minSegments,
 1178            MediaSourceId = mediaSourceId,
 1179            DeviceId = deviceId,
 1180            AudioCodec = audioCodec,
 1181            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 1182            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 1183            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 1184            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 1185            AudioSampleRate = audioSampleRate,
 1186            MaxAudioChannels = maxAudioChannels,
 1187            AudioBitRate = audioBitRate,
 1188            MaxAudioBitDepth = maxAudioBitDepth,
 1189            AudioChannels = audioChannels,
 1190            Profile = profile,
 1191            Level = level,
 1192            Framerate = framerate,
 1193            MaxFramerate = maxFramerate,
 1194            CopyTimestamps = copyTimestamps ?? false,
 1195            StartTimeTicks = startTimeTicks,
 1196            Width = width,
 1197            Height = height,
 1198            MaxWidth = maxWidth,
 1199            MaxHeight = maxHeight,
 1200            VideoBitRate = videoBitRate,
 1201            SubtitleStreamIndex = subtitleStreamIndex,
 1202            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 1203            MaxRefFrames = maxRefFrames,
 1204            MaxVideoBitDepth = maxVideoBitDepth,
 1205            RequireAvc = requireAvc ?? false,
 1206            DeInterlace = deInterlace ?? false,
 1207            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 1208            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 1209            CpuCoreLimit = cpuCoreLimit,
 1210            LiveStreamId = liveStreamId,
 1211            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 1212            VideoCodec = videoCodec,
 1213            SubtitleCodec = subtitleCodec,
 1214            TranscodeReasons = transcodeReasons,
 1215            AudioStreamIndex = audioStreamIndex,
 1216            VideoStreamIndex = videoStreamIndex,
 1217            Context = context ?? EncodingContext.Streaming,
 1218            StreamOptions = streamOptions,
 1219            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 1220            AlwaysBurnInSubtitleWhenTranscoding = alwaysBurnInSubtitleWhenTranscoding
 1221        };
 1222
 1223        return await GetDynamicSegment(streamingRequest, segmentId)
 1224            .ConfigureAwait(false);
 1225    }
 1226
 1227    /// <summary>
 1228    /// Gets a video stream using HTTP live streaming.
 1229    /// </summary>
 1230    /// <param name="itemId">The item id.</param>
 1231    /// <param name="playlistId">The playlist id.</param>
 1232    /// <param name="segmentId">The segment id.</param>
 1233    /// <param name="container">The video container. Possible values are: ts, webm, asf, wmv, ogv, mp4, m4v, mkv, mpeg, 
 1234    /// <param name="runtimeTicks">The position of the requested segment in ticks.</param>
 1235    /// <param name="actualSegmentLengthTicks">The length of the requested segment in ticks.</param>
 1236    /// <param name="static">Optional. If true, the original file will be streamed statically without any encoding. Use 
 1237    /// <param name="params">The streaming parameters.</param>
 1238    /// <param name="tag">The tag.</param>
 1239    /// <param name="deviceProfileId">Optional. The dlna device profile id to utilize.</param>
 1240    /// <param name="playSessionId">The play session id.</param>
 1241    /// <param name="segmentContainer">The segment container.</param>
 1242    /// <param name="segmentLength">The segment length.</param>
 1243    /// <param name="minSegments">The minimum number of segments.</param>
 1244    /// <param name="mediaSourceId">The media version id, if playing an alternate version.</param>
 1245    /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</par
 1246    /// <param name="audioCodec">Optional. Specify an audio codec to encode to, e.g. mp3.</param>
 1247    /// <param name="enableAutoStreamCopy">Whether or not to allow automatic stream copy if requested values match the o
 1248    /// <param name="allowVideoStreamCopy">Whether or not to allow copying of the video stream url.</param>
 1249    /// <param name="allowAudioStreamCopy">Whether or not to allow copying of the audio stream url.</param>
 1250    /// <param name="breakOnNonKeyFrames">Optional. Whether to break on non key frames.</param>
 1251    /// <param name="audioSampleRate">Optional. Specify a specific audio sample rate, e.g. 44100.</param>
 1252    /// <param name="maxAudioBitDepth">Optional. The maximum audio bit depth.</param>
 1253    /// <param name="maxStreamingBitrate">Optional. The maximum streaming bitrate.</param>
 1254    /// <param name="audioBitRate">Optional. Specify an audio bitrate to encode to, e.g. 128000. If omitted this will be
 1255    /// <param name="audioChannels">Optional. Specify a specific number of audio channels to encode to, e.g. 2.</param>
 1256    /// <param name="maxAudioChannels">Optional. Specify a maximum number of audio channels to encode to, e.g. 2.</param
 1257    /// <param name="profile">Optional. Specify a specific an encoder profile (varies by encoder), e.g. main, baseline, 
 1258    /// <param name="level">Optional. Specify a level for the encoder profile (varies by encoder), e.g. 3, 3.1.</param>
 1259    /// <param name="framerate">Optional. A specific video framerate to encode to, e.g. 23.976. Generally this should be
 1260    /// <param name="maxFramerate">Optional. A specific maximum video framerate to encode to, e.g. 23.976. Generally thi
 1261    /// <param name="copyTimestamps">Whether or not to copy timestamps when transcoding with an offset. Defaults to fals
 1262    /// <param name="startTimeTicks">Optional. Specify a starting offset, in ticks. 1 tick = 10000 ms.</param>
 1263    /// <param name="width">Optional. The fixed horizontal resolution of the encoded video.</param>
 1264    /// <param name="height">Optional. The fixed vertical resolution of the encoded video.</param>
 1265    /// <param name="videoBitRate">Optional. Specify a video bitrate to encode to, e.g. 500000. If omitted this will be 
 1266    /// <param name="subtitleStreamIndex">Optional. The index of the subtitle stream to use. If omitted no subtitles wil
 1267    /// <param name="subtitleMethod">Optional. Specify the subtitle delivery method.</param>
 1268    /// <param name="maxRefFrames">Optional.</param>
 1269    /// <param name="maxVideoBitDepth">Optional. The maximum video bit depth.</param>
 1270    /// <param name="requireAvc">Optional. Whether to require avc.</param>
 1271    /// <param name="deInterlace">Optional. Whether to deinterlace the video.</param>
 1272    /// <param name="requireNonAnamorphic">Optional. Whether to require a non anamorphic stream.</param>
 1273    /// <param name="transcodingMaxAudioChannels">Optional. The maximum number of audio channels to transcode.</param>
 1274    /// <param name="cpuCoreLimit">Optional. The limit of how many cpu cores to use.</param>
 1275    /// <param name="liveStreamId">The live stream id.</param>
 1276    /// <param name="enableMpegtsM2TsMode">Optional. Whether to enable the MpegtsM2Ts mode.</param>
 1277    /// <param name="videoCodec">Optional. Specify a video codec to encode to, e.g. h264.</param>
 1278    /// <param name="subtitleCodec">Optional. Specify a subtitle codec to encode to.</param>
 1279    /// <param name="transcodeReasons">Optional. The transcoding reason.</param>
 1280    /// <param name="audioStreamIndex">Optional. The index of the audio stream to use. If omitted the first audio stream
 1281    /// <param name="videoStreamIndex">Optional. The index of the video stream to use. If omitted the first video stream
 1282    /// <param name="context">Optional. The <see cref="EncodingContext"/>.</param>
 1283    /// <param name="streamOptions">Optional. The streaming options.</param>
 1284    /// <param name="enableAudioVbrEncoding">Optional. Whether to enable Audio Encoding.</param>
 1285    /// <response code="200">Video stream returned.</response>
 1286    /// <returns>A <see cref="FileResult"/> containing the audio file.</returns>
 1287    [HttpGet("Audio/{itemId}/hls1/{playlistId}/{segmentId}.{container}")]
 1288    [ProducesResponseType(StatusCodes.Status200OK)]
 1289    [ProducesAudioFile]
 1290    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "playlistId", Justification =
 1291    public async Task<ActionResult> GetHlsAudioSegment(
 1292        [FromRoute, Required] Guid itemId,
 1293        [FromRoute, Required] string playlistId,
 1294        [FromRoute, Required] int segmentId,
 1295        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container,
 1296        [FromQuery, Required] long runtimeTicks,
 1297        [FromQuery, Required] long actualSegmentLengthTicks,
 1298        [FromQuery] bool? @static,
 1299        [FromQuery] string? @params,
 1300        [FromQuery] string? tag,
 1301        [FromQuery, ParameterObsolete] string? deviceProfileId,
 1302        [FromQuery] string? playSessionId,
 1303        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? segmentContainer,
 1304        [FromQuery] int? segmentLength,
 1305        [FromQuery] int? minSegments,
 1306        [FromQuery] string? mediaSourceId,
 1307        [FromQuery] string? deviceId,
 1308        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? audioCodec,
 1309        [FromQuery] bool? enableAutoStreamCopy,
 1310        [FromQuery] bool? allowVideoStreamCopy,
 1311        [FromQuery] bool? allowAudioStreamCopy,
 1312        [FromQuery] bool? breakOnNonKeyFrames,
 1313        [FromQuery] int? audioSampleRate,
 1314        [FromQuery] int? maxAudioBitDepth,
 1315        [FromQuery] int? maxStreamingBitrate,
 1316        [FromQuery] int? audioBitRate,
 1317        [FromQuery] int? audioChannels,
 1318        [FromQuery] int? maxAudioChannels,
 1319        [FromQuery] string? profile,
 1320        [FromQuery] [RegularExpression(EncodingHelper.LevelValidationRegex)] string? level,
 1321        [FromQuery] float? framerate,
 1322        [FromQuery] float? maxFramerate,
 1323        [FromQuery] bool? copyTimestamps,
 1324        [FromQuery] long? startTimeTicks,
 1325        [FromQuery] int? width,
 1326        [FromQuery] int? height,
 1327        [FromQuery] int? videoBitRate,
 1328        [FromQuery] int? subtitleStreamIndex,
 1329        [FromQuery] SubtitleDeliveryMethod? subtitleMethod,
 1330        [FromQuery] int? maxRefFrames,
 1331        [FromQuery] int? maxVideoBitDepth,
 1332        [FromQuery] bool? requireAvc,
 1333        [FromQuery] bool? deInterlace,
 1334        [FromQuery] bool? requireNonAnamorphic,
 1335        [FromQuery] int? transcodingMaxAudioChannels,
 1336        [FromQuery] int? cpuCoreLimit,
 1337        [FromQuery] string? liveStreamId,
 1338        [FromQuery] bool? enableMpegtsM2TsMode,
 1339        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? videoCodec,
 1340        [FromQuery] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string? subtitleCodec,
 1341        [FromQuery] string? transcodeReasons,
 1342        [FromQuery] int? audioStreamIndex,
 1343        [FromQuery] int? videoStreamIndex,
 1344        [FromQuery] EncodingContext? context,
 1345        [FromQuery] Dictionary<string, string> streamOptions,
 1346        [FromQuery] bool enableAudioVbrEncoding = true)
 1347    {
 1348        var streamingRequest = new StreamingRequestDto
 1349        {
 1350            Id = itemId,
 1351            Container = container,
 1352            CurrentRuntimeTicks = runtimeTicks,
 1353            ActualSegmentLengthTicks = actualSegmentLengthTicks,
 1354            Static = @static ?? false,
 1355            Params = @params,
 1356            Tag = tag,
 1357            PlaySessionId = playSessionId,
 1358            SegmentContainer = segmentContainer,
 1359            SegmentLength = segmentLength,
 1360            MinSegments = minSegments,
 1361            MediaSourceId = mediaSourceId,
 1362            DeviceId = deviceId,
 1363            AudioCodec = audioCodec,
 1364            EnableAutoStreamCopy = enableAutoStreamCopy ?? true,
 1365            AllowAudioStreamCopy = allowAudioStreamCopy ?? true,
 1366            AllowVideoStreamCopy = allowVideoStreamCopy ?? true,
 1367            BreakOnNonKeyFrames = breakOnNonKeyFrames ?? false,
 1368            AudioSampleRate = audioSampleRate,
 1369            MaxAudioChannels = maxAudioChannels,
 1370            AudioBitRate = audioBitRate ?? maxStreamingBitrate,
 1371            MaxAudioBitDepth = maxAudioBitDepth,
 1372            AudioChannels = audioChannels,
 1373            Profile = profile,
 1374            Level = level,
 1375            Framerate = framerate,
 1376            MaxFramerate = maxFramerate,
 1377            CopyTimestamps = copyTimestamps ?? false,
 1378            StartTimeTicks = startTimeTicks,
 1379            Width = width,
 1380            Height = height,
 1381            VideoBitRate = videoBitRate,
 1382            SubtitleStreamIndex = subtitleStreamIndex,
 1383            SubtitleMethod = subtitleMethod ?? SubtitleDeliveryMethod.External,
 1384            MaxRefFrames = maxRefFrames,
 1385            MaxVideoBitDepth = maxVideoBitDepth,
 1386            RequireAvc = requireAvc ?? false,
 1387            DeInterlace = deInterlace ?? false,
 1388            RequireNonAnamorphic = requireNonAnamorphic ?? false,
 1389            TranscodingMaxAudioChannels = transcodingMaxAudioChannels,
 1390            CpuCoreLimit = cpuCoreLimit,
 1391            LiveStreamId = liveStreamId,
 1392            EnableMpegtsM2TsMode = enableMpegtsM2TsMode ?? false,
 1393            VideoCodec = videoCodec,
 1394            SubtitleCodec = subtitleCodec,
 1395            TranscodeReasons = transcodeReasons,
 1396            AudioStreamIndex = audioStreamIndex,
 1397            VideoStreamIndex = videoStreamIndex,
 1398            Context = context ?? EncodingContext.Streaming,
 1399            StreamOptions = streamOptions,
 1400            EnableAudioVbrEncoding = enableAudioVbrEncoding,
 1401            AlwaysBurnInSubtitleWhenTranscoding = false
 1402        };
 1403
 1404        return await GetDynamicSegment(streamingRequest, segmentId)
 1405            .ConfigureAwait(false);
 1406    }
 1407
 1408    private async Task<ActionResult> GetVariantPlaylistInternal(StreamingRequestDto streamingRequest, CancellationTokenS
 1409    {
 1410        using var state = await StreamingHelpers.GetStreamingState(
 1411                streamingRequest,
 1412                HttpContext,
 1413                _mediaSourceManager,
 1414                _userManager,
 1415                _libraryManager,
 1416                _serverConfigurationManager,
 1417                _mediaEncoder,
 1418                _encodingHelper,
 1419                _transcodeManager,
 1420                TranscodingJobType,
 1421                cancellationTokenSource.Token)
 1422            .ConfigureAwait(false);
 1423        var mediaSourceId = state.BaseRequest.MediaSourceId;
 1424        var request = new CreateMainPlaylistRequest(
 1425            mediaSourceId is null ? null : Guid.Parse(mediaSourceId),
 1426            state.MediaPath,
 1427            state.SegmentLength * 1000,
 1428            state.RunTimeTicks ?? 0,
 1429            state.Request.SegmentContainer ?? string.Empty,
 1430            "hls1/main/",
 1431            Request.QueryString.ToString(),
 1432            EncodingHelper.IsCopyCodec(state.OutputVideoCodec));
 1433        var playlist = _dynamicHlsPlaylistGenerator.CreateMainPlaylist(request);
 1434
 1435        return new FileContentResult(Encoding.UTF8.GetBytes(playlist), MimeTypes.GetMimeType("playlist.m3u8"));
 1436    }
 1437
 1438    private async Task<ActionResult> GetDynamicSegment(StreamingRequestDto streamingRequest, int segmentId)
 1439    {
 1440        if ((streamingRequest.StartTimeTicks ?? 0) > 0)
 1441        {
 1442            throw new ArgumentException("StartTimeTicks is not allowed.");
 1443        }
 1444
 1445        // CTS lifecycle is managed internally.
 1446        var cancellationTokenSource = new CancellationTokenSource();
 1447        var cancellationToken = cancellationTokenSource.Token;
 1448
 1449        var state = await StreamingHelpers.GetStreamingState(
 1450                streamingRequest,
 1451                HttpContext,
 1452                _mediaSourceManager,
 1453                _userManager,
 1454                _libraryManager,
 1455                _serverConfigurationManager,
 1456                _mediaEncoder,
 1457                _encodingHelper,
 1458                _transcodeManager,
 1459                TranscodingJobType,
 1460                cancellationToken)
 1461            .ConfigureAwait(false);
 1462
 1463        var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
 1464
 1465        var segmentPath = GetSegmentPath(state, playlistPath, segmentId);
 1466
 1467        var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 1468
 1469        TranscodingJob? job;
 1470
 1471        if (System.IO.File.Exists(segmentPath))
 1472        {
 1473            job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1474            _logger.LogDebug("returning {0} [it exists, try 1]", segmentPath);
 1475            return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellati
 1476        }
 1477
 1478        using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
 1479        {
 1480            var startTranscoding = false;
 1481            if (System.IO.File.Exists(segmentPath))
 1482            {
 1483                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1484                _logger.LogDebug("returning {0} [it exists, try 2]", segmentPath);
 1485                return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancel
 1486            }
 1487
 1488            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 1489            var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
 1490
 1491            if (segmentId == -1)
 1492            {
 1493                _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
 1494                startTranscoding = true;
 1495                segmentId = 0;
 1496            }
 1497            else if (currentTranscodingIndex is null)
 1498            {
 1499                _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
 1500                startTranscoding = true;
 1501            }
 1502            else if (segmentId < currentTranscodingIndex.Value)
 1503            {
 1504                _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segm
 1505                startTranscoding = true;
 1506            }
 1507            else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
 1508            {
 1509                _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIn
 1510                startTranscoding = true;
 1511            }
 1512
 1513            if (startTranscoding)
 1514            {
 1515                // If the playlist doesn't already exist, startup ffmpeg
 1516                try
 1517                {
 1518                    await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionI
 1519                        .ConfigureAwait(false);
 1520
 1521                    if (currentTranscodingIndex.HasValue)
 1522                    {
 1523                        await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
 1524                    }
 1525
 1526                    streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
 1527
 1528                    state.WaitForPath = segmentPath;
 1529                    job = await _transcodeManager.StartFfMpeg(
 1530                        state,
 1531                        playlistPath,
 1532                        GetCommandLineArguments(playlistPath, state, false, segmentId),
 1533                        Request.HttpContext.User.GetUserId(),
 1534                        TranscodingJobType,
 1535                        cancellationTokenSource).ConfigureAwait(false);
 1536                }
 1537                catch
 1538                {
 1539                    state.Dispose();
 1540                    throw;
 1541                }
 1542
 1543                // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false
 1544            }
 1545            else
 1546            {
 1547                job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1548                if (job?.TranscodingThrottler is not null)
 1549                {
 1550                    await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
 1551                }
 1552            }
 1553        }
 1554
 1555        _logger.LogDebug("returning {0} [general case]", segmentPath);
 1556        job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
 1557        return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationTo
 1558    }
 1559
 1560    private static double[] GetSegmentLengths(StreamState state)
 01561        => GetSegmentLengthsInternal(state.RunTimeTicks ?? 0, state.SegmentLength);
 1562
 1563    internal static double[] GetSegmentLengthsInternal(long runtimeTicks, int segmentlength)
 1564    {
 51565        var segmentLengthTicks = TimeSpan.FromSeconds(segmentlength).Ticks;
 51566        var wholeSegments = runtimeTicks / segmentLengthTicks;
 51567        var remainingTicks = runtimeTicks % segmentLengthTicks;
 1568
 51569        var segmentsLen = wholeSegments + (remainingTicks == 0 ? 0 : 1);
 51570        var segments = new double[segmentsLen];
 141571        for (int i = 0; i < wholeSegments; i++)
 1572        {
 21573            segments[i] = segmentlength;
 1574        }
 1575
 51576        if (remainingTicks != 0)
 1577        {
 31578            segments[^1] = TimeSpan.FromTicks(remainingTicks).TotalSeconds;
 1579        }
 1580
 51581        return segments;
 1582    }
 1583
 1584    private string GetCommandLineArguments(string outputPath, StreamState state, bool isEventPlaylist, int startNumber)
 1585    {
 01586        var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01587        var threads = EncodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
 1588
 01589        if (state.BaseRequest.BreakOnNonKeyFrames)
 1590        {
 1591            // FIXME: this is actually a workaround, as ideally it really should be the client which decides whether non
 1592            //        breakpoints are supported; but current implementation always uses "ffmpeg input seeking" which is 
 1593            //        to produce a missing part of video stream before first keyframe is encountered, which may lead to
 1594            //        awkward cases like a few starting HLS segments having no video whatsoever, which breaks hls.js
 01595            _logger.LogInformation("Current HLS implementation doesn't support non-keyframe breaks but one is requested,
 01596            state.BaseRequest.BreakOnNonKeyFrames = false;
 1597        }
 1598
 01599        var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
 1600
 01601        var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) 
 01602        var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
 01603        var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
 01604        var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
 01605        var outputTsArg = outputPrefix + "%d" + outputExtension;
 1606
 01607        var segmentFormat = string.Empty;
 01608        var segmentContainer = outputExtension.TrimStart('.');
 01609        var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions, segmentContainer);
 01610        var hlsArguments = $"-hls_playlist_type {(isEventPlaylist ? "event" : "vod")} -hls_list_size 0";
 1611
 01612        if (string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1613        {
 01614            segmentFormat = "mpegts";
 1615        }
 01616        else if (string.Equals(segmentContainer, "mp4", StringComparison.OrdinalIgnoreCase))
 1617        {
 01618            var outputFmp4HeaderArg = OperatingSystem.IsWindows() switch
 01619            {
 01620                // on Windows, the path of fmp4 header file needs to be configured
 01621                true => " -hls_fmp4_init_filename \"" + outputPrefix + "-1" + outputExtension + "\"",
 01622                // on Linux/Unix, ffmpeg generate fmp4 header file to m3u8 output folder
 01623                false => " -hls_fmp4_init_filename \"" + outputFileNameWithoutExtension + "-1" + outputExtension + "\""
 01624            };
 1625
 01626            var useLegacySegmentOption = _mediaEncoder.EncoderVersion < _minFFmpegHlsSegmentOptions;
 1627
 01628            if (state.VideoStream is not null && state.IsOutputVideo)
 1629            {
 1630                // fMP4 needs this flag to write the audio packet DTS/PTS including the initial delay into MOOF::TRAF::T
 01631                hlsArguments += $" {(useLegacySegmentOption ? "-hls_ts_options" : "-hls_segment_options")} movflags=+fra
 1632            }
 1633
 01634            segmentFormat = "fmp4" + outputFmp4HeaderArg;
 1635        }
 1636        else
 1637        {
 01638            _logger.LogError("Invalid HLS segment container: {SegmentContainer}, default to mpegts", segmentContainer);
 01639            segmentFormat = "mpegts";
 1640        }
 1641
 01642        var maxMuxingQueueSize = _encodingOptions.MaxMuxingQueueSize > 128
 01643            ? _encodingOptions.MaxMuxingQueueSize.ToString(CultureInfo.InvariantCulture)
 01644            : "128";
 1645
 01646        var baseUrlParam = string.Empty;
 01647        if (isEventPlaylist)
 1648        {
 01649            baseUrlParam = string.Format(
 01650                CultureInfo.InvariantCulture,
 01651                " -hls_base_url \"hls/{0}/\"",
 01652                Path.GetFileNameWithoutExtension(outputPath));
 1653        }
 1654
 01655        return string.Format(
 01656            CultureInfo.InvariantCulture,
 01657            "{0} {1} -map_metadata -1 -map_chapters -1 -threads {2} {3} {4} {5} -copyts -avoid_negative_ts disabled -max
 01658            inputModifier,
 01659            _encodingHelper.GetInputArgument(state, _encodingOptions, segmentContainer),
 01660            threads,
 01661            mapArgs,
 01662            GetVideoArguments(state, startNumber, isEventPlaylist, segmentContainer),
 01663            GetAudioArguments(state),
 01664            maxMuxingQueueSize,
 01665            state.SegmentLength.ToString(CultureInfo.InvariantCulture),
 01666            segmentFormat,
 01667            startNumber.ToString(CultureInfo.InvariantCulture),
 01668            baseUrlParam,
 01669            EncodingUtils.NormalizePath(outputTsArg),
 01670            hlsArguments,
 01671            EncodingUtils.NormalizePath(outputPath)).Trim();
 1672    }
 1673
 1674    /// <summary>
 1675    /// Gets the audio arguments for transcoding.
 1676    /// </summary>
 1677    /// <param name="state">The <see cref="StreamState"/>.</param>
 1678    /// <returns>The command line arguments for audio transcoding.</returns>
 1679    private string GetAudioArguments(StreamState state)
 1680    {
 01681        if (state.AudioStream is null)
 1682        {
 01683            return string.Empty;
 1684        }
 1685
 01686        var audioCodec = _encodingHelper.GetAudioEncoder(state);
 01687        var bitStreamArgs = _encodingHelper.GetAudioBitStreamArguments(state, state.Request.SegmentContainer, state.Medi
 1688
 1689        // opus, dts, truehd and flac (in FFmpeg 5 and older) are experimental in mp4 muxer
 01690        var strictArgs = string.Empty;
 01691        var actualOutputAudioCodec = state.ActualOutputAudioCodec;
 01692        if (string.Equals(actualOutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase)
 01693            || string.Equals(actualOutputAudioCodec, "dts", StringComparison.OrdinalIgnoreCase)
 01694            || string.Equals(actualOutputAudioCodec, "truehd", StringComparison.OrdinalIgnoreCase)
 01695            || (string.Equals(actualOutputAudioCodec, "flac", StringComparison.OrdinalIgnoreCase)
 01696                && _mediaEncoder.EncoderVersion < _minFFmpegFlacInMp4))
 1697        {
 01698            strictArgs = " -strict -2";
 1699        }
 1700
 01701        if (!state.IsOutputVideo)
 1702        {
 01703            var audioTranscodeParams = string.Empty;
 1704
 1705            // -vn to drop any video streams
 01706            audioTranscodeParams += "-vn";
 1707
 01708            if (EncodingHelper.IsCopyCodec(audioCodec))
 1709            {
 01710                return audioTranscodeParams + " -acodec copy" + bitStreamArgs + strictArgs;
 1711            }
 1712
 01713            audioTranscodeParams += " -acodec " + audioCodec + bitStreamArgs + strictArgs;
 1714
 01715            var audioBitrate = state.OutputAudioBitrate;
 01716            var audioChannels = state.OutputAudioChannels;
 1717
 01718            if (audioBitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(state.ActualOutputAudioCodec, Stri
 1719            {
 01720                var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, audioBitrate.Value, audioChannels ?? 2);
 01721                if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1722                {
 01723                    audioTranscodeParams += vbrParam;
 1724                }
 1725                else
 1726                {
 01727                    audioTranscodeParams += " -ab " + audioBitrate.Value.ToString(CultureInfo.InvariantCulture);
 1728                }
 1729            }
 1730
 01731            if (audioChannels.HasValue)
 1732            {
 01733                audioTranscodeParams += " -ac " + audioChannels.Value.ToString(CultureInfo.InvariantCulture);
 1734            }
 1735
 01736            if (state.OutputAudioSampleRate.HasValue)
 1737            {
 01738                audioTranscodeParams += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCultur
 1739            }
 1740
 01741            return audioTranscodeParams;
 1742        }
 1743
 01744        if (EncodingHelper.IsCopyCodec(audioCodec))
 1745        {
 01746            var videoCodec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 01747            var copyArgs = "-codec:a:0 copy" + bitStreamArgs + strictArgs;
 1748
 01749            if (EncodingHelper.IsCopyCodec(videoCodec) && state.EnableBreakOnNonKeyFrames(videoCodec))
 1750            {
 01751                return copyArgs + " -copypriorss:a:0 0";
 1752            }
 1753
 01754            return copyArgs;
 1755        }
 1756
 01757        var args = "-codec:a:0 " + audioCodec + bitStreamArgs + strictArgs;
 1758
 01759        var channels = state.OutputAudioChannels;
 1760
 01761        var useDownMixAlgorithm = DownMixAlgorithmsHelper.AlgorithmFilterStrings.ContainsKey((_encodingOptions.DownMixSt
 1762
 01763        if (channels.HasValue
 01764            && (channels.Value != 2
 01765                || (state.AudioStream?.Channels is not null && !useDownMixAlgorithm)))
 1766        {
 01767            args += " -ac " + channels.Value;
 1768        }
 1769
 01770        var bitrate = state.OutputAudioBitrate;
 01771        if (bitrate.HasValue && !EncodingHelper.LosslessAudioCodecs.Contains(actualOutputAudioCodec, StringComparison.Or
 1772        {
 01773            var vbrParam = _encodingHelper.GetAudioVbrModeParam(audioCodec, bitrate.Value, channels ?? 2);
 01774            if (_encodingOptions.EnableAudioVbr && state.EnableAudioVbrEncoding && vbrParam is not null)
 1775            {
 01776                args += vbrParam;
 1777            }
 1778            else
 1779            {
 01780                args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
 1781            }
 1782        }
 1783
 01784        if (state.OutputAudioSampleRate.HasValue)
 1785        {
 01786            args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
 1787        }
 01788        else if (state.AudioStream?.CodecTag is not null && state.AudioStream.CodecTag.Equals("ac-4", StringComparison.O
 1789        {
 1790            // ac-4 audio tends to have a super weird sample rate that will fail most encoders
 1791            // force resample it to 48KHz
 01792            args += " -ar 48000";
 1793        }
 1794
 01795        args += _encodingHelper.GetAudioFilterParam(state, _encodingOptions);
 1796
 01797        return args;
 1798    }
 1799
 1800    /// <summary>
 1801    /// Gets the video arguments for transcoding.
 1802    /// </summary>
 1803    /// <param name="state">The <see cref="StreamState"/>.</param>
 1804    /// <param name="startNumber">The first number in the hls sequence.</param>
 1805    /// <param name="isEventPlaylist">Whether the playlist is EVENT or VOD.</param>
 1806    /// <param name="segmentContainer">The segment container.</param>
 1807    /// <returns>The command line arguments for video transcoding.</returns>
 1808    private string GetVideoArguments(StreamState state, int startNumber, bool isEventPlaylist, string segmentContainer)
 1809    {
 01810        if (state.VideoStream is null)
 1811        {
 01812            return string.Empty;
 1813        }
 1814
 01815        if (!state.IsOutputVideo)
 1816        {
 01817            return string.Empty;
 1818        }
 1819
 01820        var codec = _encodingHelper.GetVideoEncoder(state, _encodingOptions);
 1821
 01822        var args = "-codec:v:0 " + codec;
 1823
 01824        var isActualOutputVideoCodecAv1 = string.Equals(state.ActualOutputVideoCodec, "av1", StringComparison.OrdinalIgn
 01825        var isActualOutputVideoCodecHevc = string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalI
 01826                                           || string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.Ordin
 1827
 01828        if (isActualOutputVideoCodecHevc || isActualOutputVideoCodecAv1)
 1829        {
 01830            var requestedRange = state.GetRequestedRangeTypes(state.ActualOutputVideoCodec);
 1831            // Clients reporting Dolby Vision capabilities with fallbacks may only support the fallback layer.
 1832            // Only enable Dolby Vision remuxing if the client explicitly declares support for profiles without fallback
 01833            var clientSupportsDoVi = requestedRange.Contains(VideoRangeType.DOVI.ToString(), StringComparison.OrdinalIgn
 01834            var videoIsDoVi = EncodingHelper.IsDovi(state.VideoStream);
 1835
 01836            if (EncodingHelper.IsCopyCodec(codec)
 01837                && (videoIsDoVi && clientSupportsDoVi)
 01838                && !_encodingHelper.IsDoviRemoved(state))
 1839            {
 01840                if (isActualOutputVideoCodecHevc)
 1841                {
 1842                    // Prefer dvh1 to dvhe
 01843                    args += " -tag:v:0 dvh1 -strict -2";
 1844                }
 01845                else if (isActualOutputVideoCodecAv1)
 1846                {
 01847                    args += " -tag:v:0 dav1 -strict -2";
 1848                }
 1849            }
 01850            else if (isActualOutputVideoCodecHevc)
 1851            {
 1852                // Prefer hvc1 to hev1
 01853                args += " -tag:v:0 hvc1";
 1854            }
 1855        }
 1856
 1857        // if  (state.EnableMpegtsM2TsMode)
 1858        // {
 1859        //     args += " -mpegts_m2ts_mode 1";
 1860        // }
 1861
 1862        // See if we can save come cpu cycles by avoiding encoding.
 01863        if (EncodingHelper.IsCopyCodec(codec))
 1864        {
 1865            // If h264_mp4toannexb is ever added, do not use it for live tv.
 01866            if (state.VideoStream is not null && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.O
 1867            {
 01868                string bitStreamArgs = _encodingHelper.GetBitStreamArgs(state, MediaStreamType.Video);
 01869                if (!string.IsNullOrEmpty(bitStreamArgs))
 1870                {
 01871                    args += " " + bitStreamArgs;
 1872                }
 1873            }
 1874
 01875            args += " -start_at_zero";
 1876        }
 1877        else
 1878        {
 01879            args += _encodingHelper.GetVideoQualityParam(state, codec, _encodingOptions, isEventPlaylist ? DefaultEventE
 1880
 1881            // Set the key frame params for video encoding to match the hls segment time.
 01882            args += _encodingHelper.GetHlsVideoKeyFrameArguments(state, codec, state.SegmentLength, isEventPlaylist, sta
 1883
 1884            // Currently b-frames in libx265 breaks the FMP4-HLS playback on iOS, disable it for now.
 01885            if (string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
 01886                && _mediaEncoder.EncoderVersion < _minFFmpegX265BframeInFmp4)
 1887            {
 01888                args += " -bf 0";
 1889            }
 1890
 1891            // video processing filters.
 01892            var videoProcessParam = _encodingHelper.GetVideoProcessingFilterParam(state, _encodingOptions, codec);
 1893
 01894            var negativeMapArgs = _encodingHelper.GetNegativeMapArgsByFilters(state, videoProcessParam);
 1895
 01896            args = negativeMapArgs + args + videoProcessParam;
 1897
 1898            // -start_at_zero is necessary to use with -ss when seeking,
 1899            // otherwise the target position cannot be determined.
 01900            if (state.SubtitleStream is not null)
 1901            {
 1902                // Disable start_at_zero for external graphical subs
 01903                if (!(state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
 1904                {
 01905                    args += " -start_at_zero";
 1906                }
 1907            }
 1908        }
 1909
 1910        // TODO why was this not enabled for VOD?
 01911        if (isEventPlaylist && string.Equals(segmentContainer, "ts", StringComparison.OrdinalIgnoreCase))
 1912        {
 01913            args += " -flags -global_header";
 1914        }
 1915
 01916        if (!string.IsNullOrEmpty(state.OutputVideoSync))
 1917        {
 01918            args += EncodingHelper.GetVideoSyncOption(state.OutputVideoSync, _mediaEncoder.EncoderVersion);
 1919        }
 1920
 01921        args += _encodingHelper.GetOutputFFlags(state);
 1922
 01923        return args;
 1924    }
 1925
 1926    private string GetSegmentPath(StreamState state, string playlist, int index)
 1927    {
 01928        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException($"Provided path ({playlist}) is not 
 01929        var filename = Path.GetFileNameWithoutExtension(playlist);
 1930
 01931        return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + EncodingHelper.GetSegmentF
 1932    }
 1933
 1934    private async Task<ActionResult> GetSegmentResult(
 1935        StreamState state,
 1936        string playlistPath,
 1937        string segmentPath,
 1938        string segmentExtension,
 1939        int segmentIndex,
 1940        TranscodingJob? transcodingJob,
 1941        CancellationToken cancellationToken)
 1942    {
 1943        var segmentExists = System.IO.File.Exists(segmentPath);
 1944        if (segmentExists)
 1945        {
 1946            if (transcodingJob is not null && transcodingJob.HasExited)
 1947            {
 1948                // Transcoding job is over, so assume all existing files are ready
 1949                _logger.LogDebug("serving up {0} as transcode is over", segmentPath);
 1950                return GetSegmentResult(state, segmentPath, transcodingJob);
 1951            }
 1952
 1953            var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
 1954
 1955            // If requested segment is less than transcoding position, we can't transcode backwards, so assume it's read
 1956            if (segmentIndex < currentTranscodingIndex)
 1957            {
 1958                _logger.LogDebug("serving up {0} as transcode index {1} is past requested point {2}", segmentPath, curre
 1959                return GetSegmentResult(state, segmentPath, transcodingJob);
 1960            }
 1961        }
 1962
 1963        var nextSegmentPath = GetSegmentPath(state, playlistPath, segmentIndex + 1);
 1964        if (transcodingJob is not null)
 1965        {
 1966            while (!cancellationToken.IsCancellationRequested && !transcodingJob.HasExited)
 1967            {
 1968                // To be considered ready, the segment file has to exist AND
 1969                // either the transcoding job should be done or next segment should also exist
 1970                if (segmentExists)
 1971                {
 1972                    if (transcodingJob.HasExited || System.IO.File.Exists(nextSegmentPath))
 1973                    {
 1974                        _logger.LogDebug("Serving up {SegmentPath} as it deemed ready", segmentPath);
 1975                        return GetSegmentResult(state, segmentPath, transcodingJob);
 1976                    }
 1977                }
 1978                else
 1979                {
 1980                    segmentExists = System.IO.File.Exists(segmentPath);
 1981                    if (segmentExists)
 1982                    {
 1983                        continue; // avoid unnecessary waiting if segment just became available
 1984                    }
 1985                }
 1986
 1987                await Task.Delay(100, cancellationToken).ConfigureAwait(false);
 1988            }
 1989
 1990            if (!System.IO.File.Exists(segmentPath))
 1991            {
 1992                _logger.LogWarning("cannot serve {0} as transcoding quit before we got there", segmentPath);
 1993            }
 1994            else
 1995            {
 1996                _logger.LogDebug("serving {0} as it's on disk and transcoding stopped", segmentPath);
 1997            }
 1998
 1999            cancellationToken.ThrowIfCancellationRequested();
 2000        }
 2001        else
 2002        {
 2003            _logger.LogWarning("cannot serve {0} as it doesn't exist and no transcode is running", segmentPath);
 2004        }
 2005
 2006        return GetSegmentResult(state, segmentPath, transcodingJob);
 2007    }
 2008
 2009    private ActionResult GetSegmentResult(StreamState state, string segmentPath, TranscodingJob? transcodingJob)
 2010    {
 02011        var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks;
 2012
 02013        Response.OnCompleted(() =>
 02014        {
 02015            _logger.LogDebug("Finished serving {SegmentPath}", segmentPath);
 02016            if (transcodingJob is not null)
 02017            {
 02018                transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPos
 02019                _transcodeManager.OnTranscodeEndRequest(transcodingJob);
 02020            }
 02021
 02022            return Task.CompletedTask;
 02023        });
 2024
 02025        return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
 2026    }
 2027
 2028    private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
 2029    {
 02030        var job = _transcodeManager.GetTranscodingJob(playlist, TranscodingJobType);
 2031
 02032        if (job is null || job.HasExited)
 2033        {
 02034            return null;
 2035        }
 2036
 02037        var file = GetLastTranscodingFile(playlist, segmentExtension, _fileSystem);
 2038
 02039        if (file is null)
 2040        {
 02041            return null;
 2042        }
 2043
 02044        var playlistFilename = Path.GetFileNameWithoutExtension(playlist.AsSpan());
 2045
 02046        var indexString = Path.GetFileNameWithoutExtension(file.Name.AsSpan()).Slice(playlistFilename.Length);
 2047
 02048        return int.Parse(indexString, NumberStyles.Integer, CultureInfo.InvariantCulture);
 2049    }
 2050
 2051    private static FileSystemMetadata? GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem file
 2052    {
 02053        var folder = Path.GetDirectoryName(playlist) ?? throw new ArgumentException("Path can't be a root directory.", n
 2054
 02055        var filePrefix = Path.GetFileNameWithoutExtension(playlist);
 2056
 2057        try
 2058        {
 02059            return fileSystem.GetFiles(folder, new[] { segmentExtension }, true, false)
 02060                .Where(i => Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgno
 02061                .MaxBy(fileSystem.GetLastWriteTimeUtc);
 2062        }
 02063        catch (IOException)
 2064        {
 02065            return null;
 2066        }
 02067    }
 2068
 2069    private async Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
 2070    {
 2071        var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
 2072
 2073        if (file is null)
 2074        {
 2075            return;
 2076        }
 2077
 2078        await DeleteFile(file.FullName, retryCount).ConfigureAwait(false);
 2079    }
 2080
 2081    private async Task DeleteFile(string path, int retryCount)
 2082    {
 2083        if (retryCount >= 5)
 2084        {
 2085            return;
 2086        }
 2087
 2088        _logger.LogDebug("Deleting partial HLS file {Path}", path);
 2089
 2090        try
 2091        {
 2092            _fileSystem.DeleteFile(path);
 2093        }
 2094        catch (IOException ex)
 2095        {
 2096            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 2097
 2098            await Task.Delay(100).ConfigureAwait(false);
 2099            await DeleteFile(path, retryCount + 1).ConfigureAwait(false);
 2100        }
 2101        catch (Exception ex)
 2102        {
 2103            _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
 2104        }
 2105    }
 2106}