MediaCodec getInputImage return 在某些设备上为 null

MediaCodec getInputImage return null on Some Devices

我想通过将颜色格式设置为 COLOR_FormatYUV420Flexible 使用 MediaCodec 进行编码。 我的输入缓冲区是 yuv420p.When 我这样输入缓冲区:

    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;
    }

但是有些设备颜色不对。 所以我试试这个:

    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()};

我将缓冲区填充到 YUV 通道。它在某些设备上工作。但是moto X pro和huawei P7在调用getInputImage时得到的是null。 文档说图像不包含原始数据。 但它也提到 COLOR_FormatYUV420Flexible 受支持,因为 API 21.So 我应该如何解决这个问题。

getInputImage 文档说:

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

或者不是包含原始图像的 ByteBuffer。 可能意味着图像不支持颜色格式。 仅仅因为 COLOR_FormatYUV420Flexible 从 21 开始可用,并不意味着所有编解码器都支持这种格式。

如果您绝对必须使用 getInputImage,那么也许可以尝试:

  • COLOR_FormatYUV420Planar
  • COLOR_FormatYUV420SemiPlanar
  • 可以处理 COLOR_FormatYUV420Flexible
  • 的不同编解码器