1. 从onPreviewFrame获得的数据是YUV格式黑白的,如何转换为彩色?
private PreviewCallback mPreviewCallback = new PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (MediaCodecManager.frame != null) {
System.arraycopy(data, 0, MediaCodecManager.frame, 0, data.length);
}
mCamera.addCallbackBuffer(data);
}
};
在编码器里:
mediaCodec.setCallback(new MediaCodec.Callback() {
@Override
public void onInputBufferAvailable(MediaCodec codec, int index) {
NV21toI420SemiPlanar(frame, mFrameData, mPreviewWidth, mPreviewHeight);
ByteBuffer byteBuffer = codec.getInputBuffer(index);
byteBuffer.put(mFrameData);
codec.queueInputBuffer(index, 0, mFrameData.length, 1, BUFFER_FLAG_CODEC_CONFIG);
}
@Override
public void onOutputBufferAvailable(MediaCodec codec, int index,
MediaCodec.BufferInfo info) {
if (index > -1) {
ByteBuffer outputBuffer = codec.getOutputBuffer(index);
byte[] bb = new byte[info.size];
outputBuffer.get(bb);
try {
fileOutputStream.write(bb);
} catch (IOException e) {
e.printStackTrace();
}
try {
mOutputQueue.put(bb);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
codec.releaseOutputBuffer(index, false);
}
}
@Override
public void onError(MediaCodec codec, MediaCodec.CodecException e) {
codec.reset();
}
@Override
public void onOutputFormatChanged(MediaCodec codec, MediaFormat format) {
}
});
在调用queueInputBuffer给数据之前,调用了函数NV21toI420SemiPlanar进行了颜色转换,这样出来的就是彩色的:
protected void NV21toI420SemiPlanar(byte[] nv21bytes, byte[] i420bytes, int width, int height) {
final int iSize = width * height;
System.arraycopy(nv21bytes, 0, i420bytes, 0, iSize);
for (int iIndex = 0; iIndex < iSize / 2; iIndex += 2) {
i420bytes[iSize + iIndex / 2 + iSize / 4] = nv21bytes[iSize + iIndex]; // U
i420bytes[iSize + iIndex / 2] = nv21bytes[iSize + iIndex + 1]; // V
}
}