1 package com.googlecode.mp4parser.boxes.mp4.objectdescriptors; 2 3 import java.nio.ByteBuffer; 4 5 public class BitWriterBuffer { 6 7 private ByteBuffer buffer; 8 int initialPos; 9 int position = 0; 10 11 public BitWriterBuffer(ByteBuffer buffer) { 12 this.buffer = buffer; 13 this.initialPos = buffer.position(); 14 } 15 16 public void writeBits(int i, int numBits) { 17 assert i <= ((1 << numBits)-1): String.format("Trying to write a value bigger (%s) than the number bits (%s) allows. " + 18 "Please mask the value before writing it and make your code is really working as intended.", i, (1<<numBits)-1); 19 20 int left = 8 - position % 8; 21 if (numBits <= left) { 22 int current = (buffer.get(initialPos + position / 8)); 23 current = current < 0 ? current + 256 : current; 24 current += i << (left - numBits); 25 buffer.put(initialPos + position / 8, (byte) (current > 127 ? current - 256 : current)); 26 position += numBits; 27 } else { 28 int bitsSecondWrite = numBits - left; 29 writeBits(i >> bitsSecondWrite, left); 30 writeBits(i & (1 << bitsSecondWrite) - 1, bitsSecondWrite); 31 } 32 buffer.position(initialPos + position / 8 + ((position % 8 > 0) ? 1 : 0)); 33 } 34 35 36 } 37