解释此编码器如何处理PPS和SPS?

时间:2018-09-08 15:09:31

标签: video h.264 video-processing video-encoding

我在网上找到了此代码,有人可以解释一下PPS和SPS部分吗?

所有if (sps != null && pps != null)之后的内容我都知道,因为我们检查if (spsPpsBuffer.getInt() == 0x00000001)是因为NALU以 0x00000001 开头,但是在那之后我真的不明白以下内容:< / p>

  • 为什么先将ppsIndex设置为0,然后再将其设置为spsPpsBuffer.position()

  • 为什么SPS缓冲区的大小为ppsIndex - 8

  • 为什么PPS缓冲区的大小为outData.length - ppsIndex

这是代码:

@Override
public void offerEncoder(byte[] input) {
    try {
        ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
        ByteBuffer[] outputBuffers = mediaCodec.getOutputBuffers();
        int inputBufferIndex = mediaCodec.dequeueInputBuffer(-1);
        if (inputBufferIndex >= 0) {
            ByteBuffer inputBuffer = inputBuffers[inputBufferIndex];
            inputBuffer.clear();
            inputBuffer.put(input);
            mediaCodec.queueInputBuffer(inputBufferIndex, 0, input.length, 0, 0);
        }
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
        int outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
        while (outputBufferIndex >= 0) {
            ByteBuffer outputBuffer = outputBuffers[outputBufferIndex];
            byte[] outData = new byte[bufferInfo.size];
            outputBuffer.get(outData);
            if (sps != null && pps != null) {
                ByteBuffer frameBuffer = ByteBuffer.wrap(outData);
                frameBuffer.putInt(bufferInfo.size - 4);
                frameListener.frameReceived(outData, 0, outData.length);
            } else {
                ByteBuffer spsPpsBuffer = ByteBuffer.wrap(outData);
                if (spsPpsBuffer.getInt() == 0x00000001) {
                    System.out.println("parsing sps/pps");
                } else {
                    System.out.println("something is amiss?");
                }
                int ppsIndex = 0;
                while(!(spsPpsBuffer.get() == 0x00 && spsPpsBuffer.get() == 0x00 && spsPpsBuffer.get() == 0x00 && spsPpsBuffer.get() == 0x01)) {
                }
                ppsIndex = spsPpsBuffer.position();
                sps = new byte[ppsIndex - 8];
                System.arraycopy(outData, 4, sps, 0, sps.length);
                pps = new byte[outData.length - ppsIndex];
                System.arraycopy(outData, ppsIndex, pps, 0, pps.length);
                if (null != parameterSetsListener) {
                    parameterSetsListener.avcParametersSetsEstablished(sps, pps);
                }
            }
            mediaCodec.releaseOutputBuffer(outputBufferIndex, false);
            outputBufferIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 0);
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

非常感谢您。

1 个答案:

答案 0 :(得分:2)

您可以从较早的答案中获得有关PPS / SPS的一般概念: H264 with multiple PPS and SPS

以上代码是高度专业的,仅适用于一小部分H.264流。该代码假定固定长度的SPS(8个字节),并进行了更多无效的假设。 除非代码是针对一种特定的编码器的,否则我可能不会使用。

这似乎是不错的H.264解析器:https://github.com/aizvorski/h264bitstream