MediaCodec : H264硬解码核心代码总结

解码过程分为两个过程:

1.获取h264视屏流,并进视屏流放入到解码器中的buffer中 

2.获取解码器的buffer ,并获取buffer中解码后的数据,并将其设置到SurfaceView 上进行显示

 

显示界面:

mSurfaceView = (SurfaceView) findViewById(R.id.sv);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);

 

在surfaceCreated回调中开启2.中读取解码数据的循环线程

public class HardDecodeThread extends Thread{
		

	@Override
	public void run() {
		try {
			mMediaCodec = MediaCodec.createDecoderByType("video/avc");
			MediaFormat format = MediaFormat.createVideoFormat("video/avc", 1280, 720);
			mMediaCodec.configure(format, mSurfaceHolder.getSurface(), null, 0);
			mMediaCodec.start();//注意开启编码,不然后面的会报错
				
			showLog("start get output veido info");
			while(isPlay){
				BufferInfo bufInfo = new BufferInfo();
				int outputIndex = 0;
				while((outputIndex = mMediaCodec.dequeueOutputBuffer(bufInfo,20 * 1000)) >= 0 ){
					mMediaCodec.releaseOutputBuffer(outputIndex, true);
				}
					
				if(outputIndex == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED){
					showLog("INFO_OUTPUT_BUFFERS_CHANGED");
				}else if(outputIndex == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED){
					showLog("INFO_OUTPUT_FORMAT_CHANGED");
				}
			}
				
			if(mMediaCodec != null){
				mMediaCodec.stop();
				mMediaCodec.release();
				mMediaCodec = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			showLog("不支持硬编码_error:" + e.getMessage());
		}
	}}


进行1部分:不断获取h264码流进行解码

if(mMediaCodec != null){
	ByteBuffer[] buffers = mMediaCodec.getInputBuffers();
	int inputBufferIndex = mMediaCodec.dequeueInputBuffer(20 * 1000);
	showLog("inputBufferIndex:" + inputBufferIndex);
	if(inputBufferIndex >= 0){
		ByteBuffer buffer = buffers[inputBufferIndex];
		buffer.clear();
		buffer.put(data);
		mMediaCodec.queueInputBuffer(inputBufferIndex, 0, data.length, 0, 0);//data表示h264的字节数组
	}
}


 

你可能感兴趣的:(流媒体)