2
0

ResolutionNormalizer.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 List<ResolutionConfiguration> Configurations =
  9. new List<ResolutionConfiguration>
  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. foreach (var config in Configurations)
  56. {
  57. if (outputBitrate <= config.MaxBitrate)
  58. {
  59. return config;
  60. }
  61. }
  62. return null;
  63. }
  64. private static double GetVideoBitrateScaleFactor(string codec)
  65. {
  66. if (StringHelper.EqualsIgnoreCase(codec, "h265") ||
  67. StringHelper.EqualsIgnoreCase(codec, "hevc") ||
  68. StringHelper.EqualsIgnoreCase(codec, "vp9"))
  69. {
  70. return .5;
  71. }
  72. return 1;
  73. }
  74. public static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  75. {
  76. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  77. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  78. var scaleFactor = outputScaleFactor/inputScaleFactor;
  79. var newBitrate = scaleFactor*bitrate;
  80. return Convert.ToInt32(newBitrate);
  81. }
  82. }
  83. }