MediaCodecUtil.java 6.66 KB
package com.glsx.libxj.util;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.TextureView;

import com.blankj.utilcode.util.LogUtils;

import java.io.IOException;
import java.nio.ByteBuffer;

@SuppressWarnings("deprecation")
public class MediaCodecUtil {
    //自定义的log打印,可以无视
//    Logger logger = Logger.getLogger();

    private String TAG = "MediaCodecUtil";
    //解码后显示的surface及其宽高
    private SurfaceHolder holder;
    private int width, height;
    //解码器
    private MediaCodec mCodec;
    //private boolean isFirst = true;
    // 需要解码的类型
    private final static String MIME_TYPE = "video/avc"; // H.264 Advanced Video
    private final static int TIME_INTERNAL = 5;

    private Surface surface;

    /**
     * 初始化解码器
     *
     * @param holder 用于显示视频的surface
     * @param width  surface宽
     * @param height surface高
     */
    public MediaCodecUtil(SurfaceHolder holder, int width, int height) {
        this.holder = holder;
        this.width = width;
        this.height = height;
    }

    public MediaCodecUtil(SurfaceHolder holder) {
        this(holder, holder.getSurfaceFrame().width(), holder.getSurfaceFrame().height());
    }

    public MediaCodecUtil(TextureView textureView) {
        this.surface = new Surface(textureView.getSurfaceTexture());
        this.width = textureView.getWidth();
        this.height = textureView.getHeight();
    }

    public boolean startCodec() {
        //if (isFirst) {
            //第一次打开则初始化解码器
            return initDecoder();
        //}
        //return true;
    }

    private boolean initDecoder() {
        try {
            //根据需要解码的类型创建解码器
            mCodec = MediaCodec.createDecoderByType(MIME_TYPE);
        } catch (IOException e) {
            LogUtils.d(TAG," codec start e="+e.getMessage());
            e.printStackTrace();
        }
        if(mCodec == null){
            return false;
        }
        //初始化MediaFormat
        MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE,
                width, height);
        //配置MediaFormat以及需要显示的surface
        mCodec.configure(mediaFormat, holder.getSurface()/*surface*/, null, 0);

        /*byte[] sps = {0,0,0,1,103,100,0,40,-84,52,-59,1,-32,17,31,120,11,80,16,16,31
                ,0,0,3,3,-23,0,0,-22,96,-108};
        byte[] pps = {0,0,0,1,104,-18,60,-128};
        MediaFormat mFormat = MediaFormat.createVideoFormat("video/avc", width, height);
        mFormat.setByteBuffer("csd-0", ByteBuffer.wrap(sps));
        mFormat.setByteBuffer("csd-1", ByteBuffer.wrap(pps));*/

        //开始解码
        mCodec.start();
        LogUtils.d(TAG," codec start width="+width+" height="+height);
        //isFirst = false;

        return true;
    }

    int mCount = 0;


    public boolean onFrame(byte[] buf, int offset, int length) {
        if(mCodec == null){
            return false;
        }
        // 获取输入buffer index
        ByteBuffer[] inputBuffers = mCodec.getInputBuffers();
        //-1表示一直等待;0表示不等待;其他大于0的参数表示等待毫秒数
        //LogUtils.e(TAG,"onFrame dequeueInputBuffer 1");
        int inputBufferIndex = mCodec.dequeueInputBuffer(-1);
        //LogUtils.e(TAG,"onFrame dequeueInputBuffer inputBufferIndex="+inputBufferIndex);
        if (inputBufferIndex >= 0) {
            ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
            //清空buffer
            inputBuffer.clear();
            //put需要解码的数据
            inputBuffer.put(buf, offset, length);
            //解码
            mCodec.queueInputBuffer(inputBufferIndex, 0, length, mCount * TIME_INTERNAL, 0);
            mCount++;

        } else {
            LogUtils.e(TAG,"onFrame inputBufferIndex < 0");
            return false;
        }
        // 获取输出buffer index
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        //LogUtils.e(TAG,"onFrame dequeueOutputBuffer 1");
        int outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, 100);
        //LogUtils.e(TAG,"onFrame dequeueOutputBuffer 2 outputBufferIndex="+outputBufferIndex);
        //循环解码,直到数据全部解码完成
        while (outputBufferIndex >= 0) {
            //logger.d("outputBufferIndex = " + outputBufferIndex);
            //true : 将解码的数据显示到surface上
            mCodec.releaseOutputBuffer(outputBufferIndex, true);
            outputBufferIndex = mCodec.dequeueOutputBuffer(bufferInfo, 0);
        }
        if (outputBufferIndex < 0) {
            //logger.e("outputBufferIndex = " + outputBufferIndex);
            //LogUtils.e(TAG,"onFrame outputBufferIndex < 0");
        }
        return true;
    }

    boolean isStopingCodec = false;
    /**
     *停止解码,释放解码器
     */
    public void stopCodec() {
        LogUtils.d(TAG,"stopCodec() mCodec="+mCodec+" isStopingCodec="+isStopingCodec);
        if(isStopingCodec){
            return;
        }
        isStopingCodec = true;
        if(mCodec != null) {
            try {
                mCodec.stop();
                mCodec.release();
                mCodec = null;
                //isFirst = true;
            } catch (Exception e) {
                LogUtils.d(TAG, "stopCodec() Exception=" + e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    mCodec.release();
                }catch (Exception e){}
                mCodec = null;
            }
        }
        isStopingCodec = false;
        LogUtils.d(TAG,"stopCodec() end");
    }

    //视频解码
    public void onFrame2(byte[] frame, int offset, int length) {
        if(!isResetCodec) {
            try {
                //LogUtils.d(TAG, "onFrame LENGTH=" + length);
                if (mCodec != null) {
                    onFrame(frame, offset, length);
                }
            } catch (IllegalStateException e) {
                //e.printStackTrace();
                LogUtils.d(TAG, "onFrame IllegalStateException=" + e.getMessage());
                if(!isResetCodec) {
                    isResetCodec = true;
                    if(mCodec != null && !isStopingCodec) {
                        stopCodec();
                        initDecoder();
                    }
                    isResetCodec = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isResetCodec() {
        return isResetCodec;
    }

    boolean isResetCodec = false;
}