Skip to content

Commit

Permalink
feat(h264parser): EncodeAVCC
Browse files Browse the repository at this point in the history
  • Loading branch information
RealKeyboardWarrior committed Sep 3, 2023
1 parent 9c8ad0e commit fe07ffe
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 16 additions & 0 deletions codec/h264parser/avcc.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ func DecodeAVCC(b []byte) ([][]byte, error) {
return nil, ErrInvalidAVCC
}

// TODO: AVCC can be 1, 2, 3 or 4 bytes length encoding
// At the moment we just force expect it to be 4
val4 := pio.U32BE(b)
if val4 > uint32(len(b)-4) {
return nil, ErrInvalidAVCC
Expand Down Expand Up @@ -42,3 +44,17 @@ func DecodeAVCC(b []byte) ([][]byte, error) {

return nil, ErrInvalidAVCC
}

func EncodeAVCC(nalus [][]byte) []byte {
b := make([]byte, 0)

for _, nalu := range nalus {
// Always encode AVCC with 4 bytes length
size := make([]byte, 4)
pio.PutU32BE(size, uint32(len(nalu)))
b = append(b, size...)
b = append(b, nalu...)
}

return b
}
15 changes: 13 additions & 2 deletions codec/h264parser/avcc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,20 @@ func TestDecodeAVCC(t *testing.T) {
t.Errorf("expected 2 NAL unit")
}
if nal := hex.EncodeToString(nalus[0]); nal != "aabbccaabbccaabb" {
t.Errorf("Expected %v", nal)
t.Errorf("Unexpected %v", nal)
}
if nal := hex.EncodeToString(nalus[1]); nal != "aa" {
t.Errorf("Expected %v", nal)
t.Errorf("Unexpected %v", nal)
}
}

func TestEncodeAVCC(t *testing.T) {
nalOne, _ := hex.DecodeString("aabbccaabbccaabb")
nalTwo, _ := hex.DecodeString("aa")

avccFrame := EncodeAVCC([][]byte{nalOne, nalTwo})

if avccFrameHex := hex.EncodeToString(avccFrame); avccFrameHex != "00000008aabbccaabbccaabb00000001aa" {
t.Errorf("Unexpected %v", avccFrameHex)
}
}

0 comments on commit fe07ffe

Please sign in to comment.