Files
jellyfin/MediaBrowser.Model/Dlna/ResolutionNormalizer.cs

86 lines
2.9 KiB
C#
Raw Permalink Normal View History

#nullable disable
2020-02-04 01:49:27 +01:00
#pragma warning disable CS1591
using System;
using System.Linq;
2018-12-27 18:27:57 -05:00
namespace MediaBrowser.Model.Dlna
{
2021-09-09 15:59:13 +02:00
public static class ResolutionNormalizer
2018-12-27 18:27:57 -05:00
{
// Please note: all bitrate here are in the scale of SDR h264 bitrate at 30fps
private static readonly ResolutionConfiguration[] _configurations =
[
new ResolutionConfiguration(416, 365000),
new ResolutionConfiguration(640, 730000),
new ResolutionConfiguration(768, 1100000),
new ResolutionConfiguration(960, 3000000),
new ResolutionConfiguration(1280, 6000000),
new ResolutionConfiguration(1920, 13500000),
new ResolutionConfiguration(2560, 28000000),
new ResolutionConfiguration(3840, 50000000)
];
2018-12-27 18:27:57 -05:00
public static ResolutionOptions Normalize(
int? inputBitrate,
2018-12-27 22:43:48 +01:00
int outputBitrate,
int h264EquivalentOutputBitrate,
2018-12-27 18:27:57 -05:00
int? maxWidth,
int? maxHeight,
float? targetFps,
bool isHdr = false) // We are not doing HDR transcoding for now, leave for future use
2018-12-27 18:27:57 -05:00
{
2020-11-18 13:46:14 +00:00
// If the bitrate isn't changing, then don't downscale the resolution
2018-12-27 22:43:48 +01:00
if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value)
{
if (maxWidth.HasValue || maxHeight.HasValue)
{
return new ResolutionOptions
{
MaxWidth = maxWidth,
MaxHeight = maxHeight
};
}
}
2018-12-27 18:27:57 -05:00
// Our reference bitrate is based on SDR h264 at 30fps
var referenceFps = targetFps ?? 30.0f;
var referenceScale = referenceFps <= 30.0f
? 30.0f / referenceFps
: 1.0f / MathF.Sqrt(referenceFps / 30.0f);
var referenceBitrate = h264EquivalentOutputBitrate * referenceScale;
if (isHdr)
2018-12-27 18:27:57 -05:00
{
referenceBitrate *= 0.8f;
}
2018-12-27 18:27:57 -05:00
var resolutionConfig = GetResolutionConfiguration(Convert.ToInt32(referenceBitrate));
if (resolutionConfig is null)
{
return new ResolutionOptions { MaxWidth = maxWidth, MaxHeight = maxHeight };
}
var originWidthValue = maxWidth;
maxWidth = Math.Min(resolutionConfig.MaxWidth, maxWidth ?? resolutionConfig.MaxWidth);
if (!originWidthValue.HasValue || originWidthValue.Value != maxWidth.Value)
{
maxHeight = null;
2018-12-27 18:27:57 -05:00
}
return new ResolutionOptions
{
MaxWidth = maxWidth,
MaxHeight = maxHeight
};
}
private static ResolutionConfiguration GetResolutionConfiguration(int outputBitrate)
{
return _configurations.FirstOrDefault(config => outputBitrate <= config.MaxBitrate);
2018-12-27 18:27:57 -05:00
}
}
}