From bfe92b95ae6f7195e58eb777dc1d860e511216fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A8=BE=E6=98=8E=E5=8D=8E?= <565209960@qq.com> Date: Wed, 20 Sep 2023 21:30:29 +0800 Subject: [PATCH] Optimize the performance of H264 packaging NALU parsing was generating slices as it went. This updates emitNalus to instead use bytes.Index which is more performant --- codecs/h264_packet.go | 55 +++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/codecs/h264_packet.go b/codecs/h264_packet.go index 17ca1bb8..e53cea09 100644 --- a/codecs/h264_packet.go +++ b/codecs/h264_packet.go @@ -4,6 +4,7 @@ package codecs import ( + "bytes" "encoding/binary" "fmt" ) @@ -34,40 +35,32 @@ const ( outputStapAHeader = 0x78 ) -func annexbNALUStartCode() []byte { return []byte{0x00, 0x00, 0x00, 0x01} } +// nolint:gochecknoglobals +var ( + naluStartCode = []byte{0x00, 0x00, 0x01} + annexbNALUStartCode = []byte{0x00, 0x00, 0x00, 0x01} +) func emitNalus(nals []byte, emit func([]byte)) { - nextInd := func(nalu []byte, start int) (indStart int, indLen int) { - zeroCount := 0 - - for i, b := range nalu[start:] { - if b == 0 { - zeroCount++ - continue - } else if b == 1 { - if zeroCount >= 2 { - return start + i - zeroCount, zeroCount + 1 - } - } - zeroCount = 0 + start := 0 + length := len(nals) + + for start < length { + end := bytes.Index(nals[start:], annexbNALUStartCode) + offset := 4 + if end == -1 { + end = bytes.Index(nals[start:], naluStartCode) + offset = 3 } - return -1, -1 - } - - nextIndStart, nextIndLen := nextInd(nals, 0) - if nextIndStart == -1 { - emit(nals) - } else { - for nextIndStart != -1 { - prevStart := nextIndStart + nextIndLen - nextIndStart, nextIndLen = nextInd(nals, prevStart) - if nextIndStart != -1 { - emit(nals[prevStart:nextIndStart]) - } else { - // Emit until end of stream, no end indicator found - emit(nals[prevStart:]) - } + if end == -1 { + emit(nals[start:]) + break } + + emit(nals[start : start+end]) + + // next NAL start position + start += end + offset } } @@ -203,7 +196,7 @@ func (p *H264Packet) doPackaging(nalu []byte) []byte { return append(naluLength, nalu...) } - return append(annexbNALUStartCode(), nalu...) + return append(annexbNALUStartCode, nalu...) } // IsDetectedFinalPacketInSequence returns true of the packet passed in has the