< 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: 223
Coverable lines: 233
Total lines: 2084
Line coverage: 4.2%
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

Metrics

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