Skip to content

Commit

Permalink
fix: 🐛 AnnexB Nalu with trailing zeros
Browse files Browse the repository at this point in the history
  • Loading branch information
gemxx committed Dec 23, 2024
1 parent dc22b0b commit 17051a3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
20 changes: 15 additions & 5 deletions packages/xgplayer-transmuxer/__tests__/codec/nalu.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,40 @@ import { NALu } from '../../src/codec'

describe('NALu', () => {

test('parseAnnexB', () => {
test('parseAnnexB with multiple start codes & mixed start codes', () => {
const uint0 = [9, 240]
const uint1 = [103, 100, 0, 31, 172, 217, 64, 212, 61, 176, 17, 0, 0, 3, 0, 1, 0, 0, 3, 0, 120, 15, 24, 49, 150]
const uint2 = [104, 235, 226, 75, 34, 192]
const uint3 = [226, 249, 198, 12, 0, 0, 0, 70, 83, 84, 83, 29, 1, 168, 170, 147, 1, 0, 0, 18] // 00 00 00 + not 1
const uint4 = [226, 9, 240] // trailing zeros
const data = new Uint8Array([
0, 0, 0, 1,
...uint0,
0, 0, 0, 1,
0, 0, 1,
...uint1,
0, 0, 0, 1,
...uint2,
0, 0, 1,
0, 0, 0, 1,
...uint3,
0, 0, 1
0, 0, 1,
...uint4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // trailing zeros
])

const result = NALu.parseAnnexB(data)

expect(result.length).toBe(4)
expect(result.length).toBe(5)
expect(result[0]).toEqual(new Uint8Array(uint0))
expect(result[1]).toEqual(new Uint8Array(uint1))
expect(result[2]).toEqual(new Uint8Array(uint2))
expect(result[3]).toEqual(new Uint8Array(uint3))
expect(result[4]).toEqual(new Uint8Array(uint4))
})

test('parseAnnexB with no NAL units', () => {
const data = new Uint8Array([0, 0, 0, 1])
const result = NALu.parseAnnexB(data)
expect(result.length).toBe(0)
})

test('parseAvcC', () => {
Expand Down
19 changes: 19 additions & 0 deletions packages/xgplayer-transmuxer/src/codec/nalu.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,25 @@ export class NALu {
* @returns {Uint8Array[]}
*/
static parseAnnexB (data) {
let j = data.byteLength - 1
let dropZerosLength = 0
// Collect tailing zeros.
// end with 0x000000 and more...
do {
if (data[j] === 0x00) {
dropZerosLength++
} else {
break
}

j--
} while (j > 0)

if (dropZerosLength >= 3) {
// drop tailing zeros.
data = data.subarray(0, j + 1)
}

const len = data.length
let start = 2
let end = 0
Expand Down

0 comments on commit 17051a3

Please sign in to comment.