欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[Video and Audio Data Processing] H.264视频码流解析

程序员文章站 2022-07-06 10:19:21
...

0. 基本概念

0.1 视频码流在视频播放器中的位置如下所示:

[Video and Audio Data Processing] H.264视频码流解析
H.264原始码流(又称为“裸流”)是由一个一个的NALU组成的。他们的结构如下图所示。

[Video and Audio Data Processing] H.264视频码流解析

0.2 更准确来说,原始的NALU单元组成如下:

[start code] + [NALU header] + [NALU payload]

[start code]占3字节或者4字节,为0x000001或0x00000001。

而其中[NALU header]又由如下所示构成:

forbidden_zero_bit(1bit) + nal_ref_idc(2bit) + nal_unit_type(5bit)

0.3 NALU类型

0.3.1 forbidden_zero_bit:

禁止位,初始化为0,当网络发现 NAL 单元有比特错误时可设置该比特为1,
以便接收方纠错或丢掉该单元。

0.3.2 nal_ref_idc:

nal重要性指示,标志该NAL单元的重要性,值越大,越重要,解码器在解码处理不过来的时候,
可以丢掉重要性为0的NALU。

0.3.3 nal_unit_type:

NALU句法表如下所示:

[Video and Audio Data Processing] H.264视频码流解析

一般H.264码流最开始的两个NALU是SPS和PPS,第三个NALU是IDR。而SPS、PPS、SEI这三种NALU不属于帧的范畴,它们的定义如下:

SPS(Sequence Parameter Sets):序列参数集,作用于一系列连续的编码图像。
PPS(Picture Parameter Set):图像参数集,作用于编码视频序列中一个或多个独立的图像。
SEI(Supplemental enhancement information):附加增强信息,包含了视频画面定时等信息,一般放在主编码图像数据之前,在某些应用中,它可以被省略掉。
IDR(Instantaneous Decoding Refresh):即时解码刷新。
HRD(Hypothetical Reference Decoder):假想码流调度器。

1. 代码

还是学习的雷神的代码,我进一步写了详细注释。

extern "C"
{
#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS

#endif

}
extern "C" {

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
}







typedef enum {
	NALU_TYPE_SLICE = 1,
	NALU_TYPE_DPA = 2,
	NALU_TYPE_DPB = 3,
	NALU_TYPE_DPC = 4,
	NALU_TYPE_IDR = 5,
	NALU_TYPE_SEI = 6,
	NALU_TYPE_SPS = 7,
	NALU_TYPE_PPS = 8,
	NALU_TYPE_AUD = 9,
	NALU_TYPE_EOSEQ = 10,
	NALU_TYPE_EOSTREAM = 11,
	NALU_TYPE_FILL = 12,
} NaluType;

typedef enum {
	NALU_PRIORITY_DISPOSABLE = 0,
	NALU_PRIRITY_LOW = 1,
	NALU_PRIORITY_HIGH = 2,
	NALU_PRIORITY_HIGHEST = 3
} NaluPriority;


typedef struct
{
	int startcodeprefix_len;      
	//! 4 for parameter sets and first slice in picture, 3 for everything else (suggested)
//在H264码流中,都是以"0x00 0x00 0x01"或者"0x00 0x00 0x00 0x01"为开始码的
//startcodeprefix_len可能是三字节也可能是四个字节

	unsigned len;         
	//! Length of the NAL unit (Excluding the start code, which does not belong to the NALU)
	unsigned max_size;            //! Nal Unit Buffer size
	int forbidden_bit;            //! should be always FALSE
//禁止位forbidden_bit,初始为0,当网络发现NAL单元有比特错误时可设置改比特为1,
//以便接收方纠错或者丢掉改单元
	int nal_reference_idc;        //! NALU_PRIORITY_xxxx
//nal_reference_idc,这个是nal重要性指示,标志该NAL单元的重要性,值越大,越重要,
//解码器在解码处理不过来的时候,可以丢掉重要性为0的NALU。
	int nal_unit_type;            //! NALU_TYPE_xxxx    
	char* buf;                    //! contains the first byte followed by the EBSP
} NALU_t;

//h264bitstream这玩意是全局的文件指针
FILE* h264bitstream = NULL;                //!< the bit stream file

int info2 = 0, info3 = 0;


//在H264码流中,都是以"0x00 0x00 0x01"或者"0x00 0x00 0x00 0x01"为开始码的

//前三个字节的数据读出来是0x00 0x00 0x01返回true,否则返回false
static int FindStartCode2(unsigned char* Buf) {
	if (Buf[0] != 0 || Buf[1] != 0 || Buf[2] != 1) return 0; //0x000001?
	else return 1;
}

//前四个字节的数据读出来是0x00 0x00 0x00 0x01返回true,否则返回false
static int FindStartCode3(unsigned char* Buf) {
	if (Buf[0] != 0 || Buf[1] != 0 || Buf[2] != 0 || Buf[3] != 1) return 0;//0x00000001
	else return 1;
}


int GetAnnexbNALU(NALU_t* nalu) {
	int pos = 0;
	int StartCodeFound, rewind;
	unsigned char* Buf;

	//分配100000个字节的空间
	if ((Buf = (unsigned char*)calloc(nalu->max_size, sizeof(char))) == NULL)
		printf("GetAnnexbNALU: Could not allocate Buf memory\n");

	//默认初始化为3
	nalu->startcodeprefix_len = 3;

	//读前三个字节的数据,若无法读到,说明数据异常,直接返回。
	if (3 != fread(Buf, 1, 3, h264bitstream)) {
		free(Buf);
		return 0;
	}
	info2 = FindStartCode2(Buf);
	if (info2 != 1) { // 若读出来的前三个字节不是 0x00 0x00 0x01,则进入判断语句
		if (1 != fread(Buf + 3, 1, 1, h264bitstream)) { //再读一个字节的数据
			free(Buf);
			return 0; //这个还是避免空指针
		}
		info3 = FindStartCode3(Buf);
		//info3为1的条件是,读出前四个字节的数据是0x00 0x00  0x00 0x01
		if (info3 != 1) {
			free(Buf); //两种都不满足,说明数据异常,直接return
			return -1;
		}
		else {
			pos = 4;
			nalu->startcodeprefix_len = 4;//代码能走到这里说明开始码是四个字节的.
		}
	}
	else {
		nalu->startcodeprefix_len = 3;//否则开始码就是三个字节
		pos = 3;
	}
	StartCodeFound = 0;
	info2 = 0;
	info3 = 0;
	while (!StartCodeFound) {
		if (feof(h264bitstream)) {
			nalu->len = (pos - 1) - nalu->startcodeprefix_len;
			memcpy(nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);
			nalu->forbidden_bit = nalu->buf[0] & 0x80; //1 bit
			nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit
			nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;// 5 bit
			free(Buf);
			return pos - 1;
		}

		Buf[pos++] = fgetc(h264bitstream);
		info3 = FindStartCode3(&Buf[pos - 4]);
		if (info3 != 1)
			info2 = FindStartCode2(&Buf[pos - 3]);

		StartCodeFound = (info2 == 1 || info3 == 1);
	}
	// Here, we have found another start code 
	//and read length of startcode bytes more than we should
	// have.  Hence, go back in the file
	rewind = (info3 == 1) ? -4 : -3;

	//开始码是4个字节,后退四个位置,开始码是3个字节,后退三个位置

	if (0 != fseek(h264bitstream, rewind, SEEK_CUR)) {
		//后退文件指针h264bitstream到位置SEEK_CUR+rewind的地方,
		//注意指针向文件头偏移时,没有超出文件头返回0,超出则文件指针不变,返回-1
		free(Buf);
		printf("GetAnnexbNALU: Cannot fseek in the bit stream file");
	}

	// Here the Start code, the complete NALU, and the next start code is in the Buf.  
	// The size of Buf is pos, pos+rewind are the number of bytes excluding the next
	// start code, and (pos+rewind)-startcodeprefix_len is the size of the NALU 
	// excluding the    start code

	nalu->len = (pos + rewind) - nalu->startcodeprefix_len;
	memcpy(nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);
	//取开始码之后的NALU数据拷贝到buff里面

	nalu->forbidden_bit = nalu->buf[0] & 0x80; //1 bit
	nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit
	nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;// 5 bit
	free(Buf);

	return (pos + rewind);
}

/**
 * Analysis H.264 Bitstream
 * @param url    Location of input H.264 bitstream file.
 */
int simplest_h264_parser(const char* url) {

	NALU_t* n;
	int buffersize = 100000;

	//FILE *myout=fopen("output_log.txt","wb+");
	FILE* myout = stdout;

	h264bitstream = fopen(url, "rb+");
	//h264bitstream是一个文件指针,其被初始化为NULL.
	if (h264bitstream == NULL) {
		printf("Open file error\n");
		return 0;
	}

	n = (NALU_t*)calloc(1, sizeof(NALU_t));
	//分配1个长度为sizeof(NALU_t)的连续空间,空间首地址给n
	if (n == NULL) {
		printf("Alloc NALU Error\n");
		return 0;
	}

	//Nal 单元缓冲区大小100000
	n->max_size = buffersize;

	// buf 是100000个byte字节大小的缓冲区.
	n->buf = (char*)calloc(buffersize, sizeof(char));

	// 下面代码避免空指针
	if (n->buf == NULL) {
		free(n);
		printf("AllocNALU: n->buf");
		return 0;
	}

	int data_offset = 0;
	int nal_num = 0;
	printf("-----+-------- NALU Table ------+---------+\n");
	printf(" NUM |    POS  |    IDC |  TYPE |   LEN   |\n");
	printf("-----+---------+--------+-------+---------+\n");

	while (!feof(h264bitstream))
	{
		int data_lenth;
		data_lenth = GetAnnexbNALU(n);

		char type_str[20] = { 0 };
		switch (n->nal_unit_type) {
		case NALU_TYPE_SLICE:sprintf(type_str, "SLICE"); break;
		case NALU_TYPE_DPA:sprintf(type_str, "DPA"); break;
		case NALU_TYPE_DPB:sprintf(type_str, "DPB"); break;
		case NALU_TYPE_DPC:sprintf(type_str, "DPC"); break;
		case NALU_TYPE_IDR:sprintf(type_str, "IDR"); break;
		case NALU_TYPE_SEI:sprintf(type_str, "SEI"); break;
		case NALU_TYPE_SPS:sprintf(type_str, "SPS"); break;
		case NALU_TYPE_PPS:sprintf(type_str, "PPS"); break;
		case NALU_TYPE_AUD:sprintf(type_str, "AUD"); break;
		case NALU_TYPE_EOSEQ:sprintf(type_str, "EOSEQ"); break;
		case NALU_TYPE_EOSTREAM:sprintf(type_str, "EOSTREAM"); break;
		case NALU_TYPE_FILL:sprintf(type_str, "FILL"); break;
		}
		char idc_str[20] = { 0 };
		switch (n->nal_reference_idc >> 5) {
			// 0x60对应0110 0000,这个右移5bit即为nal_reference_idc的值,取值范围是0-3
		case NALU_PRIORITY_DISPOSABLE:sprintf(idc_str, "DISPOS"); break;
		case NALU_PRIRITY_LOW:sprintf(idc_str, "LOW"); break;
		case NALU_PRIORITY_HIGH:sprintf(idc_str, "HIGH"); break;
		case NALU_PRIORITY_HIGHEST:sprintf(idc_str, "HIGHEST"); break;
		}

		fprintf(myout, "%5d| %8d| %7s| %6s| %8d|\n", nal_num, data_offset, idc_str, 
		type_str, 
		n->len);
		//nal_num是数据的长度,data_offset是整个数据的长度,一直再增加,
		//idc_str是nal重要性指示,标志该NAL单元的重要性,值越大,越重要,
		//解码器在解码处理不过来的时候,可以丢掉重要性为0的NALU。
		//type_str表征NALU单元类型
		//n->len由子函数nalu->len确定,这个是每个NALU单元占的空间大小(字节个数),
		//注意这个不包含开始码


		data_offset = data_offset + data_lenth;

		nal_num++;
	}

	//Free
	if (n) {
		if (n->buf) {
			free(n->buf);
			n->buf = NULL;
		}
		free(n);
	}
	return 0;
}




int main()
{
	simplest_h264_parser("sintel.h264");
	return 0;
}

代码可以在visual studio 2019上成功编译。
[Video and Audio Data Processing] H.264视频码流解析

2. 重点解释

while (!StartCodeFound) {
	if (feof(h264bitstream)) {
		nalu->len = (pos - 1) - nalu->startcodeprefix_len;
		memcpy(nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);
		nalu->forbidden_bit = nalu->buf[0] & 0x80; //1 bit
		nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit
		nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;// 5 bit
		free(Buf);
		return pos - 1;
	}

	Buf[pos++] = fgetc(h264bitstream); 
	info3 = FindStartCode3(&Buf[pos - 4]);
	if (info3 != 1)
		info2 = FindStartCode2(&Buf[pos - 3]);

	StartCodeFound = (info2 == 1 || info3 == 1);
}

这段代码是重点,之前一时间没看明白。nalu->forbidden_bit、nalu->nal_reference_idc、nalu->nal_unit_type 这个没啥说的,NALU header相关的信息存在开始码之后的一个字节里面。

if (feof(h264bitstream)) {

这个判断要等到找到文件结束符,前面的普遍情况后面又把ALU header相关的信息,获取的代码写了
一遍。

Buf[pos++] = fgetc(h264bitstream); 
info3 = FindStartCode3(&Buf[pos - 4]);
if (info3 != 1)
	info2 = FindStartCode2(&Buf[pos - 3]);

StartCodeFound = (info2 == 1 || info3 == 1);

这几句是重点,我们当前的开始码是是四个字节的,由前面的分析可知(具体看我写的代码注释),
此时pos在运行到这段代码之前,值为4。

Buf[0]、Buf[1]、Buf[2]、Buf[3]已分别存好开始码四个字节的数据,数据通过h264bitstream文件指针存到Buf里面,此时Buf[pos++] = fgetc(h264bitstream); 再读后面的一个字节数据Buf[4]。

这个字节的数据对应NALU header。

此时pos为运行完,其值为5,那么&Buf[pos-4]开始往后的四个地址的数据必然不是开始码:

0x00 0x00 0x00 0x01,所以必然不满足while (!StartCodeFound) {循环跳出条件。

进一步举例理解

// Here the Start code, the complete NALU, and the next start code is in the Buf.
// The size of Buf is pos, pos+rewind are the number of bytes excluding the next
// start code, and (pos+rewind)-startcodeprefix_len is the size of the NALU excluding the start code

我们假设有个NALU的长度是99个字节,之前四个字节是开始码。pos在进入这个while循环之前
的值是4,Buf[0]、Buf[1]、Buf[2]、Buf[3]已分别存好开始码四个字节的数据

info3 = FindStartCode3(&Buf[pos - 4]);

若要使得这个info3返回1,需要找到第二个NALU前面的开始码,即pos-4为Buf[102]
根据代码Buf[pos++] = fgetc(h264bitstream),此时pos已获取到Buf[102]、Buf[103]
Buf[104]、Buf[105];注意这里Buf[102]是第一个开始码和第一个NALU后面的数据,
这四个字节是下一个开始码的四个字节。

所以说代码注释说,pos是当前的的buf长度,pos+rewind是除了下一个开始码的长度,(具体看代码
,rewind的值为-4,因为开始码是四个字节)

pos+rewind-startcodeprefix_len就是除了开始码的 NALU长度了。

3. 用Binary Viewer瞅瞅

下载安装Binary Viewer。[Video and Audio Data Processing] H.264视频码流解析
把h.264文件拖进去,可以看到前面四个字节是开始码:0x00 0x00 0x00 0x01

[Video and Audio Data Processing] H.264视频码流解析
紧接着0x67的值是0110 0111

nalu->forbidden_bit = nalu->buf[0] & 0x80 这个bit值为0

nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit
n->nal_reference_idc >> 5值为3 ,所以idc_str会打印出HIGHEST

nalu->nal_unit_type = (nalu->buf[0]) & 0x1f; 值为7,7根据之前的
句法表,表明这是序列参数集所以会打印SPS

[Video and Audio Data Processing] H.264视频码流解析

4. 参考链接

感谢阅读,本文参考链接如下:

  1. https://blog.csdn.net/leixiaohua1020/article/details/50534369
  2. https://www.jianshu.com/p/5ec31394649a
  3. https://github.com/leixiaohua1020/simplest_mediadata_test