androidAndroid技术安卓开发

Android音视频开发——MediaCodec播放H264视频

2021-08-23  本文已影响0人  Peakmain

前言

基本知识

  0110  0111
&    1  1111
   0000 0111=7
image.png

所以67实际就是sps

为什么视频编码采用YUV而不是rgb

MediaCodec概念

流程过程
image.png

大家可能不太容易明白,我画了一个图


image.png

实现H264播放

image.png
    /**
     * 找到下一帧
     */
    private int findByFrame(byte[] bytes, int start, int totalSize) {
        for (int i = start; i < totalSize - 4; i++) {
            //0x 00 00 00 01
            if (bytes[i] == 0x00 && bytes[i + 1] == 0x00 && bytes[i + 2] == 0x00 && bytes[i + 3] == 0x01) {
                return i;
            }
        }
        return -1;
    }
    public void configure(
            @Nullable MediaFormat format,
            @Nullable Surface surface,
               @Nullable MediaCrypto crypto,//加密
            @ConfigureFlag int flags) {
        configure(format, surface, crypto, null, flags);
    }

如果第二个参数设置了surface,那么在释放的时候releaseOutputBuffer的第二个参数需要设置为true

mediaCodec.releaseOutputBuffer(decodeOutIndex, true);

如果第二个参数设置为null.那么在释放的时候releaseOutputBuffer的第二个参数需要设置为false

mediaCodec.releaseOutputBuffer(decodeOutIndex, false);

因此我们可以设置编码器的初始化

   public H264Player(Context context, String path, Surface surface) {
        this.mContext = context;
        this.mPath = path;
        this.mSurface = surface;
        HandlerThread handlerThread = new HandlerThread("H264Player");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());
        try {
            mediaCodec = MediaCodec.createDecoderByType("video/avc");
            MediaFormat format = MediaFormat.createVideoFormat("video/avc", 720, 1280);
            //设置帧数
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
            mediaCodec.configure(format, surface, null, 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
     mHandler.post(() -> {
            mediaCodec.start();
            decode();
        });
    fun getBytes(path: String?): ByteArray {
        val `is`: InputStream =
            DataInputStream(FileInputStream(File(path)))
        var len: Int
        val size = 1024
        var buf: ByteArray
        val bos = ByteArrayOutputStream()
        buf = ByteArray(size)
        while (`is`.read(buf, 0, size).also { len = it } != -1) bos.write(buf, 0, len)
        buf = bos.toByteArray()
        return buf
    }

2、找到可用的byeBuffer,并将bytebuffer塞数据,塞完数据,需要通知dsp去解码

  int nextFrameStart = findByFrame(bytes, startIndex + 2, totalSize);
            MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
            int decodeInputIndex = mediaCodec.dequeueInputBuffer(TIMEOUT);
            if (decodeInputIndex >= 0) {
                ByteBuffer byteBuffer = mediaCodec.getInputBuffer(decodeInputIndex);
                byteBuffer.clear();
                byteBuffer.put(bytes, startIndex, nextFrameStart - startIndex);
                //通知dsp进行解绑
                mediaCodec.queueInputBuffer(decodeInputIndex, 0, nextFrameStart - startIndex, 0, 0);
                startIndex = nextFrameStart;
            } else {
                continue;
            }
            int decodeOutIndex = mediaCodec.dequeueOutputBuffer(info, TIMEOUT);
            if (decodeOutIndex >= 0) {
                try {
                    Thread.sleep(25);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //如果绑定了surface则设置为true
                mediaCodec.releaseOutputBuffer(decodeOutIndex, true);
            } else {
                Log.e(TAG, "解绑失败");
            }
 mediaCodec = MediaCodec.createDecoderByType("video/hevc");
MediaFormat format = MediaFormat.createVideoFormat("video/hevc", 720, 1280);

输出图片

 mediaCodec.configure(format,  null , null, 0);
      if (decodeOutIndex >= 0) {
                if (isPrintImage) {
                    //dsp的byteBuffer无法直接使用
                    ByteBuffer byteBuffer = mediaCodec.getOutputBuffer(decodeOutIndex);
                    //设置偏移量
                    byteBuffer.position(info.offset);
                    byteBuffer.limit(info.size + info.offset);
                    byte[] ba = new byte[byteBuffer.remaining()];
                    byteBuffer.get(ba);
                    YuvImage yuvImage = new YuvImage(ba, ImageFormat.NV21, 720, 1280, null);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    yuvImage.compressToJpeg(new Rect(0, 0, 720, 1280), 100, baos);
                    byte[] data = baos.toByteArray();
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    if (bitmap != null) {
                        if (printImageStatus == 0) {
                            printImageStatus = 1;
                            try {
                                File myCaptureFile = new File(Environment.getExternalStorageDirectory(), "img.png");
                                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                                bos.flush();
                                bos.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                try {
                    Thread.sleep(25);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //如果绑定了surface则设置为true
                mediaCodec.releaseOutputBuffer(decodeOutIndex, !isPrintImage);
            } else {
                Log.e(TAG, "解绑失败");
            }
上一篇下一篇

猜你喜欢

热点阅读