BitUtils.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Diagnostics;
  3. using System.Numerics;
  4. using System.Runtime.CompilerServices;
  5. namespace Ryujinx.Graphics.Nvdec.Vp9.Common
  6. {
  7. internal static class BitUtils
  8. {
  9. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  10. public static byte ClipPixel(int val)
  11. {
  12. return (byte)((val > 255) ? 255 : (val < 0) ? 0 : val);
  13. }
  14. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  15. public static ushort ClipPixelHighbd(int val, int bd)
  16. {
  17. return bd switch
  18. {
  19. 10 => (ushort)Math.Clamp(val, 0, 1023),
  20. 12 => (ushort)Math.Clamp(val, 0, 4095),
  21. _ => (ushort)Math.Clamp(val, 0, 255)
  22. };
  23. }
  24. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  25. public static int RoundPowerOfTwo(int value, int n)
  26. {
  27. return (value + (1 << (n - 1))) >> n;
  28. }
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public static long RoundPowerOfTwo(long value, int n)
  31. {
  32. return (value + (1L << (n - 1))) >> n;
  33. }
  34. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  35. public static int AlignPowerOfTwo(int value, int n)
  36. {
  37. return (value + ((1 << n) - 1)) & ~((1 << n) - 1);
  38. }
  39. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  40. private static int GetMsb(uint n)
  41. {
  42. Debug.Assert(n != 0);
  43. return 31 ^ BitOperations.LeadingZeroCount(n);
  44. }
  45. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  46. public static int GetUnsignedBits(uint numValues)
  47. {
  48. return numValues > 0 ? GetMsb(numValues) + 1 : 0;
  49. }
  50. }
  51. }