Android硬编解码接口MediaCodec使用完全解析(一)

2023-05-16

0、本文概述

MediaCodec是android api 16以后开放的硬编解码接口,英文文档参照这个链接,中文翻译可以参考这个链接。本文主要记录的是如何使用MediaCodec对视频进行编解码,最后会以实例的方式展示如何将Camera预览数据编码成H264,再把编码后的h264解码并且显示在SurfaceView中。本例不涉及音频的编解码。

1、MediaCodec编码视频

使用MediaCodec实现视频编码的步骤如下:
1.初始化MediaCodec,方法有两种,分别是通过名称和类型来创建,对应的方法为:

MediaCodec createByCodecName (String name);
MediaCodec createDecoderByType (String type);

具体可用的name和type参考文档即可。这里我们通过后者来初始化一个视频编码器。

mMC = MediaCodec.createDecoderByType(MIME_TYPE);

2.配置MediaCodec,这一步需要配置的是MediaFormat,这个类包含了比特率、帧率、关键帧间隔时间等,其中比特率如果太低就会造成类似马赛克的现象。

mMF = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
mMF.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);  
mMF.setInteger(MediaFormat.KEY_FRAME_RATE, framerate);  
if (mPrimeColorFormat != 0){
    mMF.setInteger(MediaFormat.KEY_COLOR_FORMAT, mPrimeColorFormat);  
}
mMF.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1); //关键帧间隔时间 单位s
mMC.configure(mMF, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

其中mPrimeColorFormat为本机支持的颜色空间。一般是yuv420p或者yuv420sp,Camera预览格式一般是yv12或者NV21,所以在编码之前需要进行格式转换,实例可参照文末代码。代码是最好的老师嘛。
3.打开编码器,获取输入输出缓冲区

mMC.start();
mInputBuffers = mMC.getInputBuffers();
mOutputBuffers = mMC.getOutputBuffers();

4.输入数据,过程可以分为以下几个小步:
1)获取可使用缓冲区位置得到索引

int inputbufferindex = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);

如果存在可用的缓冲区,此方法会返回其位置索引,否则返回-1,参数为超时时间,单位是毫秒,如果此参数是0,则立即返回,如果参数小于0,则无限等待直到有可使用的缓冲区,如果参数大于0,则等待时间为传入的毫秒值。
2)传入原始数据

ByteBuffer inputBuffer = mInputBuffers[inputbufferindex];
inputBuffer.clear();//清除原来的内容以接收新的内容
inputBuffer.put(bytes, 0, len);//len是传进来的有效数据长度
mMC.queueInputBuffer(inputbufferindex, 0, len, timestamp, 0);

此缓冲区一旦使用,只有在dequeueInputBuffer返回其索引位置才代表它可以再次使用。
5.获取其输出数据,获取输入原始数据和获取输出数据最好是异步进行,因为输入一帧数据不代表编码器马上就会输出对应的编码数据,可能输入好几帧才会输出一帧。获取输出数据的步骤与输入数据的步骤相似:
1)获取可用的输出缓冲区

int outputbufferindex = mMC.dequeueOutputBuffer(mBI, BUFFER_TIMEOUT);

其中参数一是一个BufferInfo类型的实例,参数二为超时时间,负数代表无限等待(可见,不要在主线程进行操作)。
2)获取输出数据

mOutputBuffers[outputbufferindex].get(bytes, 0, mBI.size);

3)释放缓冲区

mMC.releaseOutputBuffer(outputbufferindex, false);

2、MediaCodec解码视频

解码视频的步骤跟编码的类似,配置不一样:
1.实例化解码器

mMC = MediaCodec.createDecoderByType(MIME_TYPE);

2.配置解码器,此处需要配置用于显示图像的Surface、MediaFormat包含视频的pps和sps(包含在编码出来的第一帧数据)

int[] width = new int[1];
int[] height = new int[1];  
AvcUtils.parseSPS(sps, width, height);//从sps中解析出视频宽高
mMF = MediaFormat.createVideoFormat(MIME_TYPE, width[0], height[0]);
mMF.setByteBuffer("csd-0", ByteBuffer.wrap(sps));
mMF.setByteBuffer("csd-1", ByteBuffer.wrap(pps));
mMF.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, width[0] * height[0]);
mMC.configure(mMF, surface, null, 0);

3.开启编码器并获取输入输出缓冲区

mMC.start();
mInputBuffers = mMC.getInputBuffers();
mOutputBuffers = mMC.getOutputBuffers();

4.输入数据
1)获取可用的输入缓冲区

int inputbufferindex = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);

返回值为可用缓冲区的索引

ByteBuffer inputBuffer = mInputBuffers[inputbufferindex];
inputBuffer.clear();

2)然后输入数据

inputBuffer.put(bytes, 0, len);
mMC.queueInputBuffer(inputbufferindex, 0, len, timestamp, 0);

5.获取输出数据,这一步与4同样应该异步进行,其具体步骤与上面解码的基本相同,在释放缓冲区的时候需要注意第二个参数设置为true,表示解码显示在Surface上

mMC.releaseOutputBuffer(outputbufferindex, true);

3、编解码实例

下面是一个MediaCodec编解码实例,此例子Camera预览数据(yv12)编码成H264,再把编码后的h264解码并且显示在SurfaceView中。
##3.1布局文件
布局文件非常简单,两个SurfaceView分别用于显示编解码的图像,两个按钮控制开始和停止,一个TextView用于显示捕捉帧率。布局文件代码就不展示了,界面如下

3.2编码器类Encoder

package com.example.mediacodecpro;

import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.util.Log;

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

/**
 * Created by chuibai on 2017/3/10.<br />
 */

public class Encoder {

    public static final int TRY_AGAIN_LATER = -1;
    public static final int BUFFER_OK = 0;
    public static final int BUFFER_TOO_SMALL = 1;
    public static final int OUTPUT_UPDATE = 2;

    private int format = 0;
    private final String MIME_TYPE = "video/avc";
    private MediaCodec mMC = null;
    private MediaFormat mMF;
    private ByteBuffer[] inputBuffers;
    private ByteBuffer[] outputBuffers;
    private long BUFFER_TIMEOUT = 0;
    private MediaCodec.BufferInfo mBI;

    /**
     * 初始化编码器
     * @throws IOException 创建编码器失败会抛出异常
     */
    public void init() throws IOException {
        mMC = MediaCodec.createEncoderByType(MIME_TYPE);
        format = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar;
        mBI = new MediaCodec.BufferInfo();
    }

    /**
     * 配置编码器,需要配置颜色、帧率、比特率以及视频宽高
     * @param width 视频的宽
     * @param height 视频的高
     * @param bitrate 视频比特率
     * @param framerate 视频帧率
     */
    public void configure(int width,int height,int bitrate,int framerate){
        if(mMF == null){
            mMF = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
            mMF.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
            mMF.setInteger(MediaFormat.KEY_FRAME_RATE, framerate);
            if (format != 0){
                mMF.setInteger(MediaFormat.KEY_COLOR_FORMAT, format);
            }
            mMF.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, -1); //关键帧间隔时间 单位s
        }
        mMC.configure(mMF,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
    }

    /**
     * 开启编码器,获取输入输出缓冲区
     */
    public void start(){
        mMC.start();
        inputBuffers = mMC.getInputBuffers();
        outputBuffers = mMC.getOutputBuffers();
    }

    /**
     * 向编码器输入数据,此处要求输入YUV420P的数据
     * @param data YUV数据
     * @param len 数据长度
     * @param timestamp 时间戳
     * @return
     */
    public int input(byte[] data,int len,long timestamp){
        int index = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);
        Log.e("...","" + index);
        if(index >= 0){
            ByteBuffer inputBuffer = inputBuffers[index];
            inputBuffer.clear();
            if(inputBuffer.capacity() < len){
                mMC.queueInputBuffer(index, 0, 0, timestamp, 0);
                return BUFFER_TOO_SMALL;
            }
            inputBuffer.put(data,0,len);
            mMC.queueInputBuffer(index,0,len,timestamp,0);
        }else{
            return index;
        }
        return BUFFER_OK;
    }

    /**
     * 输出编码后的数据
     * @param data 数据
     * @param len 有效数据长度
     * @param ts 时间戳
     * @return
     */
    public int output(/*out*/byte[] data,/* out */int[] len,/* out */long[] ts){
        int i = mMC.dequeueOutputBuffer(mBI, BUFFER_TIMEOUT);
        if(i >= 0){
            if(mBI.size > data.length) return BUFFER_TOO_SMALL;
            outputBuffers[i].position(mBI.offset);
            outputBuffers[i].limit(mBI.offset + mBI.size);
            outputBuffers[i].get(data, 0, mBI.size);
            len[0] = mBI.size ;
            ts[0] = mBI.presentationTimeUs;
            mMC.releaseOutputBuffer(i, false);
        } else if (i == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            outputBuffers = mMC.getOutputBuffers();
            return OUTPUT_UPDATE;
        } else if (i == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            mMF = mMC.getOutputFormat();
            return OUTPUT_UPDATE;
        } else if (i == MediaCodec.INFO_TRY_AGAIN_LATER) {
            return TRY_AGAIN_LATER;
        }

        return BUFFER_OK;
    }

    public void release(){
        mMC.stop();
        mMC.release();
        mMC = null;
        outputBuffers = null;
        inputBuffers = null;
    }

    public void flush() {
        mMC.flush();
    }
}

3.3解码器类Decoder

package com.example.mediacodecpro;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.view.Surface;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Created by chuibai on 2017/3/10.<br />
 */

public class Decoder {

    public static final int TRY_AGAIN_LATER = -1;
    public static final int BUFFER_OK = 0;
    public static final int BUFFER_TOO_SMALL = 1;
    public static final int OUTPUT_UPDATE = 2;

    private final String MIME_TYPE = "video/avc";
    private MediaCodec mMC = null;
    private MediaFormat mMF;
    private long BUFFER_TIMEOUT = 0;
    private MediaCodec.BufferInfo mBI;
    private ByteBuffer[] mInputBuffers;
    private ByteBuffer[] mOutputBuffers;

    /**
     * 初始化编码器
     * @throws IOException 创建编码器失败会抛出异常
     */
    public void init() throws IOException {
        mMC = MediaCodec.createDecoderByType(MIME_TYPE);
        mBI = new MediaCodec.BufferInfo();
    }

    /**
     * 配置解码器
     * @param sps 用于配置的sps参数
     * @param pps 用于配置的pps参数
     * @param surface 用于解码显示的Surface
     */
    public void configure(byte[] sps, byte[] pps, Surface surface){
        int[] width = new int[1];
        int[] height = new int[1];
        AvcUtils.parseSPS(sps, width, height);//从sps中解析出视频宽高
        mMF = MediaFormat.createVideoFormat(MIME_TYPE, width[0], height[0]);
        mMF.setByteBuffer("csd-0", ByteBuffer.wrap(sps));
        mMF.setByteBuffer("csd-1", ByteBuffer.wrap(pps));
        mMF.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, width[0] * height[0]);
        mMC.configure(mMF, surface, null, 0);
    }

    /**
     * 开启解码器,获取输入输出缓冲区
     */
    public void start(){
        mMC.start();
        mInputBuffers = mMC.getInputBuffers();
        mOutputBuffers = mMC.getOutputBuffers();
    }

    /**
     * 输入数据
     * @param data 输入的数据
     * @param len 数据有效长度
     * @param timestamp 时间戳
     * @return 成功则返回{@link #BUFFER_OK} 否则返回{@link #TRY_AGAIN_LATER}
     */
    public int input(byte[] data,int len,long timestamp){
        int i = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);
        if(i >= 0){
            ByteBuffer inputBuffer = mInputBuffers[i];
            inputBuffer.clear();
            inputBuffer.put(data, 0, len);
            mMC.queueInputBuffer(i, 0, len, timestamp, 0);
        }else {
            return TRY_AGAIN_LATER;
        }
        return BUFFER_OK;
    }

    public int output(byte[] data,int[] len,long[] ts){
        int i = mMC.dequeueOutputBuffer(mBI, BUFFER_TIMEOUT);
        if(i >= 0){
            if (mOutputBuffers[i] != null)
            {
                mOutputBuffers[i].position(mBI.offset);
                mOutputBuffers[i].limit(mBI.offset + mBI.size);

                if (data != null)
                    mOutputBuffers[i].get(data, 0, mBI.size);
                len[0] = mBI.size;
                ts[0] = mBI.presentationTimeUs;
            }
            mMC.releaseOutputBuffer(i, true);
        }else{
            return TRY_AGAIN_LATER;
        }
        return BUFFER_OK;
    }

    public void flush(){
        mMC.flush();
    }

    public void release() {
        flush();
        mMC.stop();
        mMC.release();
        mMC = null;
        mInputBuffers = null;
        mOutputBuffers = null;
    }
}

3.4MainAcitivity

package com.example.mediacodecpro;

import android.content.pm.ActivityInfo;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Camera.PreviewCallback {

    @BindView(R.id.surfaceView_encode)
    SurfaceView surfaceViewEncode;
    @BindView(R.id.surfaceView_decode)
    SurfaceView surfaceViewDecode;
    @BindView(R.id.btnStart)
    Button btnStart;
    @BindView(R.id.btnStop)
    Button btnStop;
    @BindView(R.id.capture)
    TextView capture;
    private int width;
    private int height;
    private int bitrate;
    private int framerate;
    private int captureFrame;
    private Camera mCamera;
    private Queue<PreviewBufferInfo> mPreviewBuffers_clean;
    private Queue<PreviewBufferInfo> mPreviewBuffers_dirty;
    private Queue<PreviewBufferInfo> mDecodeBuffers_clean;
    private Queue<PreviewBufferInfo> mDecodeBuffers_dirty;
    private int PREVIEW_POOL_CAPACITY = 5;
    private int format;
    private int DECODE_UNI_SIZE = 1024 * 1024;
    private byte[] mAvcBuf = new byte[1024 * 1024];
    private final int MSG_ENCODE = 0;
    private final int MSG_DECODE = 1;
    private String TAG = "MainActivity";
    private long mLastTestTick = 0;
    private Object mAvcEncLock;
    private Object mDecEncLock;
    private Decoder mDecoder;
    private Handler codecHandler;
    private byte[] mRawData;
    private Encoder mEncoder;
    private CodecThread codecThread;
    private DatagramSocket socket;
    private DatagramPacket packet;
    private byte[] sps_pps;
    private byte[] mPacketBuf = new byte[1024 * 1024];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //初始化参数
        initParams();

        //设置监听事件
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
    }

    /**
     * 初始化参数,包括帧率、颜色、比特率,视频宽高等
     */
    private void initParams() {
        width = 352;
        height = 288;
        bitrate = 1500000;
        framerate = 30;
        captureFrame = 0;
        format = ImageFormat.YV12;
        mAvcEncLock = new Object();
        mDecEncLock = new Object();
    }

    @Override
    protected void onResume() {
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnStart:
                mCamera = Camera.open(0);
                initQueues();
                initEncoder();
                initCodecThread();
                startPreview();
                break;
            case R.id.btnStop:
                releaseCodecThread();
                releseEncoderAndDecoder();
                releaseCamera();
                releaseQueue();
                break;
        }
    }

    /**
     * 释放队列资源
     */
    private void releaseQueue() {
        if (mPreviewBuffers_clean != null){
            mPreviewBuffers_clean.clear();
            mPreviewBuffers_clean = null;
        }
        if (mPreviewBuffers_dirty != null){
            mPreviewBuffers_dirty.clear();
            mPreviewBuffers_dirty = null;
        }
        if (mDecodeBuffers_clean != null){
            mDecodeBuffers_clean.clear();
            mDecodeBuffers_clean = null;
        }
        if (mDecodeBuffers_dirty != null){
            mDecodeBuffers_dirty.clear();
            mDecodeBuffers_dirty = null;
        }
    }

    /**
     * 释放摄像头资源
     */
    private void releaseCamera() {
        if(mCamera != null){
            mCamera.setPreviewCallbackWithBuffer(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private void releseEncoderAndDecoder() {
        if(mEncoder != null){
            mEncoder.flush();
            mEncoder.release();
            mEncoder = null;
        }
        if(mDecoder != null){
            mDecoder.release();
            mDecoder = null;
        }
    }

    private void releaseCodecThread() {
        codecHandler.getLooper().quit();
        codecHandler = null;
        codecThread = null;
    }

    private void initCodecThread() {
        codecThread = new CodecThread();
        codecThread.start();
    }

    /**
     * 开启预览
     */
    private void startPreview() {
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewFormat(format);
        parameters.setPreviewFrameRate(framerate);
        parameters.setPreviewSize(width,height);
        mCamera.setParameters(parameters);
        try {
            mCamera.setPreviewDisplay(surfaceViewEncode.getHolder());
        } catch (IOException e) {
            e.printStackTrace();
        }
        mCamera.setPreviewCallbackWithBuffer(this);
        mCamera.startPreview();
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        /** 预览的data为null */
        if(data == null) {
            Log.e(TAG,"预览的data为null");
            return;
        }

        long curTick = System.currentTimeMillis();
        if (mLastTestTick == 0) {
            mLastTestTick = curTick;
        }
        if (curTick > mLastTestTick + 1000) {
            setCaptureFPSTextView(captureFrame);
            captureFrame = 0;
            mLastTestTick = curTick;
        } else
            captureFrame++;
        synchronized(mAvcEncLock) {
            PreviewBufferInfo info = mPreviewBuffers_clean.poll();    //remove the head of queue
            info.buffer = data;
            info.size = getPreviewBufferSize(width, height, format);
            info.timestamp = System.currentTimeMillis();
            mPreviewBuffers_dirty.add(info);
            if(mDecoder == null){
                codecHandler.sendEmptyMessage(MSG_ENCODE);
            }
        }
    }

    private void setCaptureFPSTextView(int captureFrame) {
        capture.setText("当前帧率:" + captureFrame);
    }

    private void initEncoder() {
        mEncoder = new Encoder();
        try {
            mEncoder.init();
            mEncoder.configure(width,height,bitrate,framerate);
            mEncoder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化各种队列
     */
    private void initQueues() {
        if (mPreviewBuffers_clean == null)
            mPreviewBuffers_clean = new LinkedList<>();
        if (mPreviewBuffers_dirty == null)
            mPreviewBuffers_dirty = new LinkedList<>();
        int size = getPreviewBufferSize(width, height, format);
        for (int i = 0; i < PREVIEW_POOL_CAPACITY; i++) {
            byte[] mem = new byte[size];
            mCamera.addCallbackBuffer(mem);    //ByteBuffer.array is a reference, not a copy
            PreviewBufferInfo info = new PreviewBufferInfo();
            info.buffer = null;
            info.size = 0;
            info.timestamp = 0;
            mPreviewBuffers_clean.add(info);
        }
        if (mDecodeBuffers_clean == null)
            mDecodeBuffers_clean = new LinkedList<>();
        if (mDecodeBuffers_dirty == null)
            mDecodeBuffers_dirty = new LinkedList<>();
        for (int i = 0; i < PREVIEW_POOL_CAPACITY; i++) {
            PreviewBufferInfo info = new PreviewBufferInfo();
            info.buffer = new byte[DECODE_UNI_SIZE];
            info.size = 0;
            info.timestamp = 0;
            mDecodeBuffers_clean.add(info);
        }
    }

    /**
     * 获取预览buffer的大小
     * @param width 预览宽
     * @param height 预览高
     * @param format 预览颜色格式
     * @return 预览buffer的大小
     */
    private int getPreviewBufferSize(int width, int height, int format) {
        int size = 0;
        switch (format) {
            case ImageFormat.YV12: {
                int yStride = (int) Math.ceil(width / 16.0) * 16;
                int uvStride = (int) Math.ceil((yStride / 2) / 16.0) * 16;
                int ySize = yStride * height;
                int uvSize = uvStride * height / 2;
                size = ySize + uvSize * 2;
            }
            break;

            case ImageFormat.NV21: {
                float bytesPerPix = (float) ImageFormat.getBitsPerPixel(format) / 8;
                size = (int) (width * height * bytesPerPix);
            }
            break;
        }

        return size;
    }

    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);
    }

    private class PreviewBufferInfo {
        public byte[] buffer;
        public int size;
        public long timestamp;
    }

    private class CodecThread extends Thread {
        @Override
        public void run() {
            Looper.prepare();
            codecHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case MSG_ENCODE:
                            int res = Encoder.BUFFER_OK;
                            synchronized (mAvcEncLock) {
                                if (mPreviewBuffers_dirty != null && mPreviewBuffers_clean != null) {
                                    Iterator<PreviewBufferInfo> ite = mPreviewBuffers_dirty.iterator();
                                    while (ite.hasNext()) {
                                        PreviewBufferInfo info = ite.next();
                                        byte[] data = info.buffer;
                                        int data_size = info.size;
                                        if (format == ImageFormat.YV12) {
                                            if (mRawData == null || mRawData.length < data_size) {
                                                mRawData = new byte[data_size];
                                            }
                                            swapYV12toI420(data, mRawData, width, height);
                                        } else {
                                            Log.e(TAG, "preview size MUST be YV12, cur is " + format);
                                            mRawData = data;
                                        }
                                        res = mEncoder.input(mRawData, data_size, info.timestamp);
                                        if (res != Encoder.BUFFER_OK) {
//                                            Log.e(TAG, "mEncoder.input, maybe wrong:" + res);
                                            break;        //the rest buffers shouldn't go into encoder, if the previous one get problem
                                        } else {
                                            ite.remove();
                                            mPreviewBuffers_clean.add(info);
                                            if (mCamera != null) {
                                                mCamera.addCallbackBuffer(data);
                                            }
                                        }
                                    }
                                }
                            }


                            while (res == Encoder.BUFFER_OK) {
                                int[] len = new int[1];
                                long[] ts = new long[1];
                                synchronized (mAvcEncLock) {
                                    res = mEncoder.output(mAvcBuf, len, ts);
                                }

                                if (res == Encoder.BUFFER_OK) {
                                    //发送h264
                                    if(sps_pps != null){
                                        send(len[0]);
                                    }

                                    if (mDecodeBuffers_clean != null && mDecodeBuffers_dirty != null) {
                                        synchronized (mAvcEncLock) {
                                            Iterator<PreviewBufferInfo> ite = mDecodeBuffers_clean.iterator();
                                            if (ite.hasNext()) {
                                                PreviewBufferInfo bufferInfo = ite.next();
                                                if (bufferInfo.buffer.length >= len[0]) {
                                                    bufferInfo.timestamp = ts[0];
                                                    bufferInfo.size = len[0];
                                                    System.arraycopy(mAvcBuf, 0, bufferInfo.buffer, 0, len[0]);
                                                    ite.remove();
                                                    mDecodeBuffers_dirty.add(bufferInfo);
                                                } else {
                                                    Log.e(TAG, "decoder uni buffer too small, need " + len[0] + " but has " + bufferInfo.buffer.length);
                                                }
                                            }
                                        }
                                        initDecoder(len);
                                    }
                                }

                            }
                            codecHandler.sendEmptyMessageDelayed(MSG_ENCODE, 30);
                            break;

                        case MSG_DECODE:
                            synchronized (mDecEncLock) {
                                int result = Decoder.BUFFER_OK;

                                //STEP 1: handle input buffer
                                if (mDecodeBuffers_dirty != null && mDecodeBuffers_clean != null) {
                                    Iterator<PreviewBufferInfo> ite = mDecodeBuffers_dirty.iterator();
                                    while (ite.hasNext()) {
                                        PreviewBufferInfo info = ite.next();
                                        result = mDecoder.input(info.buffer, info.size, info.timestamp);
                                        if (result != Decoder.BUFFER_OK) {
                                            break;        //the rest buffers shouldn't go into encoder, if the previous one get problem
                                        } else {
                                            ite.remove();
                                            mDecodeBuffers_clean.add(info);
                                        }
                                    }
                                }

                                int[] len = new int[1];
                                long[] ts = new long[1];
                                while (result == Decoder.BUFFER_OK) {
                                    result = mDecoder.output(null, len, ts);
                                }
                            }
                            codecHandler.sendEmptyMessageDelayed(MSG_DECODE, 30);
                            break;
                    }
                }
            };
            Looper.loop();
        }
    }

    private void send(int len) {
        try {
            if(socket == null) socket = new DatagramSocket();
            if(packet == null){
                packet = new DatagramPacket(mPacketBuf,0,sps_pps.length + len);
                packet.setAddress(InetAddress.getByName("192.168.43.1"));
                packet.setPort(5006);
            }
            if(mAvcBuf[4] == 0x65){
                System.arraycopy(sps_pps,0,mPacketBuf,0,sps_pps.length);
                System.arraycopy(mAvcBuf,0,mPacketBuf,sps_pps.length,len);
                len += sps_pps.length;
            }else{
                System.arraycopy(mAvcBuf,0,mPacketBuf,0,len);
            }
            packet.setLength(len);
            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initDecoder(int[] len) {
        if(sps_pps == null){
            sps_pps = new byte[len[0]];
            System.arraycopy(mAvcBuf,0,sps_pps,0,len[0]);
        }
        if(mDecoder == null){
            mDecoder = new Decoder();
            try {
                mDecoder.init();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] sps_nal = null;
            int sps_len = 0;
            byte[] pps_nal = null;
            int pps_len = 0;
            ByteBuffer byteb = ByteBuffer.wrap(mAvcBuf, 0, len[0]);
            //SPS
            if (true == AvcUtils.goToPrefix(byteb)) {
                int sps_position = 0;
                int pps_position = 0;
                int nal_type = AvcUtils.getNalType(byteb);
                if (AvcUtils.NAL_TYPE_SPS == nal_type) {
                    Log.d(TAG, "OutputAvcBuffer, AVC NAL type: SPS");
                    sps_position = byteb.position() - AvcUtils.START_PREFIX_LENGTH - AvcUtils.NAL_UNIT_HEADER_LENGTH;
                    //PPS
                    if (true == AvcUtils.goToPrefix(byteb)) {
                        nal_type = AvcUtils.getNalType(byteb);
                        if (AvcUtils.NAL_TYPE_PPS == nal_type) {
                            pps_position = byteb.position() - AvcUtils.START_PREFIX_LENGTH - AvcUtils.NAL_UNIT_HEADER_LENGTH;
                            sps_len = pps_position - sps_position;
                            sps_nal = new byte[sps_len];
                            int cur_pos = byteb.position();
                            byteb.position(sps_position);
                            byteb.get(sps_nal, 0, sps_len);
                            byteb.position(cur_pos);
                            //slice
                            if (true == AvcUtils.goToPrefix(byteb)) {
                                nal_type = AvcUtils.getNalType(byteb);
                                int pps_end_position = byteb.position() - AvcUtils.START_PREFIX_LENGTH - AvcUtils.NAL_UNIT_HEADER_LENGTH;
                                pps_len = pps_end_position - pps_position;
                            } else {
                                pps_len = byteb.position() - pps_position;
                                //pps_len = byteb.limit() - pps_position + 1;
                            }
                            if (pps_len > 0) {
                                pps_nal = new byte[pps_len];
                                cur_pos = byteb.position();
                                byteb.position(pps_position);
                                byteb.get(pps_nal, 0, pps_len);
                                byteb.position(cur_pos);
                            }
                        } else {
                            //Log.d(log_tag, "OutputAvcBuffer, AVC NAL type: "+nal_type);
                            throw new UnsupportedOperationException("SPS is not followed by PPS, nal type :" + nal_type);
                        }
                    }
                } else {
                    //Log.d(log_tag, "OutputAvcBuffer, AVC NAL type: "+nal_type);
                }

                //2. configure AVC decoder with SPS/PPS
                if (sps_nal != null && pps_nal != null) {

                    int[] width = new int[1];
                    int[] height = new int[1];
                    AvcUtils.parseSPS(sps_nal, width, height);
                    mDecoder.configure(sps_nal, pps_nal,surfaceViewDecode.getHolder().getSurface());
                    mDecoder.start();
                    if (codecHandler != null) {
                        codecHandler.sendEmptyMessage(MSG_DECODE);
                    }
                }

            }
        }
    }

}

上面的send方法可以把手机捕捉并编码的视频数据发送到电脑上使用ffplay播放,使用ffplay的时候记得加上参数-analyzeduration 200000减小视频延迟。

4.要点总结

个人总结使用MediaCodec编解码的时候主要需要注意以下事项:

  • 数据的输入和输出要异步进行,不要采用阻塞的方式等待输出数据
  • 编码Camera预览数据的时候使用带buffer的预览回调,避免帧率过低
  • 适当使用缓存队列,不要每一帧都new一个byte数组,避免频繁的GC
  • 不要在主线程进行操作,在我学习的过程中看到有些朋友直接在预览回调里进行编解码,在dequeueOutputBuffer方法还传递-1,也就是无限等待程序返回

5.代码下载

有朋友求代码,本来代码在CSDN上,但是由于积分问题申请删除了。今天整理旧电脑,找到了这个代码。很多年前写的代码,非常丑陋,随便看看就好。

Github:https://github.com/sahooz/MediaCodecSample

当时本来想完成一个Android多媒体系列,包括编解码、RTSP、RTMP和SDL等等,但是工作变动搁浅了。或许后面会重新拾起来,再来完成吧~。感谢大家的阅读和评论。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android硬编解码接口MediaCodec使用完全解析(一) 的相关文章

  • C++ ZeroMQ 发布订阅模式例子跟注意事项

    发布订阅模式 接收端 xff1a void context void subscriber 第一步 xff1a zmq ctx new 创建context对象 context 61 zmq ctx new 第二步 xff1a 创建socke
  • 目标检测算法——anchor free

    一 anchor free 概述 1 先要知道anchor 是什么 xff08 这需要先了解二阶段如faster rcnn xff0c 一阶检测器如YOLO V2以后或SSD等 xff09 在过去 xff0c 目标检测通常被建模为对候选框的
  • 度量学习(Metric learning)—— 基于分类损失函数(softmax、交叉熵、cosface、arcface)

    概述 首先 xff0c 我们把loss归为两类 xff1a 一类是本篇讲述的基于softmax的 xff0c 一类是基于pair对的 xff08 如对比损失 三元损失等 xff09 基于pair对的 xff0c 参考我的另一篇博客 xff1
  • Oauth2知识总结

    官网 xff1a OAuth Community Site OAuth是一个关于授权 xff08 authorization xff09 的开放网络工业标准 xff0c 允许用户授权第三方应用访问用户存储在其它应用上的信息 xff0c 而不
  • 重构技巧之策略模式优化业务代码

    重构技巧之策略模式优化业务代码 策略模式对业务代码进行重构背景分析 在日常的开发过程中 xff0c 我们肯定会遇到很多if else或者switch case的业务代码 xff0c 作为维护这类代码的开发者来说 xff0c 分支太长 xff
  • 64位Ubuntu使用john破解密码的No password hashes loaded

    最近研究了一下Linux的密码破解 xff0c 因为正好在学习computer security 计算机信息安全 这门课 我在使用 john the ripper 的时候遇到了一个问题 No password hashes loaded 今
  • Java常量池详解之抓狂的面试题

    今天My partner问我一个让他头疼的Java question xff0c 求输出结果 xff1a 64 author DreamSea 2011 11 19 public class IntegerTest public stati
  • PC软件问题定位工具-windbg

    windbg工具使用 windbg是微软的工具 xff0c 可以从百度或微软官网获取 工具支持 xff1a 分析dmp文件 定位CPU 内存 崩溃等异常问题 代替VS调试C 43 43 程序 这里主要整理了收集或分析dmp文件的相关命令 x
  • Ubuntu18.04使用RealVNC进行远程桌面连接

    可以直接查看最新的 xff1a RealVNC Server Ubuntu 20 04 无显示器连接 虚拟显示器 捉不住的鼬鼠的足迹 CSDN博客 使用Linux服务器 xff0c 在一般情况下是不太用桌面环境的 不过现在我想着开发用Lin
  • CMakeLists.txt 详解

    目录 CMakeLists txt用例详解 xff08 WDS中的用例 xff09 CMakeLists txt作用 生成对象库OBJECT实例 xff08 wds libwds common CMakeLists txt xff09 生成
  • ubuntu16.10安装numpy, scipy, matplotlib

    在Python3 x中安装numpy sudo apt get span class hljs keyword install span python3 pip pip3 span class hljs keyword install sp
  • Linux进程状态分析

    最近在看APUE过程中 xff0c 遇到了一个有关于进程的 僵死进程 的状态 既然遇到了进程状态的问题 xff0c 索性就查了查 Linux内核设计与实现 xff0c 里面给出了5种状态 xff0c 分别是 TASK RUNNING TAS
  • IDEA自动生成Javadoc代码注释

    在日常写代码时往往不会注重注释的格式 规范等问题 xff0c 可能注释都不会写 xff0c 但是一旦代码完成后要交付他人 xff0c 就需要考虑注释的问题了 xff0c 因为重要函数 方法的注释往往对整个代码的阅读起着十分重要的作用 xff
  • VNC连接远程服务器

    记录探索之路 由于跑深度学习算法 xff0c 需要连接服务器 xff0c 以前都是利用XShell连接 xff0c 也比较好用 xff0c 但是没有界面 VNC可以展示界面 xff0c 更加清晰 xff0c 以下是探索的方法 1 下载软件
  • Linux文件权限管理命令学习

    你必须非常努力 xff0c 才能看起来毫不费力 xff01 微信搜索公众号 漫漫Coding路 xff0c 一起From Zero To Hero 前言 本篇文章主要讨论Linux中的文件权限管理命令 xff0c 包括更改文件权限 文件所有
  • App移动端测试-Fiddler工作场景总结

    文章目录 一 测试思路1 1App测试内容1 2APP功能测试思路 二 Fiddler测试环境配置2 1Fiddler PC配置2 2模拟器端配置2 3模拟器端代理设置 三 Fiddler测试工作应用场景3 1 Fiddler抓包辅助定位B
  • 当Linux配置zh_CN.UTF-8 ,中文还是显示乱码解决办法

    文章目录 一 出现问题的可能原因1 服务器没有安装zh CN UTF 8 字符集2 远程登录软件字符设置 这篇博客主要说明出现问题的原因和解决思路 一 出现问题的可能原因 1 服务器没有安装zh CN UTF 8 字符集 安装对应的软件包就
  • tar (child): lbzip2: Cannot exec: No such file or directory 解决方法

    tar child lbzip2 Cannot exec No such file or directory 解决方法 今天用tar命令解压文件的时候出错了 xff0c 信息如下 xff1a tar child lbzip2 Cannot
  • openstack newton Linuxbridge改ovs并配置dvr

    这几天一直在搞dvr xff0c 现在终于搞好了 网上的资料比较杂乱 xff0c 期间也一直在各种尝试 xff0c 步骤也很繁琐而且混乱 xff0c 坑比较多 xff0c 现在整理一下 官方安装文档从前几个版本开始在 配置网络的时候就由ov
  • Android jcenter bad gateway 502(Unable to load Maven meta-data from https://jcenter.bintray.com)

    今天在Android studio运行项目的时候报了如下错误 xff0c 项目都编译不过了 xff0c 顿时慌 这里附上gradle额下载地址 gradle Error Could not resolve all files for con

随机推荐

  • 优化Webview加载速度 TBS(腾讯浏览服务X5内核) | VasSonic(提升H5首屏加载速度)

    浏览增强 传统系统内核 Webview 存在适配成本高 不安全 不稳定 耗流量 速度慢 视频播放差 文件能力差等问题 xff0c 这是移动应用开发商在进行Hybrid App开发时普遍面临的难题 腾讯浏览服务基于腾讯X5内核解决方案 xff
  • 稀疏矩阵求解工具AMGX

    之前稀疏矩阵求解 xff0c 使用mkl 43 Eigen xff0c 1500 1500 2规模的稀疏矩阵求解时间为9秒 xff0c 后来使用AMGX求解 xff0c 求解时间提升至0 02秒 AMGX主要使用了mpi和cuda来进行加速
  • k8s中pod sandbox创建失败"failed to start sandbox container"

    背景 今天在k8s更新服务时 发现pod启动失败 报错failed to start sandbox container 如下所示 Events Type Reason Age From Message
  • GO语言入门1:基本数据类型

    一 GO语法结构 1 示例代码 package main 包声明 xff0c 必须出现在源文件第一行 xff0c 指明文件处于哪个包 import 34 fmt 34 引入文件中需要的包文件 func main 文件执行入口 这是我的第一个
  • GO语言入门2:

    四 运算符 1 算数运算符 43 xff1a 值为商 xff1a 取余 43 43 2 关系运算符 61 61 61 gt lt gt 61 lt 61 3 逻辑运算符 amp amp 4 位运算符 amp lt lt gt gt 5 赋值
  • Go语言入门2-指针问题:同一地址取值,*(&a)与*ip值不同?

    一 测试结果 二 测试代码 package main import 34 fmt 34 func main var a int 61 20 声明实际变量 var ip int 声明指针变量 ip 61 amp a 指针变量的存储地址 fmt
  • Google 用搜索追踪流感趋势

    Google 周二发布了一个新网站 http www google org flutrends 用来追踪流感趋势 该服务使用了与 Google Trends 一样的关键词追踪技术 xff0c 对人们输入的 flu 一类的词汇进行追踪 xff
  • openCV(Java版):直接操作像素点的实例

    最近看了平均脸的一些东西 xff0c 试了一下午没有装成功dlib xff0c 因此就简单的将两张图片对应位置相加 xff0c 然后取平均 xff0c 虽然很简单 xff0c 但是一直纠结在如何操作像素的问题 程序具体如下 xff1a im
  • openCv+Java实现人脸剪切

    学习需要 xff0c 对手里人脸图片进行了剪切 xff0c 将人脸图像铺满整张图片 FaceCrop java import org opencv core Core import org opencv core Mat import or
  • selenium之ChromeDriver与版本下载

    最近开始学习爬虫 xff0c 遇到使用selenium工具 xff0c 需要下载ChromeDriver xff0c 我的Chrome版本是65 xff0c 网上大多信息是60版本的 xff0c 但是Driver很多 xff0c 然后发现D
  • 视觉场景理解论文阅读笔记2:Hierarchically Structured Reinforcement Learning for Topically Coherent Visual Story

    一 文章相关资料 论文地址 点击打开链接 二 阅读笔记 1 论文思想 针对序列图像生成故事描述的需求 xff0c 使用层次结构的网络进行解码学习 高级网络用于学习序列中每幅图像的语义信息 xff0c 所属主题 xff1b 低级网络用于根据学
  • 自动驾驶数据集梳理

    1 Kitty数据集 数据链接 xff1a http www cvlibs net datasets kitti 主要应用方向 xff1a 用于评测立体图像 stereo xff0c 光流 optical flow xff0c 视觉测距 v
  • 去除Chrome空白页的缩略图

    文章目录 Chrome 74 0 xx xff08 2019 05 08更新 xff09 Chrome 73 0 3683 103 xff08 2019 04 15更新 xff09 Chrome 新版本处理 xff08 2018 11 16
  • “数字化”与“信息化”的区别是什么?

    大家应该都注意到了 xff0c 前些年都在提信息化 xff0c 近几年又在提数字化 xff0c 数字孪生 xff0c 但是 数字化 和 信息化 到底有什么区别呢 xff1f 今天看到了数字化专家付晓岩老师的回答 xff0c 感觉非常经典受用
  • oauth2密码授权模式

    Oauth2提供的默认端点 oauth authorize xff1a 授权端点 oauth token xff1a 令牌端点 oauth confirm access xff1a 用户确认授权提交端点 oauth error xff1a
  • 全屏网页时钟屏保flipclock-beautify,简约风格,电脑手机均支持访问

    简介 这是一个全屏网页时钟屏保 xff08 桌面时钟 xff09 xff0c 简约风格 爱学习爱工作的你一定会喜欢它滴 全屏时钟显示效果 特点 支持背景图片显示与隐藏支持不同的时钟样式显示支持本地图片加载支持随机互联网超清图片及分辨率切换支
  • ROS-学习笔记-06- Docker安装ROS、ROS VNC & Docker常用命令

    使用Docker安装ros可以避免需要同时开多个虚拟机模拟不同版本ros和不同版本机器人的情况 目录 安装DockerDAOCloud一键安装其他安装方法注意要卸载旧docker用户设置问题 拉取ROS镜像1 Xserver 显示2 打包好
  • RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED

    问题 xff1a 调用显卡时 xff0c 出现RuntimeError cuDNN error CUDNN STATUS NOT INITIALIZED 问题分析 xff1a 出现这种问题 xff0c 一般是因为cuda cudnn 显卡驱
  • 学习PCL库:PCL库中surface模块

    公众号致力于点云处理 xff0c SLAM xff0c 三维视觉 xff0c 高精地图等领域相关内容的干货分享 xff0c 欢迎各位加入 xff0c 有兴趣的可联系dianyunpcl 64 163 com 未经作者允许请勿转载 xff0c
  • Android硬编解码接口MediaCodec使用完全解析(一)

    0 本文概述 MediaCodec是android api 16以后开放的硬编解码接口 xff0c 英文文档参照这个链接 xff0c 中文翻译可以参考这个链接 本文主要记录的是如何使用MediaCodec对视频进行编解码 xff0c 最后会