Skip to content

Commit bfe92b9

Browse files
ziminghuaSean-Der
authored andcommitted
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
1 parent 67d2b3e commit bfe92b9

File tree

1 file changed

+24
-31
lines changed

1 file changed

+24
-31
lines changed

codecs/h264_packet.go

+24-31
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package codecs
55

66
import (
7+
"bytes"
78
"encoding/binary"
89
"fmt"
910
)
@@ -34,40 +35,32 @@ const (
3435
outputStapAHeader = 0x78
3536
)
3637

37-
func annexbNALUStartCode() []byte { return []byte{0x00, 0x00, 0x00, 0x01} }
38+
// nolint:gochecknoglobals
39+
var (
40+
naluStartCode = []byte{0x00, 0x00, 0x01}
41+
annexbNALUStartCode = []byte{0x00, 0x00, 0x00, 0x01}
42+
)
3843

3944
func emitNalus(nals []byte, emit func([]byte)) {
40-
nextInd := func(nalu []byte, start int) (indStart int, indLen int) {
41-
zeroCount := 0
42-
43-
for i, b := range nalu[start:] {
44-
if b == 0 {
45-
zeroCount++
46-
continue
47-
} else if b == 1 {
48-
if zeroCount >= 2 {
49-
return start + i - zeroCount, zeroCount + 1
50-
}
51-
}
52-
zeroCount = 0
45+
start := 0
46+
length := len(nals)
47+
48+
for start < length {
49+
end := bytes.Index(nals[start:], annexbNALUStartCode)
50+
offset := 4
51+
if end == -1 {
52+
end = bytes.Index(nals[start:], naluStartCode)
53+
offset = 3
5354
}
54-
return -1, -1
55-
}
56-
57-
nextIndStart, nextIndLen := nextInd(nals, 0)
58-
if nextIndStart == -1 {
59-
emit(nals)
60-
} else {
61-
for nextIndStart != -1 {
62-
prevStart := nextIndStart + nextIndLen
63-
nextIndStart, nextIndLen = nextInd(nals, prevStart)
64-
if nextIndStart != -1 {
65-
emit(nals[prevStart:nextIndStart])
66-
} else {
67-
// Emit until end of stream, no end indicator found
68-
emit(nals[prevStart:])
69-
}
55+
if end == -1 {
56+
emit(nals[start:])
57+
break
7058
}
59+
60+
emit(nals[start : start+end])
61+
62+
// next NAL start position
63+
start += end + offset
7164
}
7265
}
7366

@@ -203,7 +196,7 @@ func (p *H264Packet) doPackaging(nalu []byte) []byte {
203196
return append(naluLength, nalu...)
204197
}
205198

206-
return append(annexbNALUStartCode(), nalu...)
199+
return append(annexbNALUStartCode, nalu...)
207200
}
208201

209202
// IsDetectedFinalPacketInSequence returns true of the packet passed in has the

0 commit comments

Comments
 (0)