摄像头预览的图片格式设置YV12,编码成H264时要转成YUV420的,编码完成后再解码播放,就有花屏、重影的现象,现在不知道是什么原因了,求助!!!!
图标左侧是预览的,没有问题,右侧是经过编码、解码后的
设置图片预览格式
parameters.setPictureFormat(ImageFormat.YV12);
编码
// add h264 file for test
public int encode(byte[] input, byte[] output, RandomAccessFile raf){
int pos = 0;
swapYV12toI420(input, yuv420, width, height);
// yuv420 = swapYV12toI420(input, width, height);
try {
ByteBuffer[] inputBuffers = mediaencodec.getInputBuffers();
ByteBuffer[] outputBuffers = mediaencodec.getOutputBuffers();
int inputBufferIndex = mediaencodec.dequeueInputBuffer(-1);
//Log.i("EncodeAndDecode", "encode inputBufferIndex= "+inputBufferIndex);
++einputcount;
Log.i("EncodeAndDecode", "encode inputcount= "+einputcount+" input size="+yuv420.length);
if (inputBufferIndex >= 0)
{
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
inputBuffer.clear();
inputBuffer.put(yuv420);
mediaencodec.queueInputBuffer(inputBufferIndex, 0, yuv420.length, 0, 0);
}
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputBufferIndex = mediaencodec.dequeueOutputBuffer(bufferInfo,0);
//Log.i("EncodeAndDecode", "encode outputBufferIndex= "+outputBufferIndex);
// add h264 file for test
// raf.write(new byte[]{0x00,0x00,0x00,0x01});
while (outputBufferIndex >= 0)
{
ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
byte[] outData = new byte[bufferInfo.size];
outputBuffer.get(outData);
++eoutputcount;
Log.i("EncodeAndDecode", "encode outputcount= "+eoutputcount+" outData size="+outData.length);
// add h264 file for test
// raf.write(outData);
decode(outData);
mediaencodec.releaseOutputBuffer(outputBufferIndex, false);
outputBufferIndex = mediaencodec.dequeueOutputBuffer(bufferInfo, 0);
}
} catch (Throwable t) {
t.printStackTrace();
}
return pos;
}
格式转换
private void swapYV12toI420(byte[] yv12bytes, byte[] i420bytes, int width, int height)
{
System.arraycopy(yv12bytes, 0, i420bytes, 0, width*height);
System.arraycopy(yv12bytes, width*height+width*height/4, i420bytes, width*height, width*height/4);
System.arraycopy(yv12bytes, width*height, i420bytes, width*height+width*height/4, width*height/4);
}