ResolutionNormalizer.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Linq;
  5. namespace MediaBrowser.Model.Dlna
  6. {
  7. public static class ResolutionNormalizer
  8. {
  9. // Please note: all bitrate here are in the scale of SDR h264 bitrate at 30fps
  10. private static readonly ResolutionConfiguration[] _configurations =
  11. [
  12. new ResolutionConfiguration(416, 365000),
  13. new ResolutionConfiguration(640, 730000),
  14. new ResolutionConfiguration(768, 1100000),
  15. new ResolutionConfiguration(960, 3000000),
  16. new ResolutionConfiguration(1280, 6000000),
  17. new ResolutionConfiguration(1920, 13500000),
  18. new ResolutionConfiguration(2560, 28000000),
  19. new ResolutionConfiguration(3840, 50000000)
  20. ];
  21. public static ResolutionOptions Normalize(
  22. int? inputBitrate,
  23. int outputBitrate,
  24. int h264EquivalentOutputBitrate,
  25. int? maxWidth,
  26. int? maxHeight,
  27. float? targetFps,
  28. bool isHdr = false) // We are not doing HDR transcoding for now, leave for future use
  29. {
  30. // If the bitrate isn't changing, then don't downscale the resolution
  31. if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value)
  32. {
  33. if (maxWidth.HasValue || maxHeight.HasValue)
  34. {
  35. return new ResolutionOptions
  36. {
  37. MaxWidth = maxWidth,
  38. MaxHeight = maxHeight
  39. };
  40. }
  41. }
  42. var referenceBitrate = h264EquivalentOutputBitrate * (30.0f / (targetFps ?? 30.0f));
  43. if (isHdr)
  44. {
  45. referenceBitrate *= 0.8f;
  46. }
  47. var resolutionConfig = GetResolutionConfiguration(Convert.ToInt32(referenceBitrate));
  48. if (resolutionConfig is null)
  49. {
  50. return new ResolutionOptions { MaxWidth = maxWidth, MaxHeight = maxHeight };
  51. }
  52. var originWidthValue = maxWidth;
  53. maxWidth = Math.Min(resolutionConfig.MaxWidth, maxWidth ?? resolutionConfig.MaxWidth);
  54. if (!originWidthValue.HasValue || originWidthValue.Value != maxWidth.Value)
  55. {
  56. maxHeight = null;
  57. }
  58. return new ResolutionOptions
  59. {
  60. MaxWidth = maxWidth,
  61. MaxHeight = maxHeight
  62. };
  63. }
  64. private static ResolutionConfiguration GetResolutionConfiguration(int outputBitrate)
  65. {
  66. return _configurations.FirstOrDefault(config => outputBitrate <= config.MaxBitrate);
  67. }
  68. }
  69. }