BitStreamWriter.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.IO;
  2. namespace Ryujinx.Graphics.VDec
  3. {
  4. class BitStreamWriter
  5. {
  6. private const int BufferSize = 8;
  7. private Stream BaseStream;
  8. private int Buffer;
  9. private int BufferPos;
  10. public BitStreamWriter(Stream BaseStream)
  11. {
  12. this.BaseStream = BaseStream;
  13. }
  14. public void WriteBit(bool Value)
  15. {
  16. WriteBits(Value ? 1 : 0, 1);
  17. }
  18. public void WriteBits(int Value, int ValueSize)
  19. {
  20. int ValuePos = 0;
  21. int Remaining = ValueSize;
  22. while (Remaining > 0)
  23. {
  24. int CopySize = Remaining;
  25. int Free = GetFreeBufferBits();
  26. if (CopySize > Free)
  27. {
  28. CopySize = Free;
  29. }
  30. int Mask = (1 << CopySize) - 1;
  31. int SrcShift = (ValueSize - ValuePos) - CopySize;
  32. int DstShift = (BufferSize - BufferPos) - CopySize;
  33. Buffer |= ((Value >> SrcShift) & Mask) << DstShift;
  34. ValuePos += CopySize;
  35. BufferPos += CopySize;
  36. Remaining -= CopySize;
  37. }
  38. }
  39. private int GetFreeBufferBits()
  40. {
  41. if (BufferPos == BufferSize)
  42. {
  43. Flush();
  44. }
  45. return BufferSize - BufferPos;
  46. }
  47. public void Flush()
  48. {
  49. if (BufferPos != 0)
  50. {
  51. BaseStream.WriteByte((byte)Buffer);
  52. Buffer = 0;
  53. BufferPos = 0;
  54. }
  55. }
  56. }
  57. }