音视频学习-annexb与MP4之间的转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35703954/article/details/84597079

 Annexb转MP4

目前感觉上,annexb转MP4的场景似乎不太多,但不排除某些特定场景。所以贴出下面代码。

/*
annexbBuf:输入annexb类型的数据
AvccBuffer:输出MP4或者AVCC的数据
length:输入数据的总长度
*/
int AnnexbToMp4(char *annexbBuf,char *AvccBuffer,int length){
	int FrameLen = 0;
	int index = 0;
	int naluLen = 0;
	while(index < (length-4)){
		if(annexbBuf[index]==0x00&&annexbBuf[index+1]==0x00&&annexbBuf[index+2]==0x01){//3字节
			naluLen = 0;
			index = index+3;
			FrameLen = FrameLen+4;
				while(index < (length-4)){
					if((annexbBuf[index]==0x00&&annexbBuf[index+1]==0x00&&annexbBuf[index+2]==0x01)||
							(annexbBuf[index]==0x00&&annexbBuf[index+1]==0x00&&annexbBuf[index+2]==0x00
									&&annexbBuf[index+3]==0x01)){
						break;

					}else{
						naluLen++;
						//FrameLen++;
						index++;
					}
				}
				memcpy(AvccBuffer+FrameLen,annexbBuf+index-naluLen,naluLen);

				AvccBuffer[FrameLen-1] = (unsigned char)(naluLen&0xFF);
				AvccBuffer[FrameLen-2] = (unsigned char)(naluLen >> 8 & 0xFF);
				AvccBuffer[FrameLen-3] = (unsigned char)(naluLen >> 16 & 0xFF);
				AvccBuffer[FrameLen-4] = (unsigned char)(naluLen >> 24 & 0xFF);
				FrameLen = FrameLen + naluLen;
		}
		else if(annexbBuf[index]==0x00&&annexbBuf[index+1]==0x00&&annexbBuf[index+2]==0x00
				&&annexbBuf[index+3]==0x01){//4字节
			naluLen = 0;
			index = index+4;
			FrameLen = FrameLen+4;
				while(index < (length-4)){
					if((annexbBuf[index]==0x00&&annexbBuf[index+1]==0x00&&annexbBuf[index+2]==0x01)||
							(annexbBuf[index]==0x00&&annexbBuf[index+1]==0x00&&annexbBuf[index+2]==0x00
									&&annexbBuf[index+3]==0x01)){
						break;

					}else{
						naluLen++;
						index++;
						//FrameLen++;
					}
				}
				memcpy(AvccBuffer+FrameLen,annexbBuf+index-naluLen,naluLen);

				AvccBuffer[FrameLen-1] = (unsigned char)(naluLen&0xFF);
				AvccBuffer[FrameLen-2] = (unsigned char)(naluLen >> 8 & 0xFF);
				AvccBuffer[FrameLen-3] = (unsigned char)(naluLen >> 16 & 0xFF);
				AvccBuffer[FrameLen-4] = (unsigned char)(naluLen >> 24 & 0xFF);
				FrameLen = FrameLen + naluLen;
		}
	}
	return FrameLen;
}

MP4转Annexb

MP4转Annexb相对来说就容易一点,因为只需要把前面表示长度的四个字节,转为起始字节00 00 00 01就可以了。但是在Annexb转MP4会遇到的情况就是有可能annexb起始字节为3个,因此需要补齐4个字节来表示长度,所以MP4的长度与annexb数据长度有可能不一样。

#define NAL_GET_5BIT(p) (*(p) & 0x1F)
#define NAL_GET_4BYTE(p) (*p<<24 | *(p+1)<<16 | *(p+2)<<8 |*(p+3))
#define NAL_GET_3BYTE(p) (*(p)<<16 | *(p+1)<<8 |*(p+2))


int Mp4ToAnnexb(u_char *pb, int64_t size)
{
	u_char *p = pb;
	int64_t	left = size;
	while(left > 0){
		int len = NAL_GET_4BYTE(p);
		if(len < 1 || len > left || len > size){
			return -1;
		}
		*p = 0;
		*(p+1) = 0;
		*(p+2) = 0;
		*(p+3) = 1;
		p += (len + 4);
		left -= (len + 4);
	}
	return 0;
}

 

阅读更多

没有更多推荐了,返回首页