ResolutionNormalizer.cs 3.0 KB

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