< Summary - Jellyfin

Information
Class: MediaBrowser.Model.Dlna.StreamBuilder
Assembly: MediaBrowser.Model
File(s): /srv/git/jellyfin/MediaBrowser.Model/Dlna/StreamBuilder.cs
Line coverage
70%
Covered lines: 773
Uncovered lines: 324
Coverable lines: 1097
Total lines: 2493
Line coverage: 70.4%
Branch coverage
61%
Covered branches: 616
Total branches: 1000
Branch coverage: 61.6%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 69.6% (749/1075) Branch coverage: 59.7% (576/964) Total lines: 24496/1/2026 - 12:16:05 AM Line coverage: 69.9% (759/1085) Branch coverage: 59.3% (583/982) Total lines: 24616/18/2026 - 12:16:24 AM Line coverage: 70% (763/1089) Branch coverage: 59.6% (591/990) Total lines: 24697/23/2026 - 12:16:48 AM Line coverage: 70.1% (765/1091) Branch coverage: 60.7% (604/994) Total lines: 24798/3/2026 - 12:16:46 AM Line coverage: 70.2% (769/1095) Branch coverage: 60.9% (608/998) Total lines: 248310/29/2026 - 12:17:11 AM Line coverage: 70.4% (773/1097) Branch coverage: 61.6% (616/1000) Total lines: 2493 5/31/2026 - 12:15:44 AM Line coverage: 69.6% (749/1075) Branch coverage: 59.7% (576/964) Total lines: 24496/1/2026 - 12:16:05 AM Line coverage: 69.9% (759/1085) Branch coverage: 59.3% (583/982) Total lines: 24616/18/2026 - 12:16:24 AM Line coverage: 70% (763/1089) Branch coverage: 59.6% (591/990) Total lines: 24697/23/2026 - 12:16:48 AM Line coverage: 70.1% (765/1091) Branch coverage: 60.7% (604/994) Total lines: 24798/3/2026 - 12:16:46 AM Line coverage: 70.2% (769/1095) Branch coverage: 60.9% (608/998) Total lines: 248310/29/2026 - 12:17:11 AM Line coverage: 70.4% (773/1097) Branch coverage: 61.6% (616/1000) Total lines: 2493

Coverage delta

Coverage delta 2 -2

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%11100%
.ctor(...)100%11100%
GetOptimalAudioStream(...)0%110100%
GetOptimalAudioStream(...)0%4692680%
GetOptimalVideoStream(...)80%1010100%
GetOptimalStream(...)100%11100%
SortMediaSources(...)100%11100%
GetTranscodeReasonForFailedCondition(...)32.14%2362835.71%
NormalizeMediaSourceFormatIntoSingleContainer(...)87.5%1616100%
GetAudioDirectPlayProfile(...)0%600240%
GetTranscodeReasonsFromDirectPlayProfile(...)0%420200%
GetDefaultSubtitleStreamIndex(...)93.33%313089.47%
SetStreamInfoOptionsFromTranscodingProfile(...)75%8895%
SetStreamInfoOptionsFromDirectPlayProfile(...)0%620%
BuildVideoItem(...)60.52%14211487.15%
GetVideoTranscodeProfile(...)70%101096.96%
BuildStreamVideoItem(...)90.44%13613697.36%
GetDefaultAudioBitrate(...)63.63%272278.57%
GetAudioBitrate(...)84.37%323295.83%
GetMaxAudioBitrateForTotalBitrate(...)68.75%231670.58%
GetVideoDirectPlayProfile(...)54.54%222296.11%
AggregateFailureConditions(...)100%11100%
LogConditionFailure(...)66.66%66100%
GetSubtitleProfile(...)78.94%473881.81%
IsSubtitleEmbedSupported(...)100%66100%
CanConsiderEmbedSubtitle(...)100%88100%
GetExternalSubtitleProfile(...)93.75%4848100%
IsVobSubMksDeliveryProfile(...)100%44100%
IsVobSubMksProfile(...)87.5%88100%
IsBitrateLimitExceeded(...)83.33%66100%
ValidateMediaOptions(...)68.75%351658.33%
GetProfileConditionsForVideoAudio(...)100%11100%
GetProfileConditionsForAudio(...)0%620%
ApplyTranscodingConditions(...)61.63%927523244.82%
IsAudioContainerSupported(...)0%2040%
IsAudioDirectPlaySupported(...)0%4260%
IsAudioDirectStreamSupported(...)0%4260%
GetRank(...)100%44100%
CheckVideoConditions(...)50%3232100%
GetCompatibilityContainer(...)100%11100%
GetCompatibilityVideoCodec(...)100%11100%
GetCompatibilityAudioCodec(...)75%44100%
GetCompatibilityAudioCodecDirect(...)100%22100%

File(s)

/srv/git/jellyfin/MediaBrowser.Model/Dlna/StreamBuilder.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.Linq;
 5using Jellyfin.Data.Enums;
 6using Jellyfin.Extensions;
 7using MediaBrowser.Model.Dto;
 8using MediaBrowser.Model.Entities;
 9using MediaBrowser.Model.Extensions;
 10using MediaBrowser.Model.MediaInfo;
 11using MediaBrowser.Model.Session;
 12using Microsoft.Extensions.Logging;
 13
 14namespace MediaBrowser.Model.Dlna
 15{
 16    /// <summary>
 17    /// Class StreamBuilder.
 18    /// </summary>
 19    public class StreamBuilder
 20    {
 21        // Aliases
 22        internal const TranscodeReason ContainerReasons = TranscodeReason.ContainerNotSupported | TranscodeReason.Contai
 23        internal const TranscodeReason AudioCodecReasons = TranscodeReason.AudioBitrateNotSupported | TranscodeReason.Au
 24        internal const TranscodeReason AudioReasons = TranscodeReason.AudioCodecNotSupported | AudioCodecReasons;
 25        internal const TranscodeReason VideoCodecReasons = TranscodeReason.VideoResolutionNotSupported | TranscodeReason
 26        internal const TranscodeReason VideoReasons = TranscodeReason.VideoCodecNotSupported | VideoCodecReasons;
 27        internal const TranscodeReason DirectStreamReasons = AudioReasons | TranscodeReason.ContainerNotSupported | Tran
 28
 29        private const string ManifestContainers = "hls,applehttp,dash";
 30
 31        private readonly ILogger _logger;
 32        private readonly ITranscoderSupport _transcoderSupport;
 133        private static readonly string[] _supportedHlsVideoCodecs = ["h264", "hevc", "vp9", "av1"];
 134        private static readonly string[] _supportedHlsAudioCodecsTs = ["aac", "ac3", "eac3", "mp3"];
 135        private static readonly string[] _supportedHlsAudioCodecsMp4 = ["aac", "ac3", "eac3", "mp3", "alac", "flac", "op
 36
 37        /// <summary>
 38        /// Initializes a new instance of the <see cref="StreamBuilder"/> class.
 39        /// </summary>
 40        /// <param name="transcoderSupport">The <see cref="ITranscoderSupport"/> object.</param>
 41        /// <param name="logger">The <see cref="ILogger"/> object.</param>
 42        public StreamBuilder(ITranscoderSupport transcoderSupport, ILogger logger)
 43        {
 28744            _transcoderSupport = transcoderSupport;
 28745            _logger = logger;
 28746        }
 47
 48        /// <summary>
 49        /// Gets the optimal audio stream.
 50        /// </summary>
 51        /// <param name="options">The <see cref="MediaOptions"/> object to get the audio stream from.</param>
 52        /// <returns>The <see cref="StreamInfo"/> of the optimal audio stream.</returns>
 53        public StreamInfo? GetOptimalAudioStream(MediaOptions options)
 54        {
 055            ValidateMediaOptions(options, false);
 56
 057            List<StreamInfo> streams = [];
 058            foreach (var mediaSource in options.MediaSources)
 59            {
 060                if (!(string.IsNullOrEmpty(options.MediaSourceId)
 061                    || string.Equals(mediaSource.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase)))
 62                {
 63                    continue;
 64                }
 65
 066                StreamInfo? streamInfo = GetOptimalAudioStream(mediaSource, options);
 067                if (streamInfo is not null)
 68                {
 069                    streamInfo.DeviceId = options.DeviceId;
 070                    streamInfo.DeviceProfileId = options.Profile.Id?.ToString("N", CultureInfo.InvariantCulture);
 071                    streams.Add(streamInfo);
 72                }
 73            }
 74
 075            return GetOptimalStream(streams, options.GetMaxBitrate(true) ?? 0);
 76        }
 77
 78        private StreamInfo? GetOptimalAudioStream(MediaSourceInfo item, MediaOptions options)
 79        {
 080            var playlistItem = new StreamInfo
 081            {
 082                ItemId = options.ItemId,
 083                MediaType = DlnaProfileType.Audio,
 084                MediaSource = item,
 085                RunTimeTicks = item.RunTimeTicks,
 086                Context = options.Context,
 087                DeviceProfile = options.Profile
 088            };
 89
 090            if (options.ForceDirectPlay)
 91            {
 092                playlistItem.PlayMethod = PlayMethod.DirectPlay;
 093                playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, 
 094                return playlistItem;
 95            }
 96
 097            if (options.ForceDirectStream)
 98            {
 099                playlistItem.PlayMethod = PlayMethod.DirectStream;
 0100                playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, 
 0101                return playlistItem;
 102            }
 103
 0104            MediaStream audioStream = item.GetDefaultAudioStream(null);
 105
 0106            ArgumentNullException.ThrowIfNull(audioStream);
 107
 0108            var directPlayInfo = GetAudioDirectPlayProfile(item, audioStream, options);
 109
 0110            var directPlayMethod = directPlayInfo.PlayMethod;
 0111            var transcodeReasons = directPlayInfo.TranscodeReasons;
 112
 0113            if (directPlayMethod is PlayMethod.DirectPlay)
 114            {
 0115                var audioFailureReasons = GetCompatibilityAudioCodec(options, item, item.Container, audioStream, null, f
 0116                transcodeReasons |= audioFailureReasons;
 117
 0118                if (audioFailureReasons == 0)
 119                {
 0120                    playlistItem.PlayMethod = directPlayMethod.Value;
 0121                    playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profi
 122
 0123                    return playlistItem;
 124                }
 125            }
 126
 0127            if (directPlayMethod is PlayMethod.DirectStream)
 128            {
 0129                var remuxContainer = item.TranscodingContainer ?? "ts";
 0130                string[] supportedHlsContainers = ["ts", "mp4"];
 131                // If the container specified for the profile is an HLS supported container, use that container instead,
 132                // The client should be responsible to ensure this container is compatible
 0133                remuxContainer = Array.Exists(supportedHlsContainers, element => string.Equals(element, directPlayInfo.P
 134                bool codeIsSupported;
 0135                if (item.TranscodingSubProtocol == MediaStreamProtocol.hls)
 136                {
 137                    // Enforce HLS audio codec restrictions
 0138                    if (string.Equals(remuxContainer, "mp4", StringComparison.OrdinalIgnoreCase))
 139                    {
 0140                        codeIsSupported = _supportedHlsAudioCodecsMp4.Contains(directPlayInfo.Profile?.AudioCodec ?? dir
 141                    }
 142                    else
 143                    {
 0144                        codeIsSupported = _supportedHlsAudioCodecsTs.Contains(directPlayInfo.Profile?.AudioCodec ?? dire
 145                    }
 146                }
 147                else
 148                {
 149                    // Let's assume the client has given a correct container for http
 0150                    codeIsSupported = true;
 151                }
 152
 0153                if (codeIsSupported)
 154                {
 0155                    playlistItem.PlayMethod = directPlayMethod.Value;
 0156                    playlistItem.Container = remuxContainer;
 0157                    playlistItem.TranscodeReasons = transcodeReasons;
 0158                    playlistItem.SubProtocol = item.TranscodingSubProtocol;
 0159                    item.TranscodingContainer = remuxContainer;
 0160                    return playlistItem;
 161                }
 162
 0163                transcodeReasons |= TranscodeReason.AudioCodecNotSupported;
 0164                playlistItem.TranscodeReasons = transcodeReasons;
 165            }
 166
 0167            TranscodingProfile? transcodingProfile = null;
 0168            foreach (var tcProfile in options.Profile.TranscodingProfiles)
 169            {
 0170                if (tcProfile.Type == playlistItem.MediaType
 0171                    && tcProfile.Context == options.Context
 0172                    && _transcoderSupport.CanEncodeToAudioCodec(tcProfile.AudioCodec ?? tcProfile.Container))
 173                {
 0174                    transcodingProfile = tcProfile;
 0175                    break;
 176                }
 177            }
 178
 0179            if (transcodingProfile is not null)
 180            {
 0181                if (!item.SupportsTranscoding)
 182                {
 0183                    return null;
 184                }
 185
 0186                SetStreamInfoOptionsFromTranscodingProfile(item, playlistItem, transcodingProfile);
 187
 0188                var inputAudioChannels = audioStream.Channels;
 0189                var inputAudioBitrate = audioStream.BitRate;
 0190                var inputAudioSampleRate = audioStream.SampleRate;
 0191                var inputAudioBitDepth = audioStream.BitDepth;
 192
 0193                var audioTranscodingConditions = GetProfileConditionsForAudio(options.Profile.CodecProfiles, transcoding
 0194                ApplyTranscodingConditions(playlistItem, audioTranscodingConditions, null, true, true);
 195
 196                // Honor requested max channels
 0197                playlistItem.GlobalMaxAudioChannels = options.MaxAudioChannels;
 198
 0199                var configuredBitrate = options.GetMaxBitrate(true);
 200
 0201                long transcodingBitrate = options.AudioTranscodingBitrate
 0202                    ?? (options.Context == EncodingContext.Streaming ? options.Profile.MusicStreamingTranscodingBitrate 
 0203                    ?? configuredBitrate
 0204                    ?? 128000;
 205
 0206                if (configuredBitrate.HasValue)
 207                {
 0208                    transcodingBitrate = Math.Min(configuredBitrate.Value, transcodingBitrate);
 209                }
 210
 0211                var longBitrate = Math.Min(transcodingBitrate, playlistItem.AudioBitrate ?? transcodingBitrate);
 0212                playlistItem.AudioBitrate = longBitrate > int.MaxValue ? int.MaxValue : Convert.ToInt32(longBitrate);
 213
 214                // Pure audio transcoding does not support comma separated list of transcoding codec at the moment.
 215                // So just use the AudioCodec as is would be safe enough as the _transcoderSupport.CanEncodeToAudioCodec
 216                // would fail so this profile will not even be picked up.
 0217                if (playlistItem.AudioCodecs.Count == 0 && !string.IsNullOrWhiteSpace(transcodingProfile.AudioCodec))
 218                {
 0219                    playlistItem.AudioCodecs = [transcodingProfile.AudioCodec];
 220                }
 221            }
 222
 0223            playlistItem.TranscodeReasons = transcodeReasons;
 0224            return playlistItem;
 225        }
 226
 227        /// <summary>
 228        /// Gets the optimal video stream.
 229        /// </summary>
 230        /// <param name="options">The <see cref="MediaOptions"/> object to get the video stream from.</param>
 231        /// <returns>The <see cref="StreamInfo"/> of the optimal video stream.</returns>
 232        public StreamInfo? GetOptimalVideoStream(MediaOptions options)
 233        {
 287234            ValidateMediaOptions(options, true);
 235
 287236            var mediaSources = string.IsNullOrEmpty(options.MediaSourceId)
 287237                ? options.MediaSources
 287238                : options.MediaSources.Where(x => string.Equals(x.Id, options.MediaSourceId, StringComparison.OrdinalIgn
 239
 287240            List<StreamInfo> streams = [];
 1148241            foreach (var mediaSourceInfo in mediaSources)
 242            {
 287243                var streamInfo = BuildVideoItem(mediaSourceInfo, options);
 287244                if (streamInfo is not null)
 245                {
 287246                    streams.Add(streamInfo);
 247                }
 248            }
 249
 1148250            foreach (var stream in streams)
 251            {
 287252                stream.DeviceId = options.DeviceId;
 287253                stream.DeviceProfileId = options.Profile.Id?.ToString("N", CultureInfo.InvariantCulture);
 254            }
 255
 287256            return GetOptimalStream(streams, options.GetMaxBitrate(false) ?? 0);
 257        }
 258
 259        private static StreamInfo? GetOptimalStream(List<StreamInfo> streams, long maxBitrate)
 287260            => SortMediaSources(streams, maxBitrate).FirstOrDefault();
 261
 262        private static IOrderedEnumerable<StreamInfo> SortMediaSources(List<StreamInfo> streams, long maxBitrate)
 263        {
 287264            return streams.OrderBy(i =>
 287265            {
 287266                // Nothing beats direct playing a file
 287267                if (i.PlayMethod == PlayMethod.DirectPlay && i.MediaSource?.Protocol == MediaProtocol.File)
 287268                {
 287269                    return 0;
 287270                }
 287271
 287272                return 1;
 287273            }).ThenBy(i =>
 287274            {
 287275                switch (i.PlayMethod)
 287276                {
 287277                    // Let's assume direct streaming a file is just as desirable as direct playing a remote url
 287278                    case PlayMethod.DirectStream:
 287279                    case PlayMethod.DirectPlay:
 287280                        return 0;
 287281                    default:
 287282                        return 1;
 287283                }
 287284            }).ThenBy(i =>
 287285            {
 287286                switch (i.MediaSource?.Protocol)
 287287                {
 287288                    case MediaProtocol.File:
 287289                        return 0;
 287290                    default:
 287291                        return 1;
 287292                }
 287293            }).ThenBy(i =>
 287294            {
 287295                if (maxBitrate > 0)
 287296                {
 287297                    if (i.MediaSource?.Bitrate is not null)
 287298                    {
 287299                        return Math.Abs(i.MediaSource.Bitrate.Value - maxBitrate);
 287300                    }
 287301                }
 287302
 287303                return 0;
 287304            }).ThenBy(streams.IndexOf);
 305        }
 306
 307        private static TranscodeReason GetTranscodeReasonForFailedCondition(ProfileCondition condition)
 308        {
 252309            switch (condition.Property)
 310            {
 311                case ProfileConditionValue.AudioBitrate:
 0312                    return TranscodeReason.AudioBitrateNotSupported;
 313
 314                case ProfileConditionValue.AudioChannels:
 122315                    return TranscodeReason.AudioChannelsNotSupported;
 316
 317                case ProfileConditionValue.AudioProfile:
 0318                    return TranscodeReason.AudioProfileNotSupported;
 319
 320                case ProfileConditionValue.AudioSampleRate:
 0321                    return TranscodeReason.AudioSampleRateNotSupported;
 322
 323                case ProfileConditionValue.Has64BitOffsets:
 324                    // TODO
 0325                    return 0;
 326
 327                case ProfileConditionValue.Height:
 0328                    return TranscodeReason.VideoResolutionNotSupported;
 329
 330                case ProfileConditionValue.IsAnamorphic:
 0331                    return TranscodeReason.AnamorphicVideoNotSupported;
 332
 333                case ProfileConditionValue.IsAvc:
 334                    // TODO
 0335                    return 0;
 336
 337                case ProfileConditionValue.IsInterlaced:
 0338                    return TranscodeReason.InterlacedVideoNotSupported;
 339
 340                case ProfileConditionValue.IsSecondaryAudio:
 39341                    return TranscodeReason.SecondaryAudioNotSupported;
 342
 343                case ProfileConditionValue.NumStreams:
 2344                    return TranscodeReason.StreamCountExceedsLimit;
 345
 346                case ProfileConditionValue.NumAudioStreams:
 347                    // TODO
 0348                    return 0;
 349
 350                case ProfileConditionValue.NumVideoStreams:
 351                    // TODO
 0352                    return 0;
 353
 354                case ProfileConditionValue.PacketLength:
 355                    // TODO
 0356                    return 0;
 357
 358                case ProfileConditionValue.RefFrames:
 0359                    return TranscodeReason.RefFramesNotSupported;
 360
 361                case ProfileConditionValue.VideoBitDepth:
 0362                    return TranscodeReason.VideoBitDepthNotSupported;
 363
 364                case ProfileConditionValue.AudioBitDepth:
 0365                    return TranscodeReason.AudioBitDepthNotSupported;
 366
 367                case ProfileConditionValue.VideoBitrate:
 4368                    return TranscodeReason.VideoBitrateNotSupported;
 369
 370                case ProfileConditionValue.VideoCodecTag:
 18371                    return TranscodeReason.VideoCodecTagNotSupported;
 372
 373                case ProfileConditionValue.VideoFramerate:
 0374                    return TranscodeReason.VideoFramerateNotSupported;
 375
 376                case ProfileConditionValue.VideoLevel:
 13377                    return TranscodeReason.VideoLevelNotSupported;
 378
 379                case ProfileConditionValue.VideoProfile:
 25380                    return TranscodeReason.VideoProfileNotSupported;
 381
 382                case ProfileConditionValue.VideoRangeType:
 28383                    return TranscodeReason.VideoRangeTypeNotSupported;
 384
 385                case ProfileConditionValue.VideoRotation:
 1386                    return TranscodeReason.VideoRotationNotSupported;
 387
 388                case ProfileConditionValue.VideoTimestamp:
 389                    // TODO
 0390                    return 0;
 391
 392                case ProfileConditionValue.Width:
 0393                    return TranscodeReason.VideoResolutionNotSupported;
 394
 395                default:
 0396                    return 0;
 397            }
 398        }
 399
 400        /// <summary>
 401        /// Normalizes input container.
 402        /// </summary>
 403        /// <param name="inputContainer">The input container.</param>
 404        /// <param name="profile">The <see cref="DeviceProfile"/>.</param>
 405        /// <param name="type">The <see cref="DlnaProfileType"/>.</param>
 406        /// <param name="playProfile">The <see cref="DirectPlayProfile"/> object to get the video stream from.</param>
 407        /// <returns>The normalized input container.</returns>
 408        public static string? NormalizeMediaSourceFormatIntoSingleContainer(string inputContainer, DeviceProfile? profil
 409        {
 410            // If the source is Live TV the inputContainer will be null until the mediasource is probed on first access
 424411            if (profile is null || string.IsNullOrEmpty(inputContainer) || !inputContainer.Contains(',', StringCompariso
 412            {
 110413                return inputContainer;
 414            }
 415
 314416            var formats = ContainerHelper.Split(inputContainer);
 314417            var playProfiles = playProfile is null ? profile.DirectPlayProfiles : [playProfile];
 1379418            foreach (var format in formats)
 419            {
 2619420                foreach (var directPlayProfile in playProfiles)
 421                {
 934422                    if (directPlayProfile.Type != type)
 423                    {
 424                        continue;
 425                    }
 426
 706427                    if (directPlayProfile.SupportsContainer(format))
 428                    {
 297429                        return format;
 430                    }
 431                }
 432            }
 433
 17434            return inputContainer;
 435        }
 436
 437        private (DirectPlayProfile? Profile, PlayMethod? PlayMethod, TranscodeReason TranscodeReasons) GetAudioDirectPla
 438        {
 0439            var directPlayProfile = options.Profile.DirectPlayProfiles
 0440                .FirstOrDefault(x => x.Type == DlnaProfileType.Audio && IsAudioDirectPlaySupported(x, item, audioStream)
 441
 0442            TranscodeReason transcodeReasons = 0;
 0443            if (directPlayProfile is null)
 444            {
 0445                _logger.LogDebug(
 0446                    "Profile: {0}, No audio direct play profiles found for {1} with codec {2}",
 0447                    options.Profile.Name ?? "Unknown Profile",
 0448                    item.Path ?? "Unknown path",
 0449                    audioStream.Codec ?? "Unknown codec");
 450
 0451                var directStreamProfile = options.Profile.DirectPlayProfiles
 0452                    .FirstOrDefault(x => x.Type == DlnaProfileType.Audio && IsAudioDirectStreamSupported(x, item, audioS
 453
 0454                if (directStreamProfile is not null)
 455                {
 0456                    directPlayProfile = directStreamProfile;
 0457                    transcodeReasons |= TranscodeReason.ContainerNotSupported;
 458                }
 459                else
 460                {
 0461                    return (null, null, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profil
 462                }
 463            }
 464
 465            // The profile describes what the device supports
 466            // If device requirements are satisfied then allow both direct stream and direct play
 467            // Note: As of 10.10 codebase, SupportsDirectPlay is always true because the MediaSourceInfo initializes thi
 468            // Need to check additionally for current transcode reasons
 0469            if (item.SupportsDirectPlay && transcodeReasons == 0)
 470            {
 0471                if (!IsBitrateLimitExceeded(item, options.GetMaxBitrate(true) ?? 0))
 472                {
 0473                    if (options.EnableDirectPlay)
 474                    {
 0475                        return (directPlayProfile, PlayMethod.DirectPlay, 0);
 476                    }
 477                }
 478                else
 479                {
 0480                    transcodeReasons |= TranscodeReason.ContainerBitrateExceedsLimit;
 481                }
 482            }
 483
 484            // While options takes the network and other factors into account. Only applies to direct stream
 0485            if (item.SupportsDirectStream)
 486            {
 0487                if (!IsBitrateLimitExceeded(item, options.GetMaxBitrate(true) ?? 0))
 488                {
 489                    // Note: as of 10.10 codebase, the options.EnableDirectStream is always false due to
 490                    // "direct-stream http streaming is currently broken"
 491                    // Don't check that option for audio as we always assume that is supported
 0492                    if (transcodeReasons == TranscodeReason.ContainerNotSupported)
 493                    {
 0494                        return (directPlayProfile, PlayMethod.DirectStream, transcodeReasons);
 495                    }
 496                }
 497                else
 498                {
 0499                    transcodeReasons |= TranscodeReason.ContainerBitrateExceedsLimit;
 500                }
 501            }
 502
 0503            return (directPlayProfile, null, transcodeReasons);
 504        }
 505
 506        private static TranscodeReason GetTranscodeReasonsFromDirectPlayProfile(MediaSourceInfo item, MediaStream? video
 507        {
 0508            var mediaType = videoStream is null ? DlnaProfileType.Audio : DlnaProfileType.Video;
 509
 0510            var containerSupported = false;
 0511            var audioSupported = false;
 0512            var videoSupported = false;
 513
 0514            foreach (var profile in directPlayProfiles)
 515            {
 516                // Check container type
 0517                if (profile.Type == mediaType && profile.SupportsContainer(item.Container))
 518                {
 0519                    containerSupported = true;
 520
 0521                    videoSupported = videoStream is null || profile.SupportsVideoCodec(videoStream.Codec);
 522
 0523                    audioSupported = audioStream is null || profile.SupportsAudioCodec(audioStream.Codec);
 524
 0525                    if (videoSupported && audioSupported)
 526                    {
 0527                        break;
 528                    }
 529                }
 530            }
 531
 0532            TranscodeReason reasons = 0;
 0533            if (!containerSupported)
 534            {
 0535                reasons |= TranscodeReason.ContainerNotSupported;
 536            }
 537
 0538            if (!videoSupported)
 539            {
 0540                reasons |= TranscodeReason.VideoCodecNotSupported;
 541            }
 542
 0543            if (!audioSupported)
 544            {
 0545                reasons |= TranscodeReason.AudioCodecNotSupported;
 546            }
 547
 0548            return reasons;
 549        }
 550
 551        private static int? GetDefaultSubtitleStreamIndex(MediaSourceInfo item, SubtitleProfile[] subtitleProfiles)
 552        {
 182553            int highestScore = -1;
 1830554            foreach (var stream in item.MediaStreams)
 555            {
 733556                if (stream.Type == MediaStreamType.Subtitle
 733557                    && stream.Score.HasValue
 733558                    && stream.Score.Value > highestScore)
 559                {
 144560                    highestScore = stream.Score.Value;
 561                }
 562            }
 563
 182564            List<MediaStream> topStreams = [];
 1830565            foreach (var stream in item.MediaStreams)
 566            {
 733567                if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue && stream.Score.Value == highestSco
 568                {
 321569                    topStreams.Add(stream);
 570                }
 571            }
 572
 573            // If multiple streams have an equal score, try to pick the most efficient one
 182574            if (topStreams.Count > 1)
 575            {
 378576                foreach (var stream in topStreams)
 577                {
 1464578                    foreach (var profile in subtitleProfiles)
 579                    {
 549580                        if (profile.Method == SubtitleDeliveryMethod.External
 549581                            && (IsVobSubMksProfile(profile, stream)
 549582                                || (!IsVobSubMksDeliveryProfile(profile) && string.Equals(profile.Format, stream.Codec, 
 583                        {
 0584                            return stream.Index;
 585                        }
 586                    }
 587                }
 588            }
 589
 590            // If no optimization panned out, just use the original default
 182591            return item.DefaultSubtitleStreamIndex;
 0592        }
 593
 594        private static void SetStreamInfoOptionsFromTranscodingProfile(MediaSourceInfo item, StreamInfo playlistItem, Tr
 595        {
 153596            var container = transcodingProfile.Container;
 153597            var protocol = transcodingProfile.Protocol;
 598
 153599            item.TranscodingContainer = container;
 153600            item.TranscodingSubProtocol = protocol;
 601
 153602            if (playlistItem.PlayMethod == PlayMethod.Transcode)
 603            {
 153604                playlistItem.Container = container;
 153605                playlistItem.SubProtocol = protocol;
 606            }
 607
 153608            playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
 153609            if (int.TryParse(transcodingProfile.MaxAudioChannels, CultureInfo.InvariantCulture, out int transcodingMaxAu
 610            {
 135611                playlistItem.TranscodingMaxAudioChannels = transcodingMaxAudioChannels;
 612            }
 613
 153614            playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength;
 615
 153616            playlistItem.CopyTimestamps = transcodingProfile.CopyTimestamps;
 153617            playlistItem.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
 153618            playlistItem.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
 619
 153620            playlistItem.EnableAudioVbrEncoding = transcodingProfile.EnableAudioVbrEncoding;
 621
 153622            if (transcodingProfile.MinSegments > 0)
 623            {
 104624                playlistItem.MinSegments = transcodingProfile.MinSegments;
 625            }
 626
 153627            if (transcodingProfile.SegmentLength > 0)
 628            {
 0629                playlistItem.SegmentLength = transcodingProfile.SegmentLength;
 630            }
 153631        }
 632
 633        private static void SetStreamInfoOptionsFromDirectPlayProfile(MediaOptions options, MediaSourceInfo item, Stream
 634        {
 0635            var container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileTy
 0636            var protocol = MediaStreamProtocol.http;
 637
 0638            item.TranscodingContainer = container;
 0639            item.TranscodingSubProtocol = protocol;
 640
 0641            playlistItem.Container = container;
 0642            playlistItem.SubProtocol = protocol;
 643
 0644            playlistItem.VideoCodecs = [item.VideoStream.Codec];
 0645            playlistItem.AudioCodecs = ContainerHelper.Split(directPlayProfile?.AudioCodec);
 0646        }
 647
 648        private StreamInfo BuildVideoItem(MediaSourceInfo item, MediaOptions options)
 649        {
 287650            ArgumentNullException.ThrowIfNull(item);
 651
 287652            StreamInfo playlistItem = new StreamInfo
 287653            {
 287654                ItemId = options.ItemId,
 287655                MediaType = DlnaProfileType.Video,
 287656                MediaSource = item,
 287657                RunTimeTicks = item.RunTimeTicks,
 287658                Context = options.Context,
 287659                DeviceProfile = options.Profile,
 287660                SubtitleStreamIndex = options.SubtitleStreamIndex ?? GetDefaultSubtitleStreamIndex(item, options.Profile
 287661                AlwaysBurnInSubtitleWhenTranscoding = options.AlwaysBurnInSubtitleWhenTranscoding
 287662            };
 663
 287664            var subtitleStream = playlistItem.SubtitleStreamIndex.HasValue ? item.GetMediaStream(MediaStreamType.Subtitl
 665
 287666            var audioStream = item.GetDefaultAudioStream(options.AudioStreamIndex ?? item.DefaultAudioStreamIndex);
 287667            if (audioStream is not null)
 668            {
 286669                playlistItem.AudioStreamIndex = audioStream.Index;
 670            }
 671
 672            // Collect candidate audio streams
 287673            ICollection<MediaStream> candidateAudioStreams = audioStream is null ? [] : [audioStream];
 674            // When the index is explicitly required by client or the default is specified by user, don't do any stream 
 287675            if (!item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.User) && (options.AudioStreamIndex is null or < 0
 676            {
 677                // When user has no preferences allow stream selection on all streams.
 182678                if (item.DefaultAudioIndexSource == AudioIndexSource.None && audioStream is not null)
 679                {
 181680                    candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio).ToAr
 181681                    if (audioStream.IsDefault)
 682                    {
 683                        // If default is picked, only allow selection within default streams.
 176684                        candidateAudioStreams = candidateAudioStreams.Where(stream => stream.IsDefault).ToArray();
 685                    }
 686                }
 687
 182688                if (item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.Language))
 689                {
 690                    // If user has language preference, only allow stream selection within the same language.
 0691                    candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && st
 0692                    if (item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.Default))
 693                    {
 0694                        var defaultStreamsInPreferredLanguage = candidateAudioStreams.Where(stream => stream.IsDefault).
 695
 696                        // If the user also prefers default streams, try limit selection within default tracks in the sa
 697                        // If there is no default stream in the preferred language, allow selection on all default strea
 0698                        candidateAudioStreams = defaultStreamsInPreferredLanguage.Length > 0
 0699                            ? defaultStreamsInPreferredLanguage
 0700                            : item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && stream.IsDefault
 701                    }
 702                }
 182703                else if (item.DefaultAudioIndexSource.HasFlag(AudioIndexSource.Default))
 704                {
 705                    // If user prefers default streams, only allow stream selection on default streams.
 0706                    candidateAudioStreams = item.MediaStreams.Where(stream => stream.Type == MediaStreamType.Audio && st
 707                }
 708            }
 709
 287710            var videoStream = item.VideoStream;
 711
 287712            var bitrateLimitExceeded = IsBitrateLimitExceeded(item, options.GetMaxBitrate(false) ?? 0);
 287713            var isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || !bitrateLimitExceeded)
 287714            var isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || !bitrateLimitExc
 287715            TranscodeReason transcodeReasons = 0;
 716
 717            // Force transcode or remux for BD/DVD folders
 287718            if (item.VideoType == VideoType.Dvd || item.VideoType == VideoType.BluRay)
 719            {
 0720                isEligibleForDirectPlay = false;
 721            }
 722
 723            // A manifest is not a byte stream, so it cannot be handed to the client as one. The variant
 724            // and segment URIs inside it are relative to the origin and do not resolve against the
 725            // Jellyfin url the client would fetch it from.
 287726            if (ContainerHelper.ContainsContainer(ManifestContainers, item.Container))
 727            {
 4728                isEligibleForDirectPlay = false;
 729            }
 730
 287731            if (bitrateLimitExceeded)
 732            {
 24733                transcodeReasons = TranscodeReason.ContainerBitrateExceedsLimit;
 734            }
 735
 287736            _logger.LogDebug(
 287737                "Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
 287738                options.Profile.Name ?? "Unknown Profile",
 287739                item.Path ?? "Unknown path",
 287740                isEligibleForDirectPlay,
 287741                isEligibleForDirectStream);
 742
 287743            DirectPlayProfile? directPlayProfile = null;
 287744            if (isEligibleForDirectPlay || isEligibleForDirectStream)
 745            {
 746                // See if it can be direct played
 259747                var directPlayInfo = GetVideoDirectPlayProfile(options, item, videoStream, audioStream, candidateAudioSt
 259748                var directPlay = directPlayInfo.PlayMethod;
 259749                transcodeReasons |= directPlayInfo.TranscodeReasons;
 750
 259751                if (directPlay.HasValue)
 752                {
 126753                    directPlayProfile = directPlayInfo.Profile;
 126754                    playlistItem.PlayMethod = directPlay.Value;
 126755                    playlistItem.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profi
 126756                    var videoCodec = videoStream?.Codec;
 126757                    playlistItem.VideoCodecs = videoCodec is null ? [] : [videoCodec];
 758
 126759                    if (directPlay == PlayMethod.DirectPlay)
 760                    {
 126761                        playlistItem.SubProtocol = MediaStreamProtocol.http;
 762
 126763                        var audioStreamIndex = directPlayInfo.AudioStreamIndex ?? audioStream?.Index;
 126764                        if (audioStreamIndex.HasValue)
 765                        {
 126766                            playlistItem.AudioStreamIndex = audioStreamIndex;
 126767                            var audioCodec = item.GetMediaStream(MediaStreamType.Audio, audioStreamIndex.Value)?.Codec;
 126768                            playlistItem.AudioCodecs = audioCodec is null ? [] : [audioCodec];
 769                        }
 770                    }
 0771                    else if (directPlay == PlayMethod.DirectStream)
 772                    {
 0773                        playlistItem.AudioStreamIndex = audioStream?.Index;
 0774                        if (audioStream is not null)
 775                        {
 0776                            playlistItem.AudioCodecs = ContainerHelper.Split(directPlayProfile?.AudioCodec);
 777                        }
 778
 0779                        SetStreamInfoOptionsFromDirectPlayProfile(options, item, playlistItem, directPlayProfile);
 0780                        BuildStreamVideoItem(playlistItem, options, item, videoStream, audioStream, candidateAudioStream
 781                    }
 782
 126783                    if (subtitleStream is not null)
 784                    {
 116785                        var subtitleProfile = GetSubtitleProfile(item, subtitleStream, options.Profile.SubtitleProfiles,
 786
 116787                        playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
 116788                        playlistItem.SubtitleFormat = subtitleProfile.Format;
 789                    }
 790                }
 791
 259792                _logger.LogDebug(
 259793                    "DirectPlay Result for Profile: {0}, Path: {1}, PlayMethod: {2}, AudioStreamIndex: {3}, SubtitleStre
 259794                    options.Profile.Name ?? "Anonymous Profile",
 259795                    item.Path ?? "Unknown path",
 259796                    directPlayInfo.PlayMethod,
 259797                    directPlayInfo.AudioStreamIndex ?? audioStream?.Index,
 259798                    playlistItem.SubtitleStreamIndex,
 259799                    directPlayInfo.TranscodeReasons);
 800            }
 801
 287802            playlistItem.TranscodeReasons = transcodeReasons;
 803
 287804            if (playlistItem.PlayMethod != PlayMethod.DirectStream && playlistItem.PlayMethod != PlayMethod.DirectPlay)
 805            {
 806                // Can't direct play, find the transcoding profile
 807                // If we do this for direct-stream we will overwrite the info
 161808                var (transcodingProfile, playMethod) = GetVideoTranscodeProfile(item, options, videoStream, audioStream,
 809
 161810                if (transcodingProfile is not null && playMethod.HasValue)
 811                {
 153812                    SetStreamInfoOptionsFromTranscodingProfile(item, playlistItem, transcodingProfile);
 813
 153814                    BuildStreamVideoItem(playlistItem, options, item, videoStream, audioStream, candidateAudioStreams, t
 815
 153816                    playlistItem.PlayMethod = PlayMethod.Transcode;
 817
 153818                    if (subtitleStream is not null)
 819                    {
 125820                        var subtitleProfile = GetSubtitleProfile(item, subtitleStream, options.Profile.SubtitleProfiles,
 125821                        playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
 125822                        playlistItem.SubtitleFormat = subtitleProfile.Format;
 125823                        playlistItem.SubtitleCodecs = [subtitleProfile.Format];
 824                    }
 825
 153826                    if ((playlistItem.TranscodeReasons & (VideoReasons | TranscodeReason.ContainerBitrateExceedsLimit)) 
 827                    {
 55828                        ApplyTranscodingConditions(playlistItem, transcodingProfile.Conditions, null, true, true);
 829                    }
 830                }
 831            }
 832
 287833            _logger.LogDebug(
 287834                "StreamBuilder.BuildVideoItem( Profile={0}, Path={1}, AudioStreamIndex={2}, SubtitleStreamIndex={3} ) =>
 287835                options.Profile.Name ?? "Anonymous Profile",
 287836                item.Path ?? "Unknown path",
 287837                options.AudioStreamIndex,
 287838                options.SubtitleStreamIndex,
 287839                playlistItem.PlayMethod,
 287840                playlistItem.TranscodeReasons,
 287841                playlistItem.ToUrl("media:", "<token>", null));
 842
 287843            item.Container = NormalizeMediaSourceFormatIntoSingleContainer(item.Container, options.Profile, DlnaProfileT
 287844            return playlistItem;
 845        }
 846
 847        private (TranscodingProfile? Profile, PlayMethod? PlayMethod) GetVideoTranscodeProfile(
 848            MediaSourceInfo item,
 849            MediaOptions options,
 850            MediaStream? videoStream,
 851            MediaStream? audioStream,
 852            StreamInfo playlistItem)
 853        {
 161854            var mediaSource = playlistItem.MediaSource;
 855
 161856            ArgumentNullException.ThrowIfNull(mediaSource);
 857
 161858            if (!(item.SupportsTranscoding || item.SupportsDirectStream))
 859            {
 0860                return (null, null);
 861            }
 862
 161863            var transcodingProfiles = options.Profile.TranscodingProfiles
 161864                .Where(i => i.Type == playlistItem.MediaType && i.Context == options.Context);
 865
 161866            if (item.UseMostCompatibleTranscodingProfile)
 867            {
 0868                transcodingProfiles = transcodingProfiles.Where(i => string.Equals(i.Container, "ts", StringComparison.O
 869            }
 870
 161871            var videoCodec = videoStream?.Codec;
 161872            var audioCodec = audioStream?.Codec;
 873
 161874            var analyzedProfiles = transcodingProfiles
 161875                .Select(transcodingProfile =>
 161876                {
 161877                    var rank = (Video: 3, Audio: 3);
 161878
 161879                    var container = transcodingProfile.Container;
 161880
 161881                    if (videoStream is not null
 161882                        && options.AllowVideoStreamCopy
 161883                        && ContainerHelper.ContainsContainer(transcodingProfile.VideoCodec, videoCodec))
 161884                    {
 161885                        var failures = GetCompatibilityVideoCodec(options, mediaSource, container, videoStream);
 161886                        rank.Video = failures == 0 ? 1 : 2;
 161887                    }
 161888
 161889                    if (audioStream is not null
 161890                        && options.AllowAudioStreamCopy)
 161891                    {
 161892                        // For Audio stream, we prefer the audio codec that can be directly copied, then the codec that 
 161893                        // the transcoding conditions, then the one does not satisfy the transcoding conditions.
 161894                        // For example: A client can support both aac and flac, but flac only supports 2 channels while 
 161895                        // When the source audio is 6 channel flac, we should transcode to 6 channel aac, instead of dow
 161896                        var transcodingAudioCodecs = ContainerHelper.Split(transcodingProfile.AudioCodec);
 161897
 161898                        foreach (var transcodingAudioCodec in transcodingAudioCodecs)
 161899                        {
 161900                            var failures = GetCompatibilityAudioCodec(options, mediaSource, container, audioStream, tran
 161901
 161902                            var rankAudio = 3;
 161903
 161904                            if (failures == 0)
 161905                            {
 161906                                rankAudio = string.Equals(transcodingAudioCodec, audioCodec, StringComparison.OrdinalIgn
 161907                            }
 161908
 161909                            rank.Audio = Math.Min(rank.Audio, rankAudio);
 161910
 161911                            if (rank.Audio == 1)
 161912                            {
 161913                                break;
 161914                            }
 161915                        }
 161916                    }
 161917
 161918                    PlayMethod playMethod = PlayMethod.Transcode;
 161919
 161920                    if (rank.Video == 1)
 161921                    {
 161922                        playMethod = PlayMethod.DirectStream;
 161923                    }
 161924
 161925                    return (Profile: transcodingProfile, PlayMethod: playMethod, Rank: rank);
 161926                })
 161927                .OrderBy(analysis => analysis.Rank);
 928
 161929            var profileMatch = analyzedProfiles.FirstOrDefault();
 930
 161931            return (profileMatch.Profile, profileMatch.PlayMethod);
 932        }
 933
 934        private void BuildStreamVideoItem(
 935            StreamInfo playlistItem,
 936            MediaOptions options,
 937            MediaSourceInfo item,
 938            MediaStream? videoStream,
 939            MediaStream? audioStream,
 940            IEnumerable<MediaStream> candidateAudioStreams,
 941            string? container,
 942            string? videoCodec,
 943            string? audioCodec)
 944        {
 945            // Prefer matching video codecs
 153946            var videoCodecs = ContainerHelper.Split(videoCodec).ToList();
 947
 153948            if (videoCodecs.Count == 0 && videoStream is not null)
 949            {
 950                // Add the original codec if no codec is specified
 0951                videoCodecs.Add(videoStream.Codec);
 952            }
 953
 954            // Enforce HLS video codec restrictions
 153955            if (playlistItem.SubProtocol == MediaStreamProtocol.hls)
 956            {
 139957                videoCodecs = videoCodecs.Where(codec => _supportedHlsVideoCodecs.Contains(codec)).ToList();
 958            }
 959
 153960            playlistItem.VideoCodecs = videoCodecs;
 153961            if (videoStream is not null && !ContainerHelper.ContainsContainer(videoCodecs, false, videoStream.Codec))
 962            {
 31963                playlistItem.TranscodeReasons |= TranscodeReason.VideoCodecNotSupported;
 964            }
 965
 966            // Copy video codec options as a starting point, this applies to transcode and direct-stream
 153967            playlistItem.MaxFramerate = videoStream?.ReferenceFrameRate;
 153968            var qualifier = videoStream?.Codec;
 153969            if (videoStream?.Level is not null)
 970            {
 148971                playlistItem.SetOption(qualifier, "level", videoStream.Level.Value.ToString(CultureInfo.InvariantCulture
 972            }
 973
 153974            if (videoStream?.BitDepth is not null)
 975            {
 148976                playlistItem.SetOption(qualifier, "videobitdepth", videoStream.BitDepth.Value.ToString(CultureInfo.Invar
 977            }
 978
 153979            if (!string.IsNullOrEmpty(videoStream?.Profile))
 980            {
 148981                playlistItem.SetOption(qualifier, "profile", videoStream.Profile.ToLowerInvariant());
 982            }
 983
 984            // Prefer matching audio codecs, could do better here
 153985            var audioCodecs = ContainerHelper.Split(audioCodec).ToList();
 986
 153987            if (audioCodecs.Count == 0 && audioStream is not null)
 988            {
 989                // Add the original codec if no codec is specified
 0990                audioCodecs.Add(audioStream.Codec);
 991            }
 992
 993            // Enforce HLS audio codec restrictions
 153994            if (playlistItem.SubProtocol == MediaStreamProtocol.hls)
 995            {
 139996                if (string.Equals(playlistItem.Container, "mp4", StringComparison.OrdinalIgnoreCase))
 997                {
 74998                    audioCodecs = audioCodecs.Where(codec => _supportedHlsAudioCodecsMp4.Contains(codec)).ToList();
 999                }
 1000                else
 1001                {
 651002                    audioCodecs = audioCodecs.Where(codec => _supportedHlsAudioCodecsTs.Contains(codec)).ToList();
 1003                }
 1004            }
 1005
 1531006            var audioStreamWithSupportedCodec = candidateAudioStreams.Where(stream => ContainerHelper.ContainsContainer(
 1007
 1531008            var channelsExceedsLimit = audioStreamWithSupportedCodec is not null && audioStreamWithSupportedCodec.Channe
 1009
 1531010            var directAudioFailures = audioStreamWithSupportedCodec is null ? default : GetCompatibilityAudioCodec(optio
 1011
 1531012            playlistItem.TranscodeReasons |= directAudioFailures;
 1531013            if (audioStream is not null && audioStreamWithSupportedCodec is null)
 1014            {
 651015                playlistItem.TranscodeReasons |= TranscodeReason.AudioCodecNotSupported;
 1016            }
 1017
 1531018            var directAudioStreamSatisfied = audioStreamWithSupportedCodec is not null && !channelsExceedsLimit
 1531019                && directAudioFailures == 0;
 1020
 1531021            directAudioStreamSatisfied = directAudioStreamSatisfied && !playlistItem.TranscodeReasons.HasFlag(TranscodeR
 1022
 1531023            var directAudioStream = directAudioStreamSatisfied ? audioStreamWithSupportedCodec : null;
 1024
 1531025            if (channelsExceedsLimit && playlistItem.TargetAudioStream is not null)
 1026            {
 101027                playlistItem.TranscodeReasons |= TranscodeReason.AudioChannelsNotSupported;
 101028                playlistItem.TargetAudioStream.Channels = playlistItem.TranscodingMaxAudioChannels;
 1029            }
 1030
 1531031            playlistItem.AudioCodecs = audioCodecs;
 1531032            if (directAudioStream is not null)
 1033            {
 621034                audioStream = directAudioStream;
 621035                playlistItem.AudioStreamIndex = audioStream.Index;
 621036                audioCodecs = [audioStream.Codec];
 621037                playlistItem.AudioCodecs = audioCodecs;
 1038
 1039                // Copy matching audio codec options
 621040                playlistItem.AudioSampleRate = audioStream.SampleRate;
 621041                playlistItem.SetOption(qualifier, "audiochannels", audioStream.Channels?.ToString(CultureInfo.InvariantC
 1042
 621043                if (!string.IsNullOrEmpty(audioStream.Profile))
 1044                {
 561045                    playlistItem.SetOption(audioStream.Codec, "profile", audioStream.Profile.ToLowerInvariant());
 1046                }
 1047
 621048                if (audioStream.Level.HasValue && audioStream.Level.Value != 0)
 1049                {
 01050                    playlistItem.SetOption(audioStream.Codec, "level", audioStream.Level.Value.ToString(CultureInfo.Inva
 1051                }
 1052            }
 1053
 1531054            int? width = videoStream?.Width;
 1531055            int? height = videoStream?.Height;
 1531056            int? bitDepth = videoStream?.BitDepth;
 1531057            int? videoBitrate = videoStream?.BitRate;
 1531058            double? videoLevel = videoStream?.Level;
 1531059            string? videoProfile = videoStream?.Profile;
 1531060            VideoRangeType? videoRangeType = videoStream?.VideoRangeType;
 1531061            float videoFramerate = videoStream is null ? 0 : videoStream.ReferenceFrameRate ?? 0;
 1531062            bool? isAnamorphic = videoStream?.IsAnamorphic;
 1531063            bool? isInterlaced = videoStream?.IsInterlaced;
 1531064            string? videoCodecTag = videoStream?.CodecTag;
 1531065            bool? isAvc = videoStream?.IsAVC;
 1531066            int? videoRotation = videoStream?.Rotation;
 1067
 1531068            TransportStreamTimestamp? timestamp = videoStream is null ? TransportStreamTimestamp.None : item.Timestamp;
 1531069            int? packetLength = videoStream?.PacketLength;
 1531070            int? refFrames = videoStream?.RefFrames;
 1071
 1531072            int numStreams = item.MediaStreams.Count;
 1531073            int? numAudioStreams = item.GetStreamCount(MediaStreamType.Audio);
 1531074            int? numVideoStreams = item.GetStreamCount(MediaStreamType.Video);
 1075
 1531076            var useSubContainer = playlistItem.SubProtocol == MediaStreamProtocol.hls;
 1077
 1531078            var appliedVideoConditions = options.Profile.CodecProfiles
 1531079                .Where(i => i.Type == CodecType.Video &&
 1531080                    i.ContainsAnyCodec(playlistItem.VideoCodecs, container, useSubContainer) &&
 1531081                    i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoConditionSatisfied(applyCondition,
 1531082                // Reverse codec profiles for backward compatibility - first codec profile has higher priority
 1531083                .Reverse();
 9181084            foreach (var condition in appliedVideoConditions)
 1085            {
 24961086                foreach (var transcodingVideoCodec in playlistItem.VideoCodecs)
 1087                {
 9421088                    if (condition.ContainsAnyCodec(transcodingVideoCodec, container, useSubContainer))
 1089                    {
 3141090                        ApplyTranscodingConditions(playlistItem, condition.Conditions, transcodingVideoCodec, true, true
 1091                        continue;
 1092                    }
 1093                }
 1094            }
 1095
 1096            // Honor requested max channels
 1531097            playlistItem.GlobalMaxAudioChannels = channelsExceedsLimit ? playlistItem.TranscodingMaxAudioChannels : opti
 1098
 1531099            int audioBitrate = GetAudioBitrate(options.GetMaxBitrate(true) ?? 0, playlistItem.TargetAudioCodec, audioStr
 1531100            playlistItem.AudioBitrate = Math.Min(playlistItem.AudioBitrate ?? audioBitrate, audioBitrate);
 1101
 1531102            bool? isSecondaryAudio = audioStream is null ? null : item.IsSecondaryAudio(audioStream);
 1531103            int? inputAudioBitrate = audioStream?.BitRate;
 1531104            int? audioChannels = audioStream?.Channels;
 1531105            string? audioProfile = audioStream?.Profile;
 1531106            int? inputAudioSampleRate = audioStream?.SampleRate;
 1531107            int? inputAudioBitDepth = audioStream?.BitDepth;
 1108
 1531109            var appliedAudioConditions = options.Profile.CodecProfiles
 1531110                .Where(i => i.Type == CodecType.VideoAudio &&
 1531111                    i.ContainsAnyCodec(playlistItem.AudioCodecs, container) &&
 1531112                    i.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoAudioConditionSatisfied(applyCondi
 1531113                // Reverse codec profiles for backward compatibility - first codec profile has higher priority
 1531114                .Reverse();
 1115
 6181116            foreach (var codecProfile in appliedAudioConditions)
 1117            {
 4681118                foreach (var transcodingAudioCodec in playlistItem.AudioCodecs)
 1119                {
 1561120                    if (codecProfile.ContainsAnyCodec(transcodingAudioCodec, container))
 1121                    {
 1561122                        ApplyTranscodingConditions(playlistItem, codecProfile.Conditions, transcodingAudioCodec, true, t
 1561123                        break;
 1124                    }
 1125                }
 1126            }
 1127
 1531128            var maxBitrateSetting = options.GetMaxBitrate(false);
 1129            // Honor max rate
 1531130            if (maxBitrateSetting.HasValue)
 1131            {
 1531132                var availableBitrateForVideo = maxBitrateSetting.Value;
 1133
 1531134                if (playlistItem.AudioBitrate.HasValue)
 1135                {
 1531136                    availableBitrateForVideo -= playlistItem.AudioBitrate.Value;
 1137                }
 1138
 1139                // Make sure the video bitrate is lower than bitrate settings but at least 64k
 1140                // Don't use Math.Clamp as availableBitrateForVideo can be lower then 64k.
 1531141                var currentValue = playlistItem.VideoBitrate ?? availableBitrateForVideo;
 1531142                playlistItem.VideoBitrate = Math.Max(Math.Min(availableBitrateForVideo, currentValue), 64_000);
 1143            }
 1144
 1531145            _logger.LogDebug(
 1531146                "Transcode Result for Profile: {Profile}, Path: {Path}, PlayMethod: {PlayMethod}, AudioStreamIndex: {Aud
 1531147                options.Profile.Name ?? "Anonymous Profile",
 1531148                item.Path ?? "Unknown path",
 1531149                playlistItem.PlayMethod,
 1531150                audioStream?.Index,
 1531151                playlistItem.SubtitleStreamIndex,
 1531152                playlistItem.TranscodeReasons);
 1531153        }
 1154
 1155        private static int GetDefaultAudioBitrate(string? audioCodec, int? audioChannels)
 1156        {
 641157            if (!string.IsNullOrEmpty(audioCodec))
 1158            {
 1159                // Default to a higher bitrate for stream copy
 641160                if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)
 641161                    || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)
 641162                    || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)
 641163                    || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
 1164                {
 591165                    if ((audioChannels ?? 0) < 2)
 1166                    {
 41167                        return 128000;
 1168                    }
 1169
 551170                    return (audioChannels ?? 0) >= 6 ? 640000 : 384000;
 1171                }
 1172
 51173                if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase)
 51174                    || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase))
 1175                {
 01176                    if ((audioChannels ?? 0) < 2)
 1177                    {
 01178                        return 768000;
 1179                    }
 1180
 01181                    return (audioChannels ?? 0) >= 6 ? 3584000 : 1536000;
 1182                }
 1183            }
 1184
 51185            return 192000;
 1186        }
 1187
 1188        private static int GetAudioBitrate(long maxTotalBitrate, IReadOnlyList<string> targetAudioCodecs, MediaStream? a
 1189        {
 1531190            string? targetAudioCodec = targetAudioCodecs.Count == 0 ? null : targetAudioCodecs[0];
 1191
 1531192            int? targetAudioChannels = item.GetTargetAudioChannels(targetAudioCodec);
 1193
 1194            int defaultBitrate;
 1531195            int encoderAudioBitrateLimit = int.MaxValue;
 1196
 1531197            if (audioStream is null)
 1198            {
 11199                defaultBitrate = 192000;
 1200            }
 1201            else
 1202            {
 1521203                if (targetAudioChannels.HasValue
 1521204                    && audioStream.Channels.HasValue
 1521205                    && audioStream.Channels.Value > targetAudioChannels.Value)
 1206                {
 1207                    // Reduce the bitrate if we're down mixing.
 461208                    defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels);
 1209                }
 1061210                else if (targetAudioChannels.HasValue
 1061211                         && audioStream.Channels.HasValue
 1061212                         && audioStream.Channels.Value <= targetAudioChannels.Value
 1061213                         && !string.IsNullOrEmpty(audioStream.Codec)
 1061214                         && targetAudioCodecs is not null
 1061215                         && targetAudioCodecs.Count > 0
 1061216                         && !targetAudioCodecs.Any(elem => string.Equals(audioStream.Codec, elem, StringComparison.Ordin
 1217                {
 1218                    // Shift the bitrate if we're transcoding to a different audio codec.
 141219                    defaultBitrate = GetDefaultAudioBitrate(targetAudioCodec, audioStream.Channels.Value);
 1220                }
 1221                else
 1222                {
 921223                    defaultBitrate = audioStream.BitRate ?? GetDefaultAudioBitrate(targetAudioCodec, targetAudioChannels
 1224                }
 1225
 1226                // Seeing webm encoding failures when source has 1 audio channel and 22k bitrate.
 1227                // Any attempts to transcode over 64k will fail
 1521228                if (audioStream.Channels == 1
 1521229                    && (audioStream.BitRate ?? 0) < 64000)
 1230                {
 01231                    encoderAudioBitrateLimit = 64000;
 1232                }
 1233            }
 1234
 1531235            if (maxTotalBitrate > 0)
 1236            {
 1531237                defaultBitrate = Math.Min(GetMaxAudioBitrateForTotalBitrate(maxTotalBitrate), defaultBitrate);
 1238            }
 1239
 1531240            return Math.Min(defaultBitrate, encoderAudioBitrateLimit);
 1241        }
 1242
 1243        private static int GetMaxAudioBitrateForTotalBitrate(long totalBitrate)
 1244        {
 1531245            if (totalBitrate <= 640000)
 1246            {
 81247                return 128000;
 1248            }
 1249
 1451250            if (totalBitrate <= 2000000)
 1251            {
 01252                return 384000;
 1253            }
 1254
 1451255            if (totalBitrate <= 3000000)
 1256            {
 01257                return 448000;
 1258            }
 1259
 1451260            if (totalBitrate <= 4000000)
 1261            {
 01262                return 640000;
 1263            }
 1264
 1451265            if (totalBitrate <= 5000000)
 1266            {
 01267                return 768000;
 1268            }
 1269
 1451270            if (totalBitrate <= 10000000)
 1271            {
 121272                return 1536000;
 1273            }
 1274
 1331275            if (totalBitrate <= 15000000)
 1276            {
 01277                return 2304000;
 1278            }
 1279
 1331280            if (totalBitrate <= 20000000)
 1281            {
 141282                return 3584000;
 1283            }
 1284
 1191285            return 7168000;
 1286        }
 1287
 1288        private (DirectPlayProfile? Profile, PlayMethod? PlayMethod, int? AudioStreamIndex, TranscodeReason TranscodeRea
 1289            MediaOptions options,
 1290            MediaSourceInfo mediaSource,
 1291            MediaStream? videoStream,
 1292            MediaStream? audioStream,
 1293            ICollection<MediaStream> candidateAudioStreams,
 1294            MediaStream? subtitleStream,
 1295            bool isEligibleForDirectPlay,
 1296            bool isEligibleForDirectStream)
 1297        {
 2591298            if (options.ForceDirectPlay)
 1299            {
 01300                return (null, PlayMethod.DirectPlay, audioStream?.Index, 0);
 1301            }
 1302
 2591303            if (options.ForceDirectStream)
 1304            {
 01305                return (null, PlayMethod.DirectStream, audioStream?.Index, 0);
 1306            }
 1307
 2591308            DeviceProfile profile = options.Profile;
 2591309            string container = mediaSource.Container;
 1310
 1311            // Check container conditions
 2591312            var containerProfileReasons = GetCompatibilityContainer(options, mediaSource, container, videoStream);
 1313
 1314            // Check video conditions
 2591315            var videoCodecProfileReasons = videoStream is null ? default : GetCompatibilityVideoCodec(options, mediaSour
 1316
 1317            // Check audio candidates profile conditions
 2591318            var audioStreamMatches = candidateAudioStreams.ToDictionary(s => s, audioStream => GetCompatibilityAudioCode
 1319
 2591320            TranscodeReason subtitleProfileReasons = 0;
 2591321            if (subtitleStream is not null)
 1322            {
 2251323                var subtitleProfile = GetSubtitleProfile(mediaSource, subtitleStream, options.Profile.SubtitleProfiles, 
 1324
 2251325                if (subtitleProfile.Method != SubtitleDeliveryMethod.Drop
 2251326                    && subtitleProfile.Method != SubtitleDeliveryMethod.External
 2251327                    && subtitleProfile.Method != SubtitleDeliveryMethod.Embed)
 1328                {
 01329                    _logger.LogDebug("Not eligible for {0} due to unsupported subtitles", PlayMethod.DirectPlay);
 01330                    subtitleProfileReasons |= TranscodeReason.SubtitleCodecNotSupported;
 1331                }
 1332            }
 1333
 2591334            var containerSupported = false;
 2591335            TranscodeReason[] rankings = [TranscodeReason.VideoCodecNotSupported, VideoCodecReasons, TranscodeReason.Aud
 1336
 1337            // Check DirectPlay profiles to see if it can be direct played
 2591338            var analyzedProfiles = profile.DirectPlayProfiles
 2591339                .Where(directPlayProfile => directPlayProfile.Type == DlnaProfileType.Video)
 2591340                .Select((directPlayProfile, order) =>
 2591341                {
 2591342                    TranscodeReason directPlayProfileReasons = 0;
 2591343                    TranscodeReason audioCodecProfileReasons = 0;
 2591344
 2591345                    // Check container type
 2591346                    if (!directPlayProfile.SupportsContainer(container))
 2591347                    {
 2591348                        directPlayProfileReasons |= TranscodeReason.ContainerNotSupported;
 2591349                    }
 2591350                    else
 2591351                    {
 2591352                        containerSupported = true;
 2591353                    }
 2591354
 2591355                    // Check video codec
 2591356                    string? videoCodec = videoStream?.Codec;
 2591357                    if (!directPlayProfile.SupportsVideoCodec(videoCodec))
 2591358                    {
 2591359                        directPlayProfileReasons |= TranscodeReason.VideoCodecNotSupported;
 2591360                    }
 2591361
 2591362                    // Check audio codec
 2591363                    MediaStream? selectedAudioStream = null;
 2591364                    if (candidateAudioStreams.Count != 0)
 2591365                    {
 2591366                        selectedAudioStream = candidateAudioStreams.FirstOrDefault(audioStream => directPlayProfile.Supp
 2591367                        if (selectedAudioStream is null)
 2591368                        {
 2591369                            directPlayProfileReasons |= TranscodeReason.AudioCodecNotSupported;
 2591370                        }
 2591371                        else
 2591372                        {
 2591373                            audioCodecProfileReasons = audioStreamMatches.GetValueOrDefault(selectedAudioStream);
 2591374                        }
 2591375                    }
 2591376
 2591377                    var failureReasons = directPlayProfileReasons | containerProfileReasons | subtitleProfileReasons;
 2591378
 2591379                    if ((failureReasons & TranscodeReason.VideoCodecNotSupported) == 0)
 2591380                    {
 2591381                        failureReasons |= videoCodecProfileReasons;
 2591382                    }
 2591383
 2591384                    if ((failureReasons & TranscodeReason.AudioCodecNotSupported) == 0)
 2591385                    {
 2591386                        failureReasons |= audioCodecProfileReasons;
 2591387                    }
 2591388
 2591389                    var directStreamFailureReasons = failureReasons & (~DirectStreamReasons);
 2591390
 2591391                    PlayMethod? playMethod = null;
 2591392                    if (failureReasons == 0 && isEligibleForDirectPlay && mediaSource.SupportsDirectPlay)
 2591393                    {
 2591394                        playMethod = PlayMethod.DirectPlay;
 2591395                    }
 2591396                    else if (directStreamFailureReasons == 0 && isEligibleForDirectStream && mediaSource.SupportsDirectS
 2591397                    {
 2591398                        playMethod = PlayMethod.DirectStream;
 2591399                    }
 2591400
 2591401                    var ranked = GetRank(ref failureReasons, rankings);
 2591402
 2591403                    return (Result: (Profile: directPlayProfile, PlayMethod: playMethod, AudioStreamIndex: selectedAudio
 2591404                })
 2591405                .OrderByDescending(analysis => analysis.Result.PlayMethod)
 2591406                .ThenByDescending(analysis => analysis.Rank)
 2591407                .ThenBy(analysis => analysis.Order)
 2591408                .ToArray()
 2591409                .ToLookup(analysis => analysis.Result.PlayMethod is not null);
 1410
 2591411            var profileMatch = analyzedProfiles[true]
 2591412                .Select(analysis => analysis.Result)
 2591413                .FirstOrDefault();
 2591414            if (profileMatch.Profile is not null)
 1415            {
 1261416                return profileMatch;
 1417            }
 1418
 1331419            var failureReasons = analyzedProfiles[false]
 1331420                .Select(analysis => analysis.Result)
 1331421                .Where(result => !containerSupported || !result.TranscodeReason.HasFlag(TranscodeReason.ContainerNotSupp
 1331422                .FirstOrDefault().TranscodeReason;
 1331423            if (failureReasons == 0)
 1424            {
 141425                failureReasons = TranscodeReason.DirectPlayError;
 1426            }
 1427
 1331428            return (Profile: null, PlayMethod: null, AudioStreamIndex: null, TranscodeReasons: failureReasons);
 1429        }
 1430
 1431        private TranscodeReason AggregateFailureConditions(MediaSourceInfo mediaSource, DeviceProfile profile, string ty
 1432        {
 17001433            return conditions.Aggregate<ProfileCondition, TranscodeReason>(0, (reasons, i) =>
 17001434            {
 17001435                LogConditionFailure(profile, type, i, mediaSource);
 17001436                var transcodeReasons = GetTranscodeReasonForFailedCondition(i);
 17001437                return reasons | transcodeReasons;
 17001438            });
 1439        }
 1440
 1441        private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo
 1442        {
 2521443            _logger.LogDebug(
 2521444                "Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Pa
 2521445                type,
 2521446                profile.Name ?? "Unknown Profile",
 2521447                condition.Property,
 2521448                condition.Condition,
 2521449                condition.Value ?? string.Empty,
 2521450                condition.IsRequired,
 2521451                mediaSource.Path ?? "Unknown path");
 2521452        }
 1453
 1454        /// <summary>
 1455        /// Normalizes input container.
 1456        /// </summary>
 1457        /// <param name="mediaSource">The <see cref="MediaSourceInfo"/>.</param>
 1458        /// <param name="subtitleStream">The <see cref="MediaStream"/> of the subtitle stream.</param>
 1459        /// <param name="subtitleProfiles">The list of supported <see cref="SubtitleProfile"/>s.</param>
 1460        /// <param name="playMethod">The <see cref="PlayMethod"/>.</param>
 1461        /// <param name="transcoderSupport">The <see cref="ITranscoderSupport"/>.</param>
 1462        /// <param name="outputContainer">The output container.</param>
 1463        /// <param name="transcodingSubProtocol">The subtitle transcoding protocol.</param>
 1464        /// <returns>The normalized input container.</returns>
 1465        public static SubtitleProfile GetSubtitleProfile(
 1466            MediaSourceInfo mediaSource,
 1467            MediaStream subtitleStream,
 1468            SubtitleProfile[] subtitleProfiles,
 1469            PlayMethod playMethod,
 1470            ITranscoderSupport transcoderSupport,
 1471            string? outputContainer,
 1472            MediaStreamProtocol? transcodingSubProtocol)
 1473        {
 4911474            if (CanConsiderEmbedSubtitle(subtitleStream, playMethod, transcodingSubProtocol, outputContainer))
 1475            {
 1476                // Look for supported embedded subs of the same format
 701477                foreach (var profile in subtitleProfiles)
 1478                {
 191479                    if (!profile.SupportsLanguage(subtitleStream.Language))
 1480                    {
 1481                        continue;
 1482                    }
 1483
 191484                    if (profile.Method != SubtitleDeliveryMethod.Embed)
 1485                    {
 1486                        continue;
 1487                    }
 1488
 61489                    if (!ContainerHelper.ContainsContainer(profile.Container, outputContainer))
 1490                    {
 1491                        continue;
 1492                    }
 1493
 61494                    if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(outputContainer))
 1495                    {
 1496                        continue;
 1497                    }
 1498
 61499                    if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && string.Equals
 1500                    {
 61501                        return profile;
 1502                    }
 1503                }
 1504
 1505                // Look for supported embedded subs of a convertible format
 521506                foreach (var profile in subtitleProfiles)
 1507                {
 131508                    if (!profile.SupportsLanguage(subtitleStream.Language))
 1509                    {
 1510                        continue;
 1511                    }
 1512
 131513                    if (profile.Method != SubtitleDeliveryMethod.Embed)
 1514                    {
 1515                        continue;
 1516                    }
 1517
 01518                    if (!ContainerHelper.ContainsContainer(profile.Container, outputContainer))
 1519                    {
 1520                        continue;
 1521                    }
 1522
 01523                    if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(outputContainer))
 1524                    {
 1525                        continue;
 1526                    }
 1527
 01528                    if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsSubtitleConversionTo(profile.Forma
 1529                    {
 01530                        return profile;
 1531                    }
 1532                }
 1533            }
 1534
 1535            // Look for an external or hls profile that matches the stream type (text/graphical) and doesn't require con
 4851536            return GetExternalSubtitleProfile(mediaSource, subtitleStream, subtitleProfiles, playMethod, transcoderSuppo
 4851537                GetExternalSubtitleProfile(mediaSource, subtitleStream, subtitleProfiles, playMethod, transcoderSupport,
 4851538                new SubtitleProfile
 4851539                {
 4851540                    Method = SubtitleDeliveryMethod.Encode,
 4851541                    Format = subtitleStream.Codec
 4851542                };
 1543        }
 1544
 1545        private static bool IsSubtitleEmbedSupported(string? transcodingContainer)
 1546        {
 291547            if (!string.IsNullOrEmpty(transcodingContainer))
 1548            {
 241549                if (ContainerHelper.ContainsContainer(transcodingContainer, "ts,mpegts,mp4"))
 1550                {
 71551                    return false;
 1552                }
 1553
 171554                if (ContainerHelper.ContainsContainer(transcodingContainer, "mkv,matroska"))
 1555                {
 101556                    return true;
 1557                }
 1558            }
 1559
 121560            return false;
 1561        }
 1562
 1563        private static bool CanConsiderEmbedSubtitle(MediaStream subtitleStream, PlayMethod playMethod, MediaStreamProto
 1564        {
 4911565            if (subtitleStream.IsExternal)
 1566            {
 4741567                return playMethod == PlayMethod.Transcode
 4741568                    && transcodingSubProtocol != MediaStreamProtocol.hls
 4741569                    && IsSubtitleEmbedSupported(outputContainer);
 1570            }
 1571
 171572            return playMethod != PlayMethod.Transcode
 171573                || transcodingSubProtocol != MediaStreamProtocol.hls;
 1574        }
 1575
 1576        private static SubtitleProfile? GetExternalSubtitleProfile(MediaSourceInfo mediaSource, MediaStream subtitleStre
 1577        {
 51661578            foreach (var profile in subtitleProfiles)
 1579            {
 20471580                if (profile.Method != SubtitleDeliveryMethod.External && profile.Method != SubtitleDeliveryMethod.Hls)
 1581                {
 1582                    continue;
 1583                }
 1584
 14101585                if (profile.Method == SubtitleDeliveryMethod.Hls && playMethod != PlayMethod.Transcode)
 1586                {
 1587                    continue;
 1588                }
 1589
 14101590                if (!profile.SupportsLanguage(subtitleStream.Language))
 1591                {
 1592                    continue;
 1593                }
 1594
 14101595                if (!subtitleStream.IsExternal
 14101596                    && playMethod == PlayMethod.Transcode
 14101597                    && !transcoderSupport.CanExtractSubtitles(subtitleStream.Codec)
 14101598                    && !subtitleStream.IsPgsSubtitleStream
 14101599                    && !subtitleStream.IsVobSubSubtitleStream)
 1600                {
 1601                    continue;
 1602                }
 1603
 14081604                bool isVobSubMksProfile = IsVobSubMksProfile(profile, subtitleStream);
 1605
 14081606                if ((profile.Method == SubtitleDeliveryMethod.External
 14081607                        && (isVobSubMksProfile
 14081608                            || (!IsVobSubMksDeliveryProfile(profile) && subtitleStream.IsTextSubtitleStream == MediaStre
 14081609                    (profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream))
 1610                {
 13821611                    bool requiresConversion = !isVobSubMksProfile
 13821612                        && !string.Equals(subtitleStream.Codec, profile.Format, StringComparison.OrdinalIgnoreCase);
 1613
 13821614                    if (!requiresConversion)
 1615                    {
 1941616                        return profile;
 1617                    }
 1618
 11881619                    if (!allowConversion)
 1620                    {
 1621                        continue;
 1622                    }
 1623
 1624                    // TODO: Build this into subtitleStream.SupportsExternalStream
 2861625                    if (mediaSource.IsInfiniteStream)
 1626                    {
 1627                        continue;
 1628                    }
 1629
 2861630                    if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsExternalStream && subtitleStream.S
 1631                    {
 2861632                        return profile;
 1633                    }
 1634                }
 1635            }
 1636
 2961637            return null;
 1638        }
 1639
 1640        private static bool IsVobSubMksDeliveryProfile(SubtitleProfile profile)
 1641        {
 39091642            return MediaStream.IsVobSubFormat(profile.Format)
 39091643                && !string.IsNullOrWhiteSpace(profile.Container)
 39091644                && ContainerHelper.ContainsContainer(profile.Container, "mks");
 1645        }
 1646
 1647        private static bool IsVobSubMksProfile(SubtitleProfile profile, MediaStream subtitleStream)
 1648        {
 1649            // FFmpeg cannot mux VobSub back into an .idx/.sub pair, so extracted VobSub streams are exposed as .mks.
 19571650            return IsVobSubMksDeliveryProfile(profile)
 19571651                && subtitleStream.IsVobSubSubtitleStream
 19571652                && (!subtitleStream.IsExternal || subtitleStream.Path?.EndsWith(".mks", StringComparison.OrdinalIgnoreCa
 1653        }
 1654
 1655        private bool IsBitrateLimitExceeded(MediaSourceInfo item, long maxBitrate)
 1656        {
 1657            // Don't restrict bitrate if item is remote.
 2871658            if (item.IsRemote)
 1659            {
 51660                return false;
 1661            }
 1662
 1663            // If no maximum bitrate is set, default to no maximum bitrate.
 2821664            long requestedMaxBitrate = maxBitrate > 0 ? maxBitrate : int.MaxValue;
 1665
 1666            // If we don't know the item bitrate, then force a transcode if requested max bitrate is under 40 mbps
 2821667            int itemBitrate = item.Bitrate ?? 40000000;
 1668
 2821669            if (itemBitrate > requestedMaxBitrate)
 1670            {
 241671                _logger.LogDebug(
 241672                    "Bitrate exceeds limit: media bitrate: {MediaBitrate}, max bitrate: {MaxBitrate}",
 241673                    itemBitrate,
 241674                    requestedMaxBitrate);
 241675                return true;
 1676            }
 1677
 2581678            return false;
 1679        }
 1680
 1681        private static void ValidateMediaOptions(MediaOptions options, bool isMediaSource)
 1682        {
 2871683            if (options.ItemId.IsEmpty())
 1684            {
 01685                ArgumentException.ThrowIfNullOrEmpty(options.DeviceId);
 1686            }
 1687
 2871688            if (options.Profile is null)
 1689            {
 01690                throw new ArgumentException("Profile is required");
 1691            }
 1692
 2871693            if (options.MediaSources is null)
 1694            {
 01695                throw new ArgumentException("MediaSources is required");
 1696            }
 1697
 2871698            if (isMediaSource)
 1699            {
 2871700                if (options.AudioStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
 1701                {
 01702                    throw new ArgumentException("MediaSourceId is required when a specific audio stream is requested");
 1703                }
 1704
 2871705                if (options.SubtitleStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
 1706                {
 01707                    throw new ArgumentException("MediaSourceId is required when a specific subtitle stream is requested"
 1708                }
 1709            }
 2871710        }
 1711
 1712        private static IEnumerable<ProfileCondition> GetProfileConditionsForVideoAudio(
 1713            IEnumerable<CodecProfile> codecProfiles,
 1714            string container,
 1715            string codec,
 1716            int? audioChannels,
 1717            int? audioBitrate,
 1718            int? audioSampleRate,
 1719            int? audioBitDepth,
 1720            string audioProfile,
 1721            bool? isSecondaryAudio)
 1722        {
 10261723            return codecProfiles
 10261724                .Where(profile => profile.Type == CodecType.VideoAudio &&
 10261725                    profile.ContainsAnyCodec(codec, container) &&
 10261726                    profile.ApplyConditions.All(applyCondition => ConditionProcessor.IsVideoAudioConditionSatisfied(appl
 10261727                .SelectMany(profile => profile.Conditions)
 10261728                .Where(condition => !ConditionProcessor.IsVideoAudioConditionSatisfied(condition, audioChannels, audioBi
 1729        }
 1730
 1731        private static IEnumerable<ProfileCondition> GetProfileConditionsForAudio(
 1732            IEnumerable<CodecProfile> codecProfiles,
 1733            string container,
 1734            string? codec,
 1735            int? audioChannels,
 1736            int? audioBitrate,
 1737            int? audioSampleRate,
 1738            int? audioBitDepth,
 1739            bool checkConditions)
 1740        {
 01741            var conditions = codecProfiles
 01742                .Where(profile => profile.Type == CodecType.Audio &&
 01743                    profile.ContainsAnyCodec(codec, container) &&
 01744                    profile.ApplyConditions.All(applyCondition => ConditionProcessor.IsAudioConditionSatisfied(applyCond
 01745                .SelectMany(profile => profile.Conditions);
 1746
 01747            if (!checkConditions)
 1748            {
 01749                return conditions;
 1750            }
 1751
 01752            return conditions.Where(condition => !ConditionProcessor.IsAudioConditionSatisfied(condition, audioChannels,
 1753        }
 1754
 1755        private void ApplyTranscodingConditions(StreamInfo item, IEnumerable<ProfileCondition> conditions, string? quali
 1756        {
 36061757            foreach (ProfileCondition condition in conditions)
 1758            {
 12781759                string value = condition.Value;
 1760
 12781761                if (string.IsNullOrEmpty(value))
 1762                {
 1763                    continue;
 1764                }
 1765
 1766                // No way to express this
 12781767                if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 1768                {
 1769                    continue;
 1770                }
 1771
 12781772                switch (condition.Property)
 1773                {
 1774                    case ProfileConditionValue.AudioBitrate:
 1775                        {
 01776                            if (!enableNonQualifiedConditions)
 1777                            {
 1778                                continue;
 1779                            }
 1780
 01781                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 1782                            {
 01783                                if (condition.Condition == ProfileConditionType.Equals)
 1784                                {
 01785                                    item.AudioBitrate = num;
 1786                                }
 01787                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 1788                                {
 01789                                    item.AudioBitrate = Math.Min(num, item.AudioBitrate ?? num);
 1790                                }
 01791                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 1792                                {
 01793                                    item.AudioBitrate = Math.Max(num, item.AudioBitrate ?? num);
 1794                                }
 1795                            }
 1796
 01797                            break;
 1798                        }
 1799
 1800                    case ProfileConditionValue.AudioSampleRate:
 1801                        {
 01802                            if (!enableNonQualifiedConditions)
 1803                            {
 1804                                continue;
 1805                            }
 1806
 01807                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 1808                            {
 01809                                if (condition.Condition == ProfileConditionType.Equals)
 1810                                {
 01811                                    item.AudioSampleRate = num;
 1812                                }
 01813                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 1814                                {
 01815                                    item.AudioSampleRate = Math.Min(num, item.AudioSampleRate ?? num);
 1816                                }
 01817                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 1818                                {
 01819                                    item.AudioSampleRate = Math.Max(num, item.AudioSampleRate ?? num);
 1820                                }
 1821                            }
 1822
 01823                            break;
 1824                        }
 1825
 1826                    case ProfileConditionValue.AudioChannels:
 1827                        {
 281828                            if (string.IsNullOrEmpty(qualifier))
 1829                            {
 01830                                if (!enableNonQualifiedConditions)
 1831                                {
 01832                                    continue;
 1833                                }
 1834                            }
 1835                            else
 1836                            {
 281837                                if (!enableQualifiedConditions)
 1838                                {
 1839                                    continue;
 1840                                }
 1841                            }
 1842
 281843                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 1844                            {
 281845                                if (condition.Condition == ProfileConditionType.Equals)
 1846                                {
 01847                                    item.SetOption(qualifier, "audiochannels", num.ToString(CultureInfo.InvariantCulture
 1848                                }
 281849                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 1850                                {
 281851                                    item.SetOption(qualifier, "audiochannels", Math.Min(num, item.GetTargetAudioChannels
 1852                                }
 01853                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 1854                                {
 01855                                    item.SetOption(qualifier, "audiochannels", Math.Max(num, item.GetTargetAudioChannels
 1856                                }
 1857                            }
 1858
 01859                            break;
 1860                        }
 1861
 1862                    case ProfileConditionValue.IsAvc:
 1863                        {
 01864                            if (!enableNonQualifiedConditions)
 1865                            {
 1866                                continue;
 1867                            }
 1868
 01869                            if (bool.TryParse(value, out var isAvc))
 1870                            {
 01871                                if (isAvc && condition.Condition == ProfileConditionType.Equals)
 1872                                {
 01873                                    item.RequireAvc = true;
 1874                                }
 01875                                else if (!isAvc && condition.Condition == ProfileConditionType.NotEquals)
 1876                                {
 01877                                    item.RequireAvc = true;
 1878                                }
 1879                            }
 1880
 01881                            break;
 1882                        }
 1883
 1884                    case ProfileConditionValue.IsAnamorphic:
 1885                        {
 2071886                            if (!enableNonQualifiedConditions)
 1887                            {
 1888                                continue;
 1889                            }
 1890
 2071891                            if (bool.TryParse(value, out var isAnamorphic))
 1892                            {
 2071893                                if (isAnamorphic && condition.Condition == ProfileConditionType.Equals)
 1894                                {
 01895                                    item.RequireNonAnamorphic = true;
 1896                                }
 2071897                                else if (!isAnamorphic && condition.Condition == ProfileConditionType.NotEquals)
 1898                                {
 01899                                    item.RequireNonAnamorphic = true;
 1900                                }
 1901                            }
 1902
 01903                            break;
 1904                        }
 1905
 1906                    case ProfileConditionValue.IsInterlaced:
 1907                        {
 1131908                            if (string.IsNullOrEmpty(qualifier))
 1909                            {
 01910                                if (!enableNonQualifiedConditions)
 1911                                {
 01912                                    continue;
 1913                                }
 1914                            }
 1915                            else
 1916                            {
 1131917                                if (!enableQualifiedConditions)
 1918                                {
 1919                                    continue;
 1920                                }
 1921                            }
 1922
 1131923                            if (bool.TryParse(value, out var isInterlaced))
 1924                            {
 1131925                                if (!isInterlaced && condition.Condition == ProfileConditionType.Equals)
 1926                                {
 01927                                    item.SetOption(qualifier, "deinterlace", "true");
 1928                                }
 1131929                                else if (isInterlaced && condition.Condition == ProfileConditionType.NotEquals)
 1930                                {
 1131931                                    item.SetOption(qualifier, "deinterlace", "true");
 1932                                }
 1933                            }
 1934
 1131935                            break;
 1936                        }
 1937
 1938                    case ProfileConditionValue.AudioProfile:
 1939                    case ProfileConditionValue.Has64BitOffsets:
 1940                    case ProfileConditionValue.PacketLength:
 1941                    case ProfileConditionValue.NumStreams:
 1942                    case ProfileConditionValue.NumAudioStreams:
 1943                    case ProfileConditionValue.NumVideoStreams:
 1944                    case ProfileConditionValue.IsSecondaryAudio:
 1945                    case ProfileConditionValue.VideoTimestamp:
 1946                        {
 1947                            // Not supported yet
 1948                            break;
 1949                        }
 1950
 1951                    case ProfileConditionValue.RefFrames:
 1952                        {
 21953                            if (string.IsNullOrEmpty(qualifier))
 1954                            {
 01955                                if (!enableNonQualifiedConditions)
 1956                                {
 01957                                    continue;
 1958                                }
 1959                            }
 1960                            else
 1961                            {
 21962                                if (!enableQualifiedConditions)
 1963                                {
 1964                                    continue;
 1965                                }
 1966                            }
 1967
 21968                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 1969                            {
 21970                                if (condition.Condition == ProfileConditionType.Equals)
 1971                                {
 01972                                    item.SetOption(qualifier, "maxrefframes", num.ToString(CultureInfo.InvariantCulture)
 1973                                }
 21974                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 1975                                {
 21976                                    item.SetOption(qualifier, "maxrefframes", Math.Min(num, item.GetTargetRefFrames(qual
 1977                                }
 01978                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 1979                                {
 01980                                    item.SetOption(qualifier, "maxrefframes", Math.Max(num, item.GetTargetRefFrames(qual
 1981                                }
 1982                            }
 1983
 01984                            break;
 1985                        }
 1986
 1987                    case ProfileConditionValue.VideoBitDepth:
 1988                        {
 01989                            if (string.IsNullOrEmpty(qualifier))
 1990                            {
 01991                                if (!enableNonQualifiedConditions)
 1992                                {
 01993                                    continue;
 1994                                }
 1995                            }
 1996                            else
 1997                            {
 01998                                if (!enableQualifiedConditions)
 1999                                {
 2000                                    continue;
 2001                                }
 2002                            }
 2003
 02004                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 2005                            {
 02006                                if (condition.Condition == ProfileConditionType.Equals)
 2007                                {
 02008                                    item.SetOption(qualifier, "videobitdepth", num.ToString(CultureInfo.InvariantCulture
 2009                                }
 02010                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 2011                                {
 02012                                    item.SetOption(qualifier, "videobitdepth", Math.Min(num, item.GetTargetVideoBitDepth
 2013                                }
 02014                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 2015                                {
 02016                                    item.SetOption(qualifier, "videobitdepth", Math.Max(num, item.GetTargetVideoBitDepth
 2017                                }
 2018                            }
 2019
 02020                            break;
 2021                        }
 2022
 2023                    case ProfileConditionValue.VideoProfile:
 2024                        {
 2302025                            if (string.IsNullOrEmpty(qualifier))
 2026                            {
 2027                                continue;
 2028                            }
 2029
 2030                            // Change from split by | to comma
 2031                            // Strip spaces to avoid having to encode
 2302032                            var values = value
 2302033                                .Split('|', StringSplitOptions.RemoveEmptyEntries);
 2034
 2302035                            if (condition.Condition == ProfileConditionType.Equals)
 2036                            {
 02037                                item.SetOption(qualifier, "profile", string.Join(',', values));
 2038                            }
 2302039                            else if (condition.Condition == ProfileConditionType.EqualsAny)
 2040                            {
 2302041                                var currentValue = item.GetOption(qualifier, "profile");
 2302042                                if (!string.IsNullOrEmpty(currentValue) && values.Any(value => value == currentValue))
 2043                                {
 732044                                    item.SetOption(qualifier, "profile", currentValue);
 2045                                }
 2046                                else
 2047                                {
 1572048                                    item.SetOption(qualifier, "profile", string.Join(',', values));
 2049                                }
 2050                            }
 2051
 1572052                            break;
 2053                        }
 2054
 2055                    case ProfileConditionValue.VideoRangeType:
 2056                        {
 2662057                            if (string.IsNullOrEmpty(qualifier))
 2058                            {
 2059                                continue;
 2060                            }
 2061
 2062                            // change from split by | to comma
 2063                            // strip spaces to avoid having to encode
 2662064                            var values = value
 2662065                                .Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 2066
 2662067                            if (condition.Condition == ProfileConditionType.Equals)
 2068                            {
 02069                                item.SetOption(qualifier, "rangetype", string.Join(',', values));
 2070                            }
 2662071                            else if (condition.Condition == ProfileConditionType.NotEquals)
 2072                            {
 02073                                item.SetOption(qualifier, "rangetype", string.Join(',', Enum.GetNames<VideoRangeType>().
 2074                            }
 2662075                            else if (condition.Condition == ProfileConditionType.EqualsAny)
 2076                            {
 2662077                                var currentValue = item.GetOption(qualifier, "rangetype");
 2662078                                if (!string.IsNullOrEmpty(currentValue) && values.Any(v => string.Equals(v, currentValue
 2079                                {
 02080                                    item.SetOption(qualifier, "rangetype", currentValue);
 2081                                }
 2082                                else
 2083                                {
 2662084                                    item.SetOption(qualifier, "rangetype", string.Join(',', values));
 2085                                }
 2086                            }
 2087
 2662088                            break;
 2089                        }
 2090
 2091                    case ProfileConditionValue.VideoCodecTag:
 2092                        {
 122093                            if (string.IsNullOrEmpty(qualifier))
 2094                            {
 2095                                continue;
 2096                            }
 2097
 2098                            // change from split by | to comma
 2099                            // strip spaces to avoid having to encode
 122100                            var values = value
 122101                                .Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 2102
 122103                            if (condition.Condition == ProfileConditionType.Equals)
 2104                            {
 02105                                item.SetOption(qualifier, "codectag", string.Join(',', values));
 2106                            }
 122107                            else if (condition.Condition == ProfileConditionType.EqualsAny)
 2108                            {
 122109                                var currentValue = item.GetOption(qualifier, "codectag");
 122110                                if (!string.IsNullOrEmpty(currentValue) && values.Any(v => string.Equals(v, currentValue
 2111                                {
 02112                                    item.SetOption(qualifier, "codectag", currentValue);
 2113                                }
 2114                                else
 2115                                {
 122116                                    item.SetOption(qualifier, "codectag", string.Join(',', values));
 2117                                }
 2118                            }
 2119
 122120                            break;
 2121                        }
 2122
 2123                    case ProfileConditionValue.VideoRotation:
 2124                        {
 02125                            if (string.IsNullOrEmpty(qualifier))
 2126                            {
 2127                                continue;
 2128                            }
 2129
 2130                            // change from split by | to comma
 2131                            // strip spaces to avoid having to encode
 02132                            var values = value
 02133                                .Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
 2134
 02135                            if (condition.Condition == ProfileConditionType.Equals)
 2136                            {
 02137                                item.SetOption(qualifier, "rotation", string.Join(',', values));
 2138                            }
 02139                            else if (condition.Condition == ProfileConditionType.EqualsAny)
 2140                            {
 02141                                var currentValue = item.GetOption(qualifier, "rotation");
 02142                                if (!string.IsNullOrEmpty(currentValue) && values.Any(v => string.Equals(v, currentValue
 2143                                {
 02144                                    item.SetOption(qualifier, "rotation", currentValue);
 2145                                }
 2146                                else
 2147                                {
 02148                                    item.SetOption(qualifier, "rotation", string.Join(',', values));
 2149                                }
 2150                            }
 2151
 02152                            break;
 2153                        }
 2154
 2155                    case ProfileConditionValue.Height:
 2156                        {
 02157                            if (!enableNonQualifiedConditions)
 2158                            {
 2159                                continue;
 2160                            }
 2161
 02162                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 2163                            {
 02164                                if (condition.Condition == ProfileConditionType.Equals)
 2165                                {
 02166                                    item.MaxHeight = num;
 2167                                }
 02168                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 2169                                {
 02170                                    item.MaxHeight = Math.Min(num, item.MaxHeight ?? num);
 2171                                }
 02172                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 2173                                {
 02174                                    item.MaxHeight = Math.Max(num, item.MaxHeight ?? num);
 2175                                }
 2176                            }
 2177
 02178                            break;
 2179                        }
 2180
 2181                    case ProfileConditionValue.VideoBitrate:
 2182                        {
 322183                            if (!enableNonQualifiedConditions)
 2184                            {
 2185                                continue;
 2186                            }
 2187
 322188                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 2189                            {
 322190                                if (condition.Condition == ProfileConditionType.Equals)
 2191                                {
 02192                                    item.VideoBitrate = num;
 2193                                }
 322194                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 2195                                {
 322196                                    item.VideoBitrate = Math.Min(num, item.VideoBitrate ?? num);
 2197                                }
 02198                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 2199                                {
 02200                                    item.VideoBitrate = Math.Max(num, item.VideoBitrate ?? num);
 2201                                }
 2202                            }
 2203
 02204                            break;
 2205                        }
 2206
 2207                    case ProfileConditionValue.VideoFramerate:
 2208                        {
 122209                            if (!enableNonQualifiedConditions)
 2210                            {
 2211                                continue;
 2212                            }
 2213
 122214                            if (float.TryParse(value, CultureInfo.InvariantCulture, out var num))
 2215                            {
 122216                                if (condition.Condition == ProfileConditionType.Equals)
 2217                                {
 02218                                    item.MaxFramerate = num;
 2219                                }
 122220                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 2221                                {
 122222                                    item.MaxFramerate = Math.Min(num, item.MaxFramerate ?? num);
 2223                                }
 02224                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 2225                                {
 02226                                    item.MaxFramerate = Math.Max(num, item.MaxFramerate ?? num);
 2227                                }
 2228                            }
 2229
 02230                            break;
 2231                        }
 2232
 2233                    case ProfileConditionValue.VideoLevel:
 2234                        {
 2182235                            if (string.IsNullOrEmpty(qualifier))
 2236                            {
 2237                                continue;
 2238                            }
 2239
 2182240                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 2241                            {
 2182242                                if (condition.Condition == ProfileConditionType.Equals)
 2243                                {
 02244                                    item.SetOption(qualifier, "level", num.ToString(CultureInfo.InvariantCulture));
 2245                                }
 2182246                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 2247                                {
 2182248                                    item.SetOption(qualifier, "level", Math.Min(num, item.GetTargetVideoLevel(qualifier)
 2249                                }
 02250                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 2251                                {
 02252                                    item.SetOption(qualifier, "level", Math.Max(num, item.GetTargetVideoLevel(qualifier)
 2253                                }
 2254                            }
 2255
 02256                            break;
 2257                        }
 2258
 2259                    case ProfileConditionValue.Width:
 2260                        {
 42261                            if (!enableNonQualifiedConditions)
 2262                            {
 2263                                continue;
 2264                            }
 2265
 42266                            if (int.TryParse(value, CultureInfo.InvariantCulture, out var num))
 2267                            {
 42268                                if (condition.Condition == ProfileConditionType.Equals)
 2269                                {
 02270                                    item.MaxWidth = num;
 2271                                }
 42272                                else if (condition.Condition == ProfileConditionType.LessThanEqual)
 2273                                {
 42274                                    item.MaxWidth = Math.Min(num, item.MaxWidth ?? num);
 2275                                }
 02276                                else if (condition.Condition == ProfileConditionType.GreaterThanEqual)
 2277                                {
 02278                                    item.MaxWidth = Math.Max(num, item.MaxWidth ?? num);
 2279                                }
 2280                            }
 2281
 2282                            break;
 2283                        }
 2284
 2285                    default:
 2286                        break;
 2287                }
 2288            }
 5252289        }
 2290
 2291        private static bool IsAudioContainerSupported(DirectPlayProfile profile, MediaSourceInfo item)
 2292        {
 2293            // Check container type
 02294            if (!profile.SupportsContainer(item.Container))
 2295            {
 02296                return false;
 2297            }
 2298
 2299            // Never direct play audio in matroska when the device only declare support for webm.
 2300            // The first check is not enough because mkv is assumed can be webm.
 2301            // See https://github.com/jellyfin/jellyfin/issues/13344
 02302            return !ContainerHelper.ContainsContainer("mkv", item.Container)
 02303                   || profile.SupportsContainer("mkv");
 2304        }
 2305
 2306        private static bool IsAudioDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream audi
 2307        {
 02308            if (!IsAudioContainerSupported(profile, item))
 2309            {
 02310                return false;
 2311            }
 2312
 2313            // Check audio codec
 02314            string? audioCodec = audioStream?.Codec;
 02315            if (!profile.SupportsAudioCodec(audioCodec))
 2316            {
 02317                return false;
 2318            }
 2319
 02320            return true;
 2321        }
 2322
 2323        private static bool IsAudioDirectStreamSupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream au
 2324        {
 2325            // Check container type, this should NOT be supported
 2326            // If the container is supported, the file should be directly played
 02327            if (IsAudioContainerSupported(profile, item))
 2328            {
 02329                return false;
 2330            }
 2331
 2332            // Check audio codec, we cannot use the SupportsAudioCodec here
 2333            // Because that one assumes empty container supports all codec, which is just useless
 02334            string? audioCodec = audioStream?.Codec;
 02335            return string.Equals(profile.AudioCodec, audioCodec, StringComparison.OrdinalIgnoreCase)
 02336                   || string.Equals(profile.Container, audioCodec, StringComparison.OrdinalIgnoreCase);
 2337        }
 2338
 2339        private int GetRank(ref TranscodeReason a, TranscodeReason[] rankings)
 2340        {
 12222341            var index = 1;
 88472342            foreach (var flag in rankings)
 2343            {
 37122344                var reason = a & flag;
 37122345                if (reason != 0)
 2346                {
 10212347                    return index;
 2348                }
 2349
 26912350                index++;
 2351            }
 2352
 2012353            return index;
 2354        }
 2355
 2356        /// <summary>
 2357        /// Check the profile conditions.
 2358        /// </summary>
 2359        /// <param name="conditions">Profile conditions.</param>
 2360        /// <param name="mediaSource">Media source.</param>
 2361        /// <param name="videoStream">Video stream.</param>
 2362        /// <returns>Failed profile conditions.</returns>
 2363        private IEnumerable<ProfileCondition> CheckVideoConditions(ProfileCondition[] conditions, MediaSourceInfo mediaS
 2364        {
 7432365            int? width = videoStream?.Width;
 7432366            int? height = videoStream?.Height;
 7432367            int? bitDepth = videoStream?.BitDepth;
 7432368            int? videoBitrate = videoStream?.BitRate;
 7432369            double? videoLevel = videoStream?.Level;
 7432370            string? videoProfile = videoStream?.Profile;
 7432371            VideoRangeType? videoRangeType = videoStream?.VideoRangeType;
 7432372            float videoFramerate = videoStream is null ? 0 : videoStream.ReferenceFrameRate ?? 0;
 7432373            bool? isAnamorphic = videoStream?.IsAnamorphic;
 7432374            bool? isInterlaced = videoStream?.IsInterlaced;
 7432375            string? videoCodecTag = videoStream?.CodecTag;
 7432376            bool? isAvc = videoStream?.IsAVC;
 7432377            int? videoRotation = videoStream?.Rotation;
 2378
 7432379            TransportStreamTimestamp? timestamp = videoStream is null ? TransportStreamTimestamp.None : mediaSource.Time
 7432380            int? packetLength = videoStream?.PacketLength;
 7432381            int? refFrames = videoStream?.RefFrames;
 2382
 7432383            int numStreams = mediaSource.MediaStreams.Count;
 7432384            int? numAudioStreams = mediaSource.GetStreamCount(MediaStreamType.Audio);
 7432385            int? numVideoStreams = mediaSource.GetStreamCount(MediaStreamType.Video);
 2386
 7432387            return conditions.Where(applyCondition => !ConditionProcessor.IsVideoConditionSatisfied(applyCondition, widt
 2388        }
 2389
 2390        /// <summary>
 2391        /// Check the compatibility of the container.
 2392        /// </summary>
 2393        /// <param name="options">Media options.</param>
 2394        /// <param name="mediaSource">Media source.</param>
 2395        /// <param name="container">Container.</param>
 2396        /// <param name="videoStream">Video stream.</param>
 2397        /// <returns>Transcode reasons if the container is not fully compatible.</returns>
 2398        private TranscodeReason GetCompatibilityContainer(MediaOptions options, MediaSourceInfo mediaSource, string cont
 2399        {
 2592400            var profile = options.Profile;
 2401
 2592402            var failures = AggregateFailureConditions(
 2592403                mediaSource,
 2592404                profile,
 2592405                "VideoCodecProfile",
 2592406                profile.ContainerProfiles
 2592407                    .Where(containerProfile => containerProfile.Type == DlnaProfileType.Video && containerProfile.Contai
 2592408                    .SelectMany(containerProfile => CheckVideoConditions(containerProfile.Conditions, mediaSource, video
 2409
 2592410            return failures;
 2411        }
 2412
 2413        /// <summary>
 2414        /// Check the compatibility of the video codec.
 2415        /// </summary>
 2416        /// <param name="options">Media options.</param>
 2417        /// <param name="mediaSource">Media source.</param>
 2418        /// <param name="container">Container.</param>
 2419        /// <param name="videoStream">Video stream.</param>
 2420        /// <returns>Transcode reasons if the video stream is not fully compatible.</returns>
 2421        private TranscodeReason GetCompatibilityVideoCodec(MediaOptions options, MediaSourceInfo mediaSource, string con
 2422        {
 4152423            var profile = options.Profile;
 2424
 4152425            string videoCodec = videoStream.Codec;
 2426
 4152427            var failures = AggregateFailureConditions(
 4152428                mediaSource,
 4152429                profile,
 4152430                "VideoCodecProfile",
 4152431                profile.CodecProfiles
 4152432                    .Where(codecProfile => codecProfile.Type == CodecType.Video &&
 4152433                        codecProfile.ContainsAnyCodec(videoCodec, container) &&
 4152434                        !CheckVideoConditions(codecProfile.ApplyConditions, mediaSource, videoStream).Any())
 4152435                    .SelectMany(codecProfile => CheckVideoConditions(codecProfile.Conditions, mediaSource, videoStream))
 2436
 4152437            return failures;
 2438        }
 2439
 2440        /// <summary>
 2441        /// Check the compatibility of the audio codec.
 2442        /// </summary>
 2443        /// <param name="options">Media options.</param>
 2444        /// <param name="mediaSource">Media source.</param>
 2445        /// <param name="container">Container.</param>
 2446        /// <param name="audioStream">Audio stream.</param>
 2447        /// <param name="transcodingAudioCodec">Override audio codec.</param>
 2448        /// <param name="isVideo">The media source is video.</param>
 2449        /// <param name="isSecondaryAudio">The audio stream is secondary.</param>
 2450        /// <returns>Transcode reasons if the audio stream is not fully compatible.</returns>
 2451        private TranscodeReason GetCompatibilityAudioCodec(MediaOptions options, MediaSourceInfo mediaSource, string con
 2452        {
 10262453            var profile = options.Profile;
 2454
 10262455            var audioCodec = transcodingAudioCodec ?? audioStream.Codec;
 10262456            var audioProfile = audioStream.Profile;
 10262457            var audioChannels = audioStream.Channels;
 10262458            var audioBitrate = audioStream.BitRate;
 10262459            var audioSampleRate = audioStream.SampleRate;
 10262460            var audioBitDepth = audioStream.BitDepth;
 2461
 10262462            var audioFailureConditions = isVideo
 10262463                ? GetProfileConditionsForVideoAudio(profile.CodecProfiles, container, audioCodec, audioChannels, audioBi
 10262464                : GetProfileConditionsForAudio(profile.CodecProfiles, container, audioCodec, audioChannels, audioBitrate
 2465
 10262466            var failures = AggregateFailureConditions(mediaSource, profile, "AudioCodecProfile", audioFailureConditions)
 2467
 10262468            return failures;
 2469        }
 2470
 2471        /// <summary>
 2472        /// Check the compatibility of the audio codec for direct playback.
 2473        /// </summary>
 2474        /// <param name="options">Media options.</param>
 2475        /// <param name="mediaSource">Media source.</param>
 2476        /// <param name="container">Container.</param>
 2477        /// <param name="audioStream">Audio stream.</param>
 2478        /// <param name="isVideo">The media source is video.</param>
 2479        /// <param name="isSecondaryAudio">The audio stream is secondary.</param>
 2480        /// <returns>Transcode reasons if the audio stream is not fully compatible for direct playback.</returns>
 2481        private TranscodeReason GetCompatibilityAudioCodecDirect(MediaOptions options, MediaSourceInfo mediaSource, stri
 2482        {
 2782483            var failures = GetCompatibilityAudioCodec(options, mediaSource, container, audioStream, null, isVideo, isSec
 2484
 2782485            if (audioStream.IsExternal)
 2486            {
 62487                failures |= TranscodeReason.AudioIsExternal;
 2488            }
 2489
 2782490            return failures;
 2491        }
 2492    }
 2493}

Methods/Properties

.cctor()
.ctor(MediaBrowser.Model.Dlna.ITranscoderSupport,Microsoft.Extensions.Logging.ILogger)
GetOptimalAudioStream(MediaBrowser.Model.Dlna.MediaOptions)
GetOptimalAudioStream(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.MediaOptions)
GetOptimalVideoStream(MediaBrowser.Model.Dlna.MediaOptions)
GetOptimalStream(System.Collections.Generic.List`1<MediaBrowser.Model.Dlna.StreamInfo>,System.Int64)
SortMediaSources(System.Collections.Generic.List`1<MediaBrowser.Model.Dlna.StreamInfo>,System.Int64)
GetTranscodeReasonForFailedCondition(MediaBrowser.Model.Dlna.ProfileCondition)
NormalizeMediaSourceFormatIntoSingleContainer(System.String,MediaBrowser.Model.Dlna.DeviceProfile,MediaBrowser.Model.Dlna.DlnaProfileType,MediaBrowser.Model.Dlna.DirectPlayProfile)
GetAudioDirectPlayProfile(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Dlna.MediaOptions)
GetTranscodeReasonsFromDirectPlayProfile(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Entities.MediaStream,System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Dlna.DirectPlayProfile>)
GetDefaultSubtitleStreamIndex(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.SubtitleProfile[])
SetStreamInfoOptionsFromTranscodingProfile(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.StreamInfo,MediaBrowser.Model.Dlna.TranscodingProfile)
SetStreamInfoOptionsFromDirectPlayProfile(MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.StreamInfo,MediaBrowser.Model.Dlna.DirectPlayProfile)
BuildVideoItem(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.MediaOptions)
GetVideoTranscodeProfile(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Dlna.StreamInfo)
BuildStreamVideoItem(MediaBrowser.Model.Dlna.StreamInfo,MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Entities.MediaStream,System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Entities.MediaStream>,System.String,System.String,System.String)
GetDefaultAudioBitrate(System.String,System.Nullable`1<System.Int32>)
GetAudioBitrate(System.Int64,System.Collections.Generic.IReadOnlyList`1<System.String>,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Dlna.StreamInfo)
GetMaxAudioBitrateForTotalBitrate(System.Int64)
GetVideoDirectPlayProfile(MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Entities.MediaStream,System.Collections.Generic.ICollection`1<MediaBrowser.Model.Entities.MediaStream>,MediaBrowser.Model.Entities.MediaStream,System.Boolean,System.Boolean)
AggregateFailureConditions(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Dlna.DeviceProfile,System.String,System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Dlna.ProfileCondition>)
LogConditionFailure(MediaBrowser.Model.Dlna.DeviceProfile,System.String,MediaBrowser.Model.Dlna.ProfileCondition,MediaBrowser.Model.Dto.MediaSourceInfo)
GetSubtitleProfile(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Dlna.SubtitleProfile[],MediaBrowser.Model.Session.PlayMethod,MediaBrowser.Model.Dlna.ITranscoderSupport,System.String,System.Nullable`1<Jellyfin.Data.Enums.MediaStreamProtocol>)
IsSubtitleEmbedSupported(System.String)
CanConsiderEmbedSubtitle(MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Session.PlayMethod,System.Nullable`1<Jellyfin.Data.Enums.MediaStreamProtocol>,System.String)
GetExternalSubtitleProfile(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream,MediaBrowser.Model.Dlna.SubtitleProfile[],MediaBrowser.Model.Session.PlayMethod,MediaBrowser.Model.Dlna.ITranscoderSupport,System.Boolean)
IsVobSubMksDeliveryProfile(MediaBrowser.Model.Dlna.SubtitleProfile)
IsVobSubMksProfile(MediaBrowser.Model.Dlna.SubtitleProfile,MediaBrowser.Model.Entities.MediaStream)
IsBitrateLimitExceeded(MediaBrowser.Model.Dto.MediaSourceInfo,System.Int64)
ValidateMediaOptions(MediaBrowser.Model.Dlna.MediaOptions,System.Boolean)
GetProfileConditionsForVideoAudio(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Dlna.CodecProfile>,System.String,System.String,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.String,System.Nullable`1<System.Boolean>)
GetProfileConditionsForAudio(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Dlna.CodecProfile>,System.String,System.String,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.Nullable`1<System.Int32>,System.Boolean)
ApplyTranscodingConditions(MediaBrowser.Model.Dlna.StreamInfo,System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Dlna.ProfileCondition>,System.String,System.Boolean,System.Boolean)
IsAudioContainerSupported(MediaBrowser.Model.Dlna.DirectPlayProfile,MediaBrowser.Model.Dto.MediaSourceInfo)
IsAudioDirectPlaySupported(MediaBrowser.Model.Dlna.DirectPlayProfile,MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream)
IsAudioDirectStreamSupported(MediaBrowser.Model.Dlna.DirectPlayProfile,MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream)
GetRank(MediaBrowser.Model.Session.TranscodeReason&,MediaBrowser.Model.Session.TranscodeReason[])
CheckVideoConditions(MediaBrowser.Model.Dlna.ProfileCondition[],MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Model.Entities.MediaStream)
GetCompatibilityContainer(MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,System.String,MediaBrowser.Model.Entities.MediaStream)
GetCompatibilityVideoCodec(MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,System.String,MediaBrowser.Model.Entities.MediaStream)
GetCompatibilityAudioCodec(MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,System.String,MediaBrowser.Model.Entities.MediaStream,System.String,System.Boolean,System.Boolean)
GetCompatibilityAudioCodecDirect(MediaBrowser.Model.Dlna.MediaOptions,MediaBrowser.Model.Dto.MediaSourceInfo,System.String,MediaBrowser.Model.Entities.MediaStream,System.Boolean,System.Boolean)