Jerikc XIONG
Jerikc XIONG

Reputation: 3607

How to copy the contents of ByteBuffer?

I receive the ByteBuffer object from MediaCodec and aim to copy the ByteBuffer's content to my ByteBuffer object which downsize the capacity. Something like this:

// get the ByteBuffer from MediaCodec
// the capacity of encodedBufferFromMediaCodec is 12345678
encodedBufferFromMediaCodec = getByteBuffer();
// copy the content of encodedBufferFromMediaCodec to my ByteBuffer
// the capacity of myBuffer is 123456
// the content'size of encodedBufferFromMediaCodec is 123
myBuffer.put(encodedBufferFromMediaCodec);

The above is my goal. But i got the following exception:

10-30 14:48:54.621 E/AndroidRuntime( 2999): Process: com.jerikc.demo, PID: 2999 
10-30 14:48:54.621 E/AndroidRuntime( 2999): java.nio.BufferOverflowException
10-30 14:48:54.621 E/AndroidRuntime( 2999):     at java.nio.ByteBuffer.put(ByteBuffer.java:753)

So how to do it?

Upvotes: 1

Views: 3596

Answers (3)

Roland Gude
Roland Gude

Reputation: 81

As EJP suggested, this should cover most cases. It will not work if encodedBufferFromMediaCodec has more then 12345 bytes. In that case you will get a BufferOverflowException.

    ByteBuffer myBuffer = ByteBuffer.allocate(12345);
    ByteBuffer encodedBufferFromMediaCodec = getByteBuffer();

    encodedBufferFromMediaCodec.flip();
    myBuffer.put(encodedBufferFromMediaCodec);
    encodedBufferFromMediaCodec.compact();

Upvotes: 1

BigDru
BigDru

Reputation: 161

ByteBuffer myBuffer = ByteBuffer.allocate(123456);
encodedBufferFromMediaCodec.rewind();

int i = 0;
while (i < 123456) {
    myBuffer.put(encodedBufferFromMediaCodec.get());
    i++;
}

myBuffer.flip();

Note that if the encodedBuffer contains data at 123456+, you will lose that data.

Upvotes: 0

user207421
user207421

Reputation: 310915

  1. Flip the source buffer.
  2. Put the source buffer into the target buffer.
  3. Compact the source buffer.

Upvotes: 1

Related Questions