Search code examples
androidandroid-mediacodecbytebuffer

MediaCodec: adjust the ByteBuffer values to match BufferInfo (not needed?)


I'm using a MediaCodec to record a .MP4 video (Image and audio).

I have seeing a lot of source codes with the comment before to set the position and limit of ByteBuffer.

// adjust the ByteBuffer values to match BufferInfo (not needed?)
encodedData.position(bufferInfo.offset);
encodedData.limit(bufferInfo.offset + bufferInfo.size);

Example: https://bigflake.com/mediacodec/CameraToMpegTest.java.txt

After all, are these lines really necessary?

I've been asking myself this because I'm having some problems like the exceptions below:

IllegalArgumentException: Bad limit (capacity 8192): 9303 at
java.nio.Buffer.limit(Buffer.java:298)

And

IllegalArgumentException: Bad position (limit 367): 8545 at
java.nio.Buffer.positionImpl(Buffer.java:351)

PS: These erros occurrs with the Audio encoder.


Solution

  • I realize that an other thread was changing bufferInfo values and it was causing these issues.

    Ensure that the values of bufferInfo will not change before to call writeSampleData method making a copy of bufferInfo variable/values.