github.com/bluenviron/mediacommon@v1.9.3/pkg/codecs/h264/emulation_prevention.go (about)

     1  package h264
     2  
     3  // EmulationPreventionRemove removes emulation prevention bytes from a NALU.
     4  // Specification: ITU-T Rec. H.264, 7.4.1 NAL unit semantics
     5  func EmulationPreventionRemove(nalu []byte) []byte {
     6  	// 0x00 0x00 0x03 0x00 -> 0x00 0x00 0x00
     7  	// 0x00 0x00 0x03 0x01 -> 0x00 0x00 0x01
     8  	// 0x00 0x00 0x03 0x02 -> 0x00 0x00 0x02
     9  	// 0x00 0x00 0x03 0x03 -> 0x00 0x00 0x03
    10  
    11  	l := len(nalu)
    12  	n := l
    13  
    14  	for i := 2; i < l; i++ {
    15  		if nalu[i-2] == 0 && nalu[i-1] == 0 && nalu[i] == 3 {
    16  			n--
    17  		}
    18  	}
    19  
    20  	ret := make([]byte, n)
    21  	pos := 0
    22  	start := 0
    23  
    24  	for i := 2; i < l; i++ {
    25  		if nalu[i-2] == 0 && nalu[i-1] == 0 && nalu[i] == 3 {
    26  			pos += copy(ret[pos:], nalu[start:i])
    27  			start = i + 1
    28  		}
    29  	}
    30  
    31  	copy(ret[pos:], nalu[start:])
    32  
    33  	return ret
    34  }