From 17051a36757371f155ea4c6a1b3e171066ccad60 Mon Sep 17 00:00:00 2001 From: gemstone Date: Sat, 21 Dec 2024 12:37:05 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20AnnexB=20Nalu=20with=20tr?= =?UTF-8?q?ailing=20zeros?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../__tests__/codec/nalu.spec.js | 20 ++++++++++++++----- .../xgplayer-transmuxer/src/codec/nalu.js | 19 ++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/xgplayer-transmuxer/__tests__/codec/nalu.spec.js b/packages/xgplayer-transmuxer/__tests__/codec/nalu.spec.js index cf21fcaf0..71def18f2 100644 --- a/packages/xgplayer-transmuxer/__tests__/codec/nalu.spec.js +++ b/packages/xgplayer-transmuxer/__tests__/codec/nalu.spec.js @@ -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', () => { diff --git a/packages/xgplayer-transmuxer/src/codec/nalu.js b/packages/xgplayer-transmuxer/src/codec/nalu.js index ba054e334..15d39be81 100644 --- a/packages/xgplayer-transmuxer/src/codec/nalu.js +++ b/packages/xgplayer-transmuxer/src/codec/nalu.js @@ -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