ResolutionNormalizer.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using MediaBrowser.Model.Extensions;
  3. namespace MediaBrowser.Model.Dlna
  4. {
  5. public class ResolutionNormalizer
  6. {
  7. private static readonly ResolutionConfiguration[] Configurations =
  8. new[]
  9. {
  10. new ResolutionConfiguration(426, 320000),
  11. new ResolutionConfiguration(640, 400000),
  12. new ResolutionConfiguration(720, 950000),
  13. new ResolutionConfiguration(1280, 2500000),
  14. new ResolutionConfiguration(1920, 4000000),
  15. new ResolutionConfiguration(3840, 35000000)
  16. };
  17. public static ResolutionOptions Normalize(int? inputBitrate,
  18. int? unused1,
  19. int? unused2,
  20. int outputBitrate,
  21. string inputCodec,
  22. string outputCodec,
  23. int? maxWidth,
  24. int? maxHeight)
  25. {
  26. // If the bitrate isn't changing, then don't downlscale the resolution
  27. if (inputBitrate.HasValue && outputBitrate >= inputBitrate.Value)
  28. {
  29. if (maxWidth.HasValue || maxHeight.HasValue)
  30. {
  31. return new ResolutionOptions
  32. {
  33. MaxWidth = maxWidth,
  34. MaxHeight = maxHeight
  35. };
  36. }
  37. }
  38. var resolutionConfig = GetResolutionConfiguration(outputBitrate);
  39. if (resolutionConfig != null)
  40. {
  41. var originvalValue = maxWidth;
  42. maxWidth = Math.Min(resolutionConfig.MaxWidth, maxWidth ?? resolutionConfig.MaxWidth);
  43. if (!originvalValue.HasValue || originvalValue.Value != maxWidth.Value)
  44. {
  45. maxHeight = null;
  46. }
  47. }
  48. return new ResolutionOptions
  49. {
  50. MaxWidth = maxWidth,
  51. MaxHeight = maxHeight
  52. };
  53. }
  54. private static ResolutionConfiguration GetResolutionConfiguration(int outputBitrate)
  55. {
  56. ResolutionConfiguration previousOption = null;
  57. foreach (var config in Configurations)
  58. {
  59. if (outputBitrate <= config.MaxBitrate)
  60. {
  61. return previousOption ?? config;
  62. }
  63. previousOption = config;
  64. }
  65. return null;
  66. }
  67. private static double GetVideoBitrateScaleFactor(string codec)
  68. {
  69. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase) ||
  70. string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase) ||
  71. string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  72. {
  73. return .5;
  74. }
  75. return 1;
  76. }
  77. public static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  78. {
  79. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  80. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  81. var scaleFactor = outputScaleFactor / inputScaleFactor;
  82. var newBitrate = scaleFactor * bitrate;
  83. return Convert.ToInt32(newBitrate);
  84. }
  85. }
  86. }