104 lines
2.8 KiB
C#
104 lines
2.8 KiB
C#
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using EmbyToolbox.Models;
|
|
|
|
namespace EmbyToolbox.Services;
|
|
|
|
public static class VideoBitratePolicy
|
|
{
|
|
public const string Auto = "Auto";
|
|
public const string Source = "Source";
|
|
public const string Custom = "Custom";
|
|
|
|
public static IReadOnlyList<string> UiOptions { get; } =
|
|
[
|
|
Auto,
|
|
Source,
|
|
"2 Mbps",
|
|
"3 Mbps",
|
|
"4 Mbps",
|
|
"6 Mbps",
|
|
"8 Mbps",
|
|
"10 Mbps",
|
|
"12 Mbps",
|
|
"15 Mbps",
|
|
"20 Mbps",
|
|
Custom
|
|
];
|
|
|
|
public static string NormalizeMode(string? mode) =>
|
|
mode switch
|
|
{
|
|
Source => Source,
|
|
Custom => Custom,
|
|
_ => TryParseFixedModeKbps(mode) is { } fixedKbps
|
|
? $"{fixedKbps / 1000.0:0.###} Mbps".Replace(".000", string.Empty, StringComparison.Ordinal)
|
|
: Auto
|
|
};
|
|
|
|
public static int? ResolveTargetKbps(string? mode, double? customMbps, MediaAnalysisResult? media)
|
|
{
|
|
var normalized = NormalizeMode(mode);
|
|
if (normalized == Auto)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (normalized == Source)
|
|
{
|
|
return media?.SourceVideoBitrateBps is { } bps && bps > 0
|
|
? Math.Max(1, (int)Math.Round(bps / 1000.0, MidpointRounding.AwayFromZero))
|
|
: null;
|
|
}
|
|
|
|
if (normalized == Custom)
|
|
{
|
|
return customMbps is { } mbps && mbps > 0
|
|
? Math.Max(1, (int)Math.Round(mbps * 1000.0, MidpointRounding.AwayFromZero))
|
|
: null;
|
|
}
|
|
|
|
return TryParseFixedModeKbps(normalized);
|
|
}
|
|
|
|
public static int? TryParseFixedModeKbps(string? mode)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(mode))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var m = mode.Trim();
|
|
if (m.Equals(Auto, StringComparison.OrdinalIgnoreCase)
|
|
|| m.Equals(Source, StringComparison.OrdinalIgnoreCase)
|
|
|| m.Equals(Custom, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (!m.EndsWith("Mbps", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var number = m[..^4].Trim();
|
|
if (!double.TryParse(number.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture, out var mbps) || mbps <= 0)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return Math.Max(1, (int)Math.Round(mbps * 1000.0, MidpointRounding.AwayFromZero));
|
|
}
|
|
|
|
public static string FormatCurrentSource(long? bps)
|
|
{
|
|
if (bps is not { } value || value <= 0)
|
|
{
|
|
return "Текущее: неизвестно";
|
|
}
|
|
|
|
var mbps = value / 1_000_000d;
|
|
return $"Текущее: {mbps:0.###} Mbps";
|
|
}
|
|
}
|