Android MediaCode request API level 16
public class MyTextureView extends TextureView implements TextureView.SurfaceTextureListener{
private static final String MIME_TYPE = "video/avc";
private static final String TAG = "MyTextureView" ;
private MediaCodec decode;
public MyTextureView(Context context, AttributeSet attrs) {
super(context, attrs);
setSurfaceTextureListener(this);
}
private void init(Surface surface, int width , int height) {
Log.e(TAG, "PreviewThread: gou zhao");
try {
decode = MediaCodec.createDecoderByType(MIME_TYPE);
} catch (IOException e) {
e.printStackTrace();
}
if (decode==null) {
Log.e(TAG, "decode is null ");
}
int frameRate = MainApplication.getApplication().getDeviceSettingInfo().getFrontRate();
final MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
format.setInteger(MediaFormat.KEY_BIT_RATE, 6000);
format.setInteger(MediaFormat.KEY_FRAME_RATE, frameRate>0?frameRate:30);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 32);
format.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 0);
byte[] header_sps = {0, 0, 0, 1, 103, 66, 0 , 41, -115, -115, 64, 80 , 30 , -48 , 15 ,8,-124, 83, -128};
byte[] header_pps = {0,0 ,0, 1, 104, -54, 67, -56};
format.setByteBuffer("csd-0", ByteBuffer.wrap(header_sps));
format.setByteBuffer("csd-1", ByteBuffer.wrap(header_pps));
decode.configure(format, surface,null,0);
decode.start();
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
init(new Surface(surface), width, height);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
if (decode != null) {
decode.release();
}
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
//解码h264数据
public void decoderH264(byte[] input, long timestamp) {
try {
int length = input.length;
ByteBuffer[] inputBuffers = decode.getInputBuffers();
int inputBufferIndex = decode.dequeueInputBuffer(0);
Log.i(TAG, "inputBufferIndex: " +inputBufferIndex + ", in buf len=" +inputBuffers.length);
if (inputBufferIndex >= 0) {
ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
inputBuffer.clear();
try{
inputBuffer.put(input, 0, length);
}catch (Exception e){
e.printStackTrace();
}
decode.queueInputBuffer(inputBufferIndex, 0, length, 0, 0);
}
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
int outputBufferIndex = decode.dequeueOutputBuffer(bufferInfo, 0);
Log.w(TAG, "outputBufferIndex=" +outputBufferIndex + ", out buf len=" + decode.getOutputBuffers().length);
while (outputBufferIndex >= 0) {
//decode.releaseOutputBuffer(outputBufferIndex, true);
decode.releaseOutputBuffer(outputBufferIndex, timestamp);
outputBufferIndex = decode.dequeueOutputBuffer(bufferInfo, 0);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}