Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting BufferOverflowException with MediaCodec encode data

I am using Camera2 API to get data from a camera, then using Image reader, OnImageAvailableListener implementation, I insert the camera data into a queue, then using new MediaCodec.Callback implementation I want to encode the data

This is how I init the codec:

MediaCodecInfo codecInfo = selectCodec(MIMETYPE_VIDEO_AVC);
MediaFormat format = MediaFormat.createVideoFormat(MIMETYPE_VIDEO_AVC, cameraRawData.getSize().getWidth(), cameraRawData.getSize().getHeight());
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, 2000000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 10);
format.setLong(MediaFormat.KEY_MAX_INPUT_SIZE, Long.MAX_VALUE);
try {
    encoder = MediaCodec.createByCodecName(codecInfo.getName());
} catch (IOException e) {
    Log.e(TAG, "error creating encoder", e);
    throw new RuntimeException(e);
}

The onInputBufferAvailable implementation:

ByteBuffer inputBuffer = codec.getInputBuffer(index);
ImageData imageData = imageDataQueue.poll();

if (imageData != null) {
    if (inputBuffer != null) {
        Log.i(TAG, "onInputBufferAvailable: " + imageData.getBuffer().length);
        inputBuffer.clear();
        byte[] bytes = imageData.getBuffer();
        try {
            Log.w(TAG, "before failure, the limit is: " + inputBuffer.limit());
            Log.w(TAG, "before failure, the byte array size is: " + bytes.length);
            inputBuffer.put(bytes);
        } catch (Exception e) {
            Log.e(TAG, "error", e);
        }
        codec.queueInputBuffer(index,
                0,
                imageData.getBuffer().length,
                imageData.getPresentationTimeUs(),
                0);
    }
} else {
    codec.queueInputBuffer(index,
            0,
            0,
            0,
            0);
}

and eventually, the exception I receive:

java.nio.BufferOverflowException
        at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:298)
        at java.nio.ByteBuffer.put(ByteBuffer.java:732)

Some additional information, the ByteBuffer limit is set to 12.

like image 318
Eran Friedland Avatar asked Apr 14 '26 10:04

Eran Friedland


1 Answers

After hours of debug, the issue was wrong color format. Instead of:

format.setInteger(MediaFormat.KEY_COLOR_FORMAT, COLOR_FormatSurface);

It should have been:

format.setInteger(MediaFormat.KEY_COLOR_FORMAT, COLOR_FormatYUV420Flexible);
like image 91
Eran Friedland Avatar answered Apr 16 '26 23:04

Eran Friedland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!