当前位置:   article > 正文

Android硬编解码接口MediaCodec使用完全解析(一)_mediacodec 解码后立刻输出

mediacodec 解码后立刻输出

使用异步读取编码(解码)后的数据,效率会大增。

可以直接起一个线程不断地读。

 

---------------------------------------------------------------------------------------------------------------

https://blog.csdn.net/u013028621/article/details/62417181

 

0、本文概述

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

1、MediaCodec编码视频

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

  1. MediaCodec createByCodecName (String name);
  2. MediaCodec createDecoderByType (String type);
  • 具体可用的name和type参考文档即可。这里我们通过后者来初始化一个视频编码器。
mMC = MediaCodec.createDecoderByType(MIME_TYPE);
  •  

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

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

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

  1. mMC.start();
  2. mInputBuffers = mMC.getInputBuffers();
  3. mOutputBuffers = mMC.getOutputBuffers();
  •  

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

int inputbufferindex = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);
  •  

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

  1. ByteBuffer inputBuffer = mInputBuffers[inputbufferindex];
  2. inputBuffer.clear();//清除原来的内容以接收新的内容
  3. inputBuffer.put(bytes, 0, len);//len是传进来的有效数据长度
  4. 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(包含在编码出来的第一帧数据)

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

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

  1. mMC.start();
  2. mInputBuffers = mMC.getInputBuffers();
  3. mOutputBuffers = mMC.getOutputBuffers();
  •  

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

int inputbufferindex = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);
  •  

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

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

2)然后输入数据

  1. inputBuffer.put(bytes, 0, len);
  2. 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

  1. package com.example.mediacodecpro;
  2. import android.media.MediaCodec;
  3. import android.media.MediaCodecInfo;
  4. import android.media.MediaFormat;
  5. import android.util.Log;
  6. import java.io.IOException;
  7. import java.nio.ByteBuffer;
  8. /**
  9. * Created by chuibai on 2017/3/10.<br />
  10. */
  11. public class Encoder {
  12. public static final int TRY_AGAIN_LATER = -1;
  13. public static final int BUFFER_OK = 0;
  14. public static final int BUFFER_TOO_SMALL = 1;
  15. public static final int OUTPUT_UPDATE = 2;
  16. private int format = 0;
  17. private final String MIME_TYPE = "video/avc";
  18. private MediaCodec mMC = null;
  19. private MediaFormat mMF;
  20. private ByteBuffer[] inputBuffers;
  21. private ByteBuffer[] outputBuffers;
  22. private long BUFFER_TIMEOUT = 0;
  23. private MediaCodec.BufferInfo mBI;
  24. /**
  25. * 初始化编码器
  26. * @throws IOException 创建编码器失败会抛出异常
  27. */
  28. public void init() throws IOException {
  29. mMC = MediaCodec.createEncoderByType(MIME_TYPE);
  30. format = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar;
  31. mBI = new MediaCodec.BufferInfo();
  32. }
  33. /**
  34. * 配置编码器,需要配置颜色、帧率、比特率以及视频宽高
  35. * @param width 视频的宽
  36. * @param height 视频的高
  37. * @param bitrate 视频比特率
  38. * @param framerate 视频帧率
  39. */
  40. public void configure(int width,int height,int bitrate,int framerate){
  41. if(mMF == null){
  42. mMF = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
  43. mMF.setInteger(MediaFormat.KEY_BIT_RATE, bitrate);
  44. mMF.setInteger(MediaFormat.KEY_FRAME_RATE, framerate);
  45. if (format != 0){
  46. mMF.setInteger(MediaFormat.KEY_COLOR_FORMAT, format);
  47. }
  48. mMF.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, -1); //关键帧间隔时间 单位s
  49. }
  50. mMC.configure(mMF,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
  51. }
  52. /**
  53. * 开启编码器,获取输入输出缓冲区
  54. */
  55. public void start(){
  56. mMC.start();
  57. inputBuffers = mMC.getInputBuffers();
  58. outputBuffers = mMC.getOutputBuffers();
  59. }
  60. /**
  61. * 向编码器输入数据,此处要求输入YUV420P的数据
  62. * @param data YUV数据
  63. * @param len 数据长度
  64. * @param timestamp 时间戳
  65. * @return
  66. */
  67. public int input(byte[] data,int len,long timestamp){
  68. int index = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);
  69. Log.e("...","" + index);
  70. if(index >= 0){
  71. ByteBuffer inputBuffer = inputBuffers[index];
  72. inputBuffer.clear();
  73. if(inputBuffer.capacity() < len){
  74. mMC.queueInputBuffer(index, 0, 0, timestamp, 0);
  75. return BUFFER_TOO_SMALL;
  76. }
  77. inputBuffer.put(data,0,len);
  78. mMC.queueInputBuffer(index,0,len,timestamp,0);
  79. }else{
  80. return index;
  81. }
  82. return BUFFER_OK;
  83. }
  84. /**
  85. * 输出编码后的数据
  86. * @param data 数据
  87. * @param len 有效数据长度
  88. * @param ts 时间戳
  89. * @return
  90. */
  91. public int output(/*out*/byte[] data,/* out */int[] len,/* out */long[] ts){
  92. int i = mMC.dequeueOutputBuffer(mBI, BUFFER_TIMEOUT);
  93. if(i >= 0){
  94. if(mBI.size > data.length) return BUFFER_TOO_SMALL;
  95. outputBuffers[i].position(mBI.offset);
  96. outputBuffers[i].limit(mBI.offset + mBI.size);
  97. outputBuffers[i].get(data, 0, mBI.size);
  98. len[0] = mBI.size ;
  99. ts[0] = mBI.presentationTimeUs;
  100. mMC.releaseOutputBuffer(i, false);
  101. } else if (i == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
  102. outputBuffers = mMC.getOutputBuffers();
  103. return OUTPUT_UPDATE;
  104. } else if (i == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
  105. mMF = mMC.getOutputFormat();
  106. return OUTPUT_UPDATE;
  107. } else if (i == MediaCodec.INFO_TRY_AGAIN_LATER) {
  108. return TRY_AGAIN_LATER;
  109. }
  110. return BUFFER_OK;
  111. }
  112. public void release(){
  113. mMC.stop();
  114. mMC.release();
  115. mMC = null;
  116. outputBuffers = null;
  117. inputBuffers = null;
  118. }
  119. public void flush() {
  120. mMC.flush();
  121. }
  122. }
  •  

3.3解码器类Decoder

  1. package com.example.mediacodecpro;
  2. import android.media.MediaCodec;
  3. import android.media.MediaFormat;
  4. import android.view.Surface;
  5. import java.io.IOException;
  6. import java.nio.ByteBuffer;
  7. /**
  8. * Created by chuibai on 2017/3/10.<br />
  9. */
  10. public class Decoder {
  11. public static final int TRY_AGAIN_LATER = -1;
  12. public static final int BUFFER_OK = 0;
  13. public static final int BUFFER_TOO_SMALL = 1;
  14. public static final int OUTPUT_UPDATE = 2;
  15. private final String MIME_TYPE = "video/avc";
  16. private MediaCodec mMC = null;
  17. private MediaFormat mMF;
  18. private long BUFFER_TIMEOUT = 0;
  19. private MediaCodec.BufferInfo mBI;
  20. private ByteBuffer[] mInputBuffers;
  21. private ByteBuffer[] mOutputBuffers;
  22. /**
  23. * 初始化编码器
  24. * @throws IOException 创建编码器失败会抛出异常
  25. */
  26. public void init() throws IOException {
  27. mMC = MediaCodec.createDecoderByType(MIME_TYPE);
  28. mBI = new MediaCodec.BufferInfo();
  29. }
  30. /**
  31. * 配置解码器
  32. * @param sps 用于配置的sps参数
  33. * @param pps 用于配置的pps参数
  34. * @param surface 用于解码显示的Surface
  35. */
  36. public void configure(byte[] sps, byte[] pps, Surface surface){
  37. int[] width = new int[1];
  38. int[] height = new int[1];
  39. AvcUtils.parseSPS(sps, width, height);//从sps中解析出视频宽高
  40. mMF = MediaFormat.createVideoFormat(MIME_TYPE, width[0], height[0]);
  41. mMF.setByteBuffer("csd-0", ByteBuffer.wrap(sps));
  42. mMF.setByteBuffer("csd-1", ByteBuffer.wrap(pps));
  43. mMF.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, width[0] * height[0]);
  44. mMC.configure(mMF, surface, null, 0);
  45. }
  46. /**
  47. * 开启解码器,获取输入输出缓冲区
  48. */
  49. public void start(){
  50. mMC.start();
  51. mInputBuffers = mMC.getInputBuffers();
  52. mOutputBuffers = mMC.getOutputBuffers();
  53. }
  54. /**
  55. * 输入数据
  56. * @param data 输入的数据
  57. * @param len 数据有效长度
  58. * @param timestamp 时间戳
  59. * @return 成功则返回{@link #BUFFER_OK} 否则返回{@link #TRY_AGAIN_LATER}
  60. */
  61. public int input(byte[] data,int len,long timestamp){
  62. int i = mMC.dequeueInputBuffer(BUFFER_TIMEOUT);
  63. if(i >= 0){
  64. ByteBuffer inputBuffer = mInputBuffers[i];
  65. inputBuffer.clear();
  66. inputBuffer.put(data, 0, len);
  67. mMC.queueInputBuffer(i, 0, len, timestamp, 0);
  68. }else {
  69. return TRY_AGAIN_LATER;
  70. }
  71. return BUFFER_OK;
  72. }
  73. public int output(byte[] data,int[] len,long[] ts){
  74. int i = mMC.dequeueOutputBuffer(mBI, BUFFER_TIMEOUT);
  75. if(i >= 0){
  76. if (mOutputBuffers[i] != null)
  77. {
  78. mOutputBuffers[i].position(mBI.offset);
  79. mOutputBuffers[i].limit(mBI.offset + mBI.size);
  80. if (data != null)
  81. mOutputBuffers[i].get(data, 0, mBI.size);
  82. len[0] = mBI.size;
  83. ts[0] = mBI.presentationTimeUs;
  84. }
  85. mMC.releaseOutputBuffer(i, true);
  86. }else{
  87. return TRY_AGAIN_LATER;
  88. }
  89. return BUFFER_OK;
  90. }
  91. public void flush(){
  92. mMC.flush();
  93. }
  94. public void release() {
  95. flush();
  96. mMC.stop();
  97. mMC.release();
  98. mMC = null;
  99. mInputBuffers = null;
  100. mOutputBuffers = null;
  101. }
  102. }
  • 3.4MainAcitivity
  1. package com.example.mediacodecpro;
  2. import android.content.pm.ActivityInfo;
  3. import android.graphics.ImageFormat;
  4. import android.hardware.Camera;
  5. import android.os.Bundle;
  6. import android.os.Handler;
  7. import android.os.Looper;
  8. import android.os.Message;
  9. import android.support.v7.app.AppCompatActivity;
  10. import android.util.Log;
  11. import android.view.SurfaceView;
  12. import android.view.View;
  13. import android.widget.Button;
  14. import android.widget.TextView;
  15. import java.io.IOException;
  16. import java.io.OutputStream;
  17. import java.net.DatagramPacket;
  18. import java.net.DatagramSocket;
  19. import java.net.InetAddress;
  20. import java.net.Socket;
  21. import java.nio.ByteBuffer;
  22. import java.util.Iterator;
  23. import java.util.LinkedList;
  24. import java.util.Queue;
  25. import butterknife.BindView;
  26. import butterknife.ButterKnife;
  27. public class MainActivity extends AppCompatActivity implements View.OnClickListener, Camera.PreviewCallback {
  28. @BindView(R.id.surfaceView_encode)
  29. SurfaceView surfaceViewEncode;
  30. @BindView(R.id.surfaceView_decode)
  31. SurfaceView surfaceViewDecode;
  32. @BindView(R.id.btnStart)
  33. Button btnStart;
  34. @BindView(R.id.btnStop)
  35. Button btnStop;
  36. @BindView(R.id.capture)
  37. TextView capture;
  38. private int width;
  39. private int height;
  40. private int bitrate;
  41. private int framerate;
  42. private int captureFrame;
  43. private Camera mCamera;
  44. private Queue<PreviewBufferInfo> mPreviewBuffers_clean;
  45. private Queue<PreviewBufferInfo> mPreviewBuffers_dirty;
  46. private Queue<PreviewBufferInfo> mDecodeBuffers_clean;
  47. private Queue<PreviewBufferInfo> mDecodeBuffers_dirty;
  48. private int PREVIEW_POOL_CAPACITY = 5;
  49. private int format;
  50. private int DECODE_UNI_SIZE = 1024 * 1024;
  51. private byte[] mAvcBuf = new byte[1024 * 1024];
  52. private final int MSG_ENCODE = 0;
  53. private final int MSG_DECODE = 1;
  54. private String TAG = "MainActivity";
  55. private long mLastTestTick = 0;
  56. private Object mAvcEncLock;
  57. private Object mDecEncLock;
  58. private Decoder mDecoder;
  59. private Handler codecHandler;
  60. private byte[] mRawData;
  61. private Encoder mEncoder;
  62. private CodecThread codecThread;
  63. private DatagramSocket socket;
  64. private DatagramPacket packet;
  65. private byte[] sps_pps;
  66. private byte[] mPacketBuf = new byte[1024 * 1024];
  67. @Override
  68. protected void onCreate(Bundle savedInstanceState) {
  69. super.onCreate(savedInstanceState);
  70. setContentView(R.layout.activity_main);
  71. ButterKnife.bind(this);
  72. //初始化参数
  73. initParams();
  74. //设置监听事件
  75. btnStart.setOnClickListener(this);
  76. btnStop.setOnClickListener(this);
  77. }
  78. /**
  79. * 初始化参数,包括帧率、颜色、比特率,视频宽高等
  80. */
  81. private void initParams() {
  82. width = 352;
  83. height = 288;
  84. bitrate = 1500000;
  85. framerate = 30;
  86. captureFrame = 0;
  87. format = ImageFormat.YV12;
  88. mAvcEncLock = new Object();
  89. mDecEncLock = new Object();
  90. }
  91. @Override
  92. protected void onResume() {
  93. if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
  94. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  95. }
  96. super.onResume();
  97. }
  98. @Override
  99. public void onClick(View v) {
  100. switch (v.getId()){
  101. case R.id.btnStart:
  102. mCamera = Camera.open(0);
  103. initQueues();
  104. initEncoder();
  105. initCodecThread();
  106. startPreview();
  107. break;
  108. case R.id.btnStop:
  109. releaseCodecThread();
  110. releseEncoderAndDecoder();
  111. releaseCamera();
  112. releaseQueue();
  113. break;
  114. }
  115. }
  116. /**
  117. * 释放队列资源
  118. */
  119. private void releaseQueue() {
  120. if (mPreviewBuffers_clean != null){
  121. mPreviewBuffers_clean.clear();
  122. mPreviewBuffers_clean = null;
  123. }
  124. if (mPreviewBuffers_dirty != null){
  125. mPreviewBuffers_dirty.clear();
  126. mPreviewBuffers_dirty = null;
  127. }
  128. if (mDecodeBuffers_clean != null){
  129. mDecodeBuffers_clean.clear();
  130. mDecodeBuffers_clean = null;
  131. }
  132. if (mDecodeBuffers_dirty != null){
  133. mDecodeBuffers_dirty.clear();
  134. mDecodeBuffers_dirty = null;
  135. }
  136. }
  137. /**
  138. * 释放摄像头资源
  139. */
  140. private void releaseCamera() {
  141. if(mCamera != null){
  142. mCamera.setPreviewCallbackWithBuffer(null);
  143. mCamera.stopPreview();
  144. mCamera.release();
  145. mCamera = null;
  146. }
  147. }
  148. private void releseEncoderAndDecoder() {
  149. if(mEncoder != null){
  150. mEncoder.flush();
  151. mEncoder.release();
  152. mEncoder = null;
  153. }
  154. if(mDecoder != null){
  155. mDecoder.release();
  156. mDecoder = null;
  157. }
  158. }
  159. private void releaseCodecThread() {
  160. codecHandler.getLooper().quit();
  161. codecHandler = null;
  162. codecThread = null;
  163. }
  164. private void initCodecThread() {
  165. codecThread = new CodecThread();
  166. codecThread.start();
  167. }
  168. /**
  169. * 开启预览
  170. */
  171. private void startPreview() {
  172. Camera.Parameters parameters = mCamera.getParameters();
  173. parameters.setPreviewFormat(format);
  174. parameters.setPreviewFrameRate(framerate);
  175. parameters.setPreviewSize(width,height);
  176. mCamera.setParameters(parameters);
  177. try {
  178. mCamera.setPreviewDisplay(surfaceViewEncode.getHolder());
  179. } catch (IOException e) {
  180. e.printStackTrace();
  181. }
  182. mCamera.setPreviewCallbackWithBuffer(this);
  183. mCamera.startPreview();
  184. }
  185. @Override
  186. public void onPreviewFrame(byte[] data, Camera camera) {
  187. /** 预览的datanull */
  188. if(data == null) {
  189. Log.e(TAG,"预览的data为null");
  190. return;
  191. }
  192. long curTick = System.currentTimeMillis();
  193. if (mLastTestTick == 0) {
  194. mLastTestTick = curTick;
  195. }
  196. if (curTick > mLastTestTick + 1000) {
  197. setCaptureFPSTextView(captureFrame);
  198. captureFrame = 0;
  199. mLastTestTick = curTick;
  200. } else
  201. captureFrame++;
  202. synchronized(mAvcEncLock) {
  203. PreviewBufferInfo info = mPreviewBuffers_clean.poll(); //remove the head of queue
  204. info.buffer = data;
  205. info.size = getPreviewBufferSize(width, height, format);
  206. info.timestamp = System.currentTimeMillis();
  207. mPreviewBuffers_dirty.add(info);
  208. if(mDecoder == null){
  209. codecHandler.sendEmptyMessage(MSG_ENCODE);
  210. }
  211. }
  212. }
  213. private void setCaptureFPSTextView(int captureFrame) {
  214. capture.setText("当前帧率:" + captureFrame);
  215. }
  216. private void initEncoder() {
  217. mEncoder = new Encoder();
  218. try {
  219. mEncoder.init();
  220. mEncoder.configure(width,height,bitrate,framerate);
  221. mEncoder.start();
  222. } catch (IOException e) {
  223. e.printStackTrace();
  224. }
  225. }
  226. /**
  227. * 初始化各种队列
  228. */
  229. private void initQueues() {
  230. if (mPreviewBuffers_clean == null)
  231. mPreviewBuffers_clean = new LinkedList<>();
  232. if (mPreviewBuffers_dirty == null)
  233. mPreviewBuffers_dirty = new LinkedList<>();
  234. int size = getPreviewBufferSize(width, height, format);
  235. for (int i = 0; i < PREVIEW_POOL_CAPACITY; i++) {
  236. byte[] mem = new byte[size];
  237. mCamera.addCallbackBuffer(mem); //ByteBuffer.array is a reference, not a copy
  238. PreviewBufferInfo info = new PreviewBufferInfo();
  239. info.buffer = null;
  240. info.size = 0;
  241. info.timestamp = 0;
  242. mPreviewBuffers_clean.add(info);
  243. }
  244. if (mDecodeBuffers_clean == null)
  245. mDecodeBuffers_clean = new LinkedList<>();
  246. if (mDecodeBuffers_dirty == null)
  247. mDecodeBuffers_dirty = new LinkedList<>();
  248. for (int i = 0; i < PREVIEW_POOL_CAPACITY; i++) {
  249. PreviewBufferInfo info = new PreviewBufferInfo();
  250. info.buffer = new byte[DECODE_UNI_SIZE];
  251. info.size = 0;
  252. info.timestamp = 0;
  253. mDecodeBuffers_clean.add(info);
  254. }
  255. }
  256. /**
  257. * 获取预览buffer的大小
  258. * @param width 预览宽
  259. * @param height 预览高
  260. * @param format 预览颜色格式
  261. * @return 预览buffer的大小
  262. */
  263. private int getPreviewBufferSize(int width, int height, int format) {
  264. int size = 0;
  265. switch (format) {
  266. case ImageFormat.YV12: {
  267. int yStride = (int) Math.ceil(width / 16.0) * 16;
  268. int uvStride = (int) Math.ceil((yStride / 2) / 16.0) * 16;
  269. int ySize = yStride * height;
  270. int uvSize = uvStride * height / 2;
  271. size = ySize + uvSize * 2;
  272. }
  273. break;
  274. case ImageFormat.NV21: {
  275. float bytesPerPix = (float) ImageFormat.getBitsPerPixel(format) / 8;
  276. size = (int) (width * height * bytesPerPix);
  277. }
  278. break;
  279. }
  280. return size;
  281. }
  282. private void swapYV12toI420(byte[] yv12bytes, byte[] i420bytes, int width, int height) {
  283. System.arraycopy(yv12bytes, 0, i420bytes, 0, width * height);
  284. System.arraycopy(yv12bytes, width * height + width * height / 4, i420bytes, width * height, width * height / 4);
  285. System.arraycopy(yv12bytes, width * height, i420bytes, width * height + width * height / 4, width * height / 4);
  286. }
  287. private class PreviewBufferInfo {
  288. public byte[] buffer;
  289. public int size;
  290. public long timestamp;
  291. }
  292. private class CodecThread extends Thread {
  293. @Override
  294. public void run() {
  295. Looper.prepare();
  296. codecHandler = new Handler() {
  297. @Override
  298. public void handleMessage(Message msg) {
  299. switch (msg.what) {
  300. case MSG_ENCODE:
  301. int res = Encoder.BUFFER_OK;
  302. synchronized (mAvcEncLock) {
  303. if (mPreviewBuffers_dirty != null && mPreviewBuffers_clean != null) {
  304. Iterator<PreviewBufferInfo> ite = mPreviewBuffers_dirty.iterator();
  305. while (ite.hasNext()) {
  306. PreviewBufferInfo info = ite.next();
  307. byte[] data = info.buffer;
  308. int data_size = info.size;
  309. if (format == ImageFormat.YV12) {
  310. if (mRawData == null || mRawData.length < data_size) {
  311. mRawData = new byte[data_size];
  312. }
  313. swapYV12toI420(data, mRawData, width, height);
  314. } else {
  315. Log.e(TAG, "preview size MUST be YV12, cur is " + format);
  316. mRawData = data;
  317. }
  318. res = mEncoder.input(mRawData, data_size, info.timestamp);
  319. if (res != Encoder.BUFFER_OK) {
  320. // Log.e(TAG, "mEncoder.input, maybe wrong:" + res);
  321. break; //the rest buffers shouldn't go into encoder, if the previous one get problem
  322. } else {
  323. ite.remove();
  324. mPreviewBuffers_clean.add(info);
  325. if (mCamera != null) {
  326. mCamera.addCallbackBuffer(data);
  327. }
  328. }
  329. }
  330. }
  331. }
  332. while (res == Encoder.BUFFER_OK) {
  333. int[] len = new int[1];
  334. long[] ts = new long[1];
  335. synchronized (mAvcEncLock) {
  336. res = mEncoder.output(mAvcBuf, len, ts);
  337. }
  338. if (res == Encoder.BUFFER_OK) {
  339. //发送h264
  340. if(sps_pps != null){
  341. send(len[0]);
  342. }
  343. if (mDecodeBuffers_clean != null && mDecodeBuffers_dirty != null) {
  344. synchronized (mAvcEncLock) {
  345. Iterator<PreviewBufferInfo> ite = mDecodeBuffers_clean.iterator();
  346. if (ite.hasNext()) {
  347. PreviewBufferInfo bufferInfo = ite.next();
  348. if (bufferInfo.buffer.length >= len[0]) {
  349. bufferInfo.timestamp = ts[0];
  350. bufferInfo.size = len[0];
  351. System.arraycopy(mAvcBuf, 0, bufferInfo.buffer, 0, len[0]);
  352. ite.remove();
  353. mDecodeBuffers_dirty.add(bufferInfo);
  354. } else {
  355. Log.e(TAG, "decoder uni buffer too small, need " + len[0] + " but has " + bufferInfo.buffer.length);
  356. }
  357. }
  358. }
  359. initDecoder(len);
  360. }
  361. }
  362. }
  363. codecHandler.sendEmptyMessageDelayed(MSG_ENCODE, 30);
  364. break;
  365. case MSG_DECODE:
  366. synchronized (mDecEncLock) {
  367. int result = Decoder.BUFFER_OK;
  368. //STEP 1: handle input buffer
  369. if (mDecodeBuffers_dirty != null && mDecodeBuffers_clean != null) {
  370. Iterator<PreviewBufferInfo> ite = mDecodeBuffers_dirty.iterator();
  371. while (ite.hasNext()) {
  372. PreviewBufferInfo info = ite.next();
  373. result = mDecoder.input(info.buffer, info.size, info.timestamp);
  374. if (result != Decoder.BUFFER_OK) {
  375. break; //the rest buffers shouldn't go into encoder, if the previous one get problem
  376. } else {
  377. ite.remove();
  378. mDecodeBuffers_clean.add(info);
  379. }
  380. }
  381. }
  382. int[] len = new int[1];
  383. long[] ts = new long[1];
  384. while (result == Decoder.BUFFER_OK) {
  385. result = mDecoder.output(null, len, ts);
  386. }
  387. }
  388. codecHandler.sendEmptyMessageDelayed(MSG_DECODE, 30);
  389. break;
  390. }
  391. }
  392. };
  393. Looper.loop();
  394. }
  395. }
  396. private void send(int len) {
  397. try {
  398. if(socket == null) socket = new DatagramSocket();
  399. if(packet == null){
  400. packet = new DatagramPacket(mPacketBuf,0,sps_pps.length + len);
  401. packet.setAddress(InetAddress.getByName("192.168.43.1"));
  402. packet.setPort(5006);
  403. }
  404. if(mAvcBuf[4] == 0x65){
  405. System.arraycopy(sps_pps,0,mPacketBuf,0,sps_pps.length);
  406. System.arraycopy(mAvcBuf,0,mPacketBuf,sps_pps.length,len);
  407. len += sps_pps.length;
  408. }else{
  409. System.arraycopy(mAvcBuf,0,mPacketBuf,0,len);
  410. }
  411. packet.setLength(len);
  412. socket.send(packet);
  413. } catch (IOException e) {
  414. e.printStackTrace();
  415. }
  416. }
  417. private void initDecoder(int[] len) {
  418. if(sps_pps == null){
  419. sps_pps = new byte[len[0]];
  420. System.arraycopy(mAvcBuf,0,sps_pps,0,len[0]);
  421. }
  422. if(mDecoder == null){
  423. mDecoder = new Decoder();
  424. try {
  425. mDecoder.init();
  426. } catch (IOException e) {
  427. e.printStackTrace();
  428. }
  429. byte[] sps_nal = null;
  430. int sps_len = 0;
  431. byte[] pps_nal = null;
  432. int pps_len = 0;
  433. ByteBuffer byteb = ByteBuffer.wrap(mAvcBuf, 0, len[0]);
  434. //SPS
  435. if (true == AvcUtils.goToPrefix(byteb)) {
  436. int sps_position = 0;
  437. int pps_position = 0;
  438. int nal_type = AvcUtils.getNalType(byteb);
  439. if (AvcUtils.NAL_TYPE_SPS == nal_type) {
  440. Log.d(TAG, "OutputAvcBuffer, AVC NAL type: SPS");
  441. sps_position = byteb.position() - AvcUtils.START_PREFIX_LENGTH - AvcUtils.NAL_UNIT_HEADER_LENGTH;
  442. //PPS
  443. if (true == AvcUtils.goToPrefix(byteb)) {
  444. nal_type = AvcUtils.getNalType(byteb);
  445. if (AvcUtils.NAL_TYPE_PPS == nal_type) {
  446. pps_position = byteb.position() - AvcUtils.START_PREFIX_LENGTH - AvcUtils.NAL_UNIT_HEADER_LENGTH;
  447. sps_len = pps_position - sps_position;
  448. sps_nal = new byte[sps_len];
  449. int cur_pos = byteb.position();
  450. byteb.position(sps_position);
  451. byteb.get(sps_nal, 0, sps_len);
  452. byteb.position(cur_pos);
  453. //slice
  454. if (true == AvcUtils.goToPrefix(byteb)) {
  455. nal_type = AvcUtils.getNalType(byteb);
  456. int pps_end_position = byteb.position() - AvcUtils.START_PREFIX_LENGTH - AvcUtils.NAL_UNIT_HEADER_LENGTH;
  457. pps_len = pps_end_position - pps_position;
  458. } else {
  459. pps_len = byteb.position() - pps_position;
  460. //pps_len = byteb.limit() - pps_position + 1;
  461. }
  462. if (pps_len > 0) {
  463. pps_nal = new byte[pps_len];
  464. cur_pos = byteb.position();
  465. byteb.position(pps_position);
  466. byteb.get(pps_nal, 0, pps_len);
  467. byteb.position(cur_pos);
  468. }
  469. } else {
  470. //Log.d(log_tag, "OutputAvcBuffer, AVC NAL type: "+nal_type);
  471. throw new UnsupportedOperationException("SPS is not followed by PPS, nal type :" + nal_type);
  472. }
  473. }
  474. } else {
  475. //Log.d(log_tag, "OutputAvcBuffer, AVC NAL type: "+nal_type);
  476. }
  477. //2. configure AVC decoder with SPS/PPS
  478. if (sps_nal != null && pps_nal != null) {
  479. int[] width = new int[1];
  480. int[] height = new int[1];
  481. AvcUtils.parseSPS(sps_nal, width, height);
  482. mDecoder.configure(sps_nal, pps_nal,surfaceViewDecode.getHolder().getSurface());
  483. mDecoder.start();
  484. if (codecHandler != null) {
  485. codecHandler.sendEmptyMessage(MSG_DECODE);
  486. }
  487. }
  488. }
  489. }
  490. }
  491. }
  •  

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

4.要点总结

个人总结使用MediaCodec编解码的时候主要需要注意以下事项: 
- 数据的输入和输出要异步进行,不要采用阻塞的方式等待输出数据 
- 编码Camera预览数据的时候使用带buffer的预览回调,避免帧率过低 
- 适当使用缓存队列,不要每一帧都new一个byte数组,避免频繁的GC 
- 不要在主线程进行操作,在我学习的过程中看到有些朋友直接在预览回调里进行编解码,在dequeueOutputBuffer方法还传递-1,也就是无限等待程序返回 
上述实例地址:点击这里,由于我一直没有积分去下载东西,所以下载收1个积分。如果有任何问题,欢迎指正,相互学习

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/684813
推荐阅读
相关标签
  

闽ICP备14008679号