Search code examples
androidencodeandroid-mediacodec

MediaCodec getInputImage return null on Some Devices


I want to encode using MediaCodec by setting color format to COLOR_FormatYUV420Flexible. My Input buffer's is yuv420p.When I input buffer like this :

    int inputBufferIndex = mEncoder.dequeueInputBuffer(-1);
    mCurrentBufferIndex = inputBufferIndex;
    if (inputBufferIndex >= 0) {
        ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
        //if(VERBOSE)
            Log.i(TAG,"pos:"+inputBuffer.position()+"\tlimit:"+inputBuffer.limit());
        inputBuffer.clear();
        return inputBuffer;
    }

But some devices get wrong color. So I try this :

    int inputBufferIndex = mEncoder.dequeueInputBuffer(-1);
    mCurrentBufferIndex = inputBufferIndex;
    if (inputBufferIndex >= 0) {
        Image img = mEncoder.getInputImage(inputBufferIndex);
        if(img==null)
            return null;
        //mCurrentInputPlanes = img.getPlanes();
        ByteBuffer buffers[]={img.getPlanes()[0].getBuffer(),
                img.getPlanes()[1].getBuffer(),
                img.getPlanes()[2].getBuffer()};

I fill the buffer to YUV channels .It work on some devices. But moto X pro and huawei P7 get null when calling getInputImage. The documentation say the image doesn't contains raw data. But it also mentions COLOR_FormatYUV420Flexible is supported since API 21.So how should I fix this.


Solution

  • getInputImage documentation says:

         * @return the input image, or null if the index is not a
         * dequeued input buffer, or not a ByteBuffer that contains a
         * raw image.
    

    or not a ByteBuffer that contains a raw image. could mean that the image does not support the color format. Just because COLOR_FormatYUV420Flexible is available since 21, does not mean that all codec support this format.

    If you absolutely have to use getInputImage, then maybe try:

    • COLOR_FormatYUV420Planar
    • COLOR_FormatYUV420SemiPlanar
    • a different codec that can handle COLOR_FormatYUV420Flexible