1. 程式人生 > >Android使用MediaCodec硬解碼播放H264格式視訊檔案

Android使用MediaCodec硬解碼播放H264格式視訊檔案

  前些時間,通過各種搜尋加請教了好幾個同行的朋友,在他們的指點下實現:
  RTSP+H264實時視訊播放播放及把實時視訊流儲存到手機SD卡中,再對儲存的H264格式檔案進行播放等基本功能。
  非常感謝這些朋友的無私幫忙,在實現功能的同時,我也把他們提供的一些程式碼加自己的修改簡單記錄下來,希望能給有需要的朋友一點點幫助。
  這篇部落格就是簡單記錄用MediaCodec +SurfaceView解碼播放本地H264檔案。MediaCodec硬解碼實現RTSP+H264實時視訊播放完整功能可以參考:
https://github.com/ldm520/ANDROID_MEDIACODEC_RTSP_H264
public class ParseH264FileActivity extends Activity {
    private SurfaceView mSurface = null;
    private SurfaceHolder mSurfaceHolder;
    private Thread mDecodeThread;
    private MediaCodec mCodec;
    private boolean mStopFlag = false;
    private DataInputStream mInputStream;
    private String FileName = "test.h264"
; private int Video_Width = 1920; private int Video_Height = 1080; private int FrameRate = 15; private Boolean isUsePpsAndSps = false; private String filePath = Environment.getExternalStorageDirectory() + "/" + FileName; private Handler mHandler = new Handler() { @Override
public void handleMessage(Message msg) { super.handleMessage(msg); Toast.makeText(ParseH264FileActivity.this, "播放結束!", Toast.LENGTH_LONG).show(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //保持螢幕常亮 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); File f = new File(filePath); if (null == f || !f.exists() || f.length() == 0) { Toast.makeText(this, "指定檔案不存在", Toast.LENGTH_LONG).show(); return; } try { //獲取檔案輸入流 mInputStream = new DataInputStream(new FileInputStream(new File(filePath))); } catch (FileNotFoundException e) { e.printStackTrace(); } mSurface = (SurfaceView) findViewById(R.id.preview); mSurfaceHolder = mSurface.getHolder(); mSurfaceHolder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { try { //通過多媒體格式名建立一個可用的解碼器 mCodec = MediaCodec.createDecoderByType("video/avc"); } catch (IOException e) { e.printStackTrace(); } //初始化編碼器 final MediaFormat mediaformat = MediaFormat.createVideoFormat("video/avc", Video_Width, Video_Height); //獲取h264中的pps及sps資料 if (isUsePpsAndSps) { byte[] header_sps = {0, 0, 0, 1, 103, 66, 0, 42, (byte) 149, (byte) 168, 30, 0, (byte) 137, (byte) 249, 102, (byte) 224, 32, 32, 32, 64}; byte[] header_pps = {0, 0, 0, 1, 104, (byte) 206, 60, (byte) 128, 0, 0, 0, 1, 6, (byte) 229, 1, (byte) 151, (byte) 128}; mediaformat.setByteBuffer("csd-0", ByteBuffer.wrap(header_sps)); mediaformat.setByteBuffer("csd-1", ByteBuffer.wrap(header_pps)); } //設定幀率 mediaformat.setInteger(MediaFormat.KEY_FRAME_RATE, FrameRate); //https://developer.android.com/reference/android/media/MediaFormat.html#KEY_MAX_INPUT_SIZE //設定配置引數,引數介紹 : // format 如果為解碼器,此處表示輸入資料的格式;如果為編碼器,此處表示輸出資料的格式。 //surface 指定一個surface,可用作decode的輸出渲染。 //crypto 如果需要給媒體資料加密,此處指定一個crypto類. // flags 如果正在配置的物件是用作編碼器,此處加上CONFIGURE_FLAG_ENCODE 標籤。 mCodec.configure(mediaformat, holder.getSurface(), null, 0); startDecodingThread(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } }); } private void startDecodingThread() { mCodec.start(); mDecodeThread = new Thread(new decodeH264Thread()); mDecodeThread.start(); } /** * @author ldm * @description 解碼執行緒 * @time 2016/12/19 16:36 */ private class decodeH264Thread implements Runnable { @Override public void run() { try { decodeLoop(); } catch (Exception e) { } } private void decodeLoop() { //存放目標檔案的資料 ByteBuffer[] inputBuffers = mCodec.getInputBuffers(); //解碼後的資料,包含每一個buffer的元資料資訊,例如偏差,在相關解碼器中有效的資料大小 MediaCodec.BufferInfo info = new MediaCodec.BufferInfo(); long startMs = System.currentTimeMillis(); long timeoutUs = 10000; byte[] marker0 = new byte[]{0, 0, 0, 1}; byte[] dummyFrame = new byte[]{0x00, 0x00, 0x01, 0x20}; byte[] streamBuffer = null; try { streamBuffer = getBytes(mInputStream); } catch (IOException e) { e.printStackTrace(); } int bytes_cnt = 0; while (mStopFlag == false) { bytes_cnt = streamBuffer.length; if (bytes_cnt == 0) { streamBuffer = dummyFrame; } int startIndex = 0; int remaining = bytes_cnt; while (true) { if (remaining == 0 || startIndex >= remaining) { break; } int nextFrameStart = KMPMatch(marker0, streamBuffer, startIndex + 2, remaining); if (nextFrameStart == -1) { nextFrameStart = remaining; } else { } int inIndex = mCodec.dequeueInputBuffer(timeoutUs); if (inIndex >= 0) { ByteBuffer byteBuffer = inputBuffers[inIndex]; byteBuffer.clear(); byteBuffer.put(streamBuffer, startIndex, nextFrameStart - startIndex); //在給指定Index的inputbuffer[]填充資料後,呼叫這個函式把資料傳給解碼器 mCodec.queueInputBuffer(inIndex, 0, nextFrameStart - startIndex, 0, 0); startIndex = nextFrameStart; } else { Log.e(Constant.LOG_TAG, "aaaaa"); continue; } int outIndex = mCodec.dequeueOutputBuffer(info, timeoutUs); if (outIndex >= 0) { //幀控制是不在這種情況下工作,因為沒有PTS H264是可用的 while (info.presentationTimeUs / 1000 > System.currentTimeMillis() - startMs) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } boolean doRender = (info.size != 0); //對outputbuffer的處理完後,呼叫這個函式把buffer重新返回給codec類。 mCodec.releaseOutputBuffer(outIndex, doRender); } else { Log.e(Constant.LOG_TAG, "bbbb"); } } mStopFlag = true; mHandler.sendEmptyMessage(0); } } } public static byte[] getBytes(InputStream is) throws IOException { int len; int size = 1024; byte[] buf; if (is instanceof ByteArrayInputStream) { size = is.available(); buf = new byte[size]; len = is.read(buf, 0, size); } else { // BufferedOutputStream bos=new BufferedOutputStream(new ByteArrayOutputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); buf = new byte[size]; while ((len = is.read(buf, 0, size)) != -1) bos.write(buf, 0, len); buf = bos.toByteArray(); } Log.e(Constant.LOG_TAG, "bbbb"); return buf; } private int KMPMatch(byte[] pattern, byte[] bytes, int start, int remain) { try { Thread.sleep(30); } catch (InterruptedException e) { e.printStackTrace(); } int[] lsp = computeLspTable(pattern); int j = 0; // Number of chars matched in pattern for (int i = start; i < remain; i++) { while (j > 0 && bytes[i] != pattern[j]) { // Fall back in the pattern j = lsp[j - 1]; // Strictly decreasing } if (bytes[i] == pattern[j]) { // Next char matched, increment position j++; if (j == pattern.length) return i - (j - 1); } } return -1; // Not found } private int[] computeLspTable(byte[] pattern) { int[] lsp = new int[pattern.length]; lsp[0] = 0; // Base case for (int i = 1; i < pattern.length; i++) { // Start by assuming we're extending the previous LSP int j = lsp[i - 1]; while (j > 0 && pattern[i] != pattern[j]) j = lsp[j - 1]; if (pattern[i] == pattern[j]) j++; lsp[i] = j; } return lsp; } }