The original post link is as follows: http://blog.csdn.NET/ren65432/article/details/43449391
Sometimes we need to get h264 naked stream for analysis. This article describes how to obtain a h264 stream by FFmpeg. The H264 code stream files obtained can be played directly through the player such as VLC.
I. H264 file Data flow
The following figure is a. h264 file data analyzed through the Winhex tool:
FFmpeg get H264 ideas as follows:
1, write sync code, 4 bytes (00,00,00,01)
2, write SPS
3, write sync code, 4 bytes (00,00,00,01)
4, write PPS
5, replace the first 4 digits of the read avpacket.data with the (00,00,00,01) write file.
Second, the acquisition of SPS PPS
The SPS and PPS strings of H.264 contain the information parameters needed to initialize the H.264 decoder, including the profile,level used for encoding, the width and height of the image, the Deblock filter, etc.
(1) AVCC Data structure: aligned (8) class AVCDecoderConfigurationRecord { unsigned int (8) configurationVersion = 1; Unsigned int (8) AVCProfileIndication; unsigned int (8) profile_compatibility; unsigned int (8) AVCLevelIndication; bit (6) reserved = ' 111111 ' b; Unsigned int (2) lengthSizeMinusOne; bit (3) reserved = ' b; unsigned int (5) numOfSequenceParameterSets; for (i=0; i< numofsequenceparametersetsispan> unsigned int sequenceParameterSetLength ; Bit (8*sequenceparameTersetlength) sequenceParameterSetNALUnit; } unsigned int (8) numOfPictureParameterSets; for (i=0; i< numOfPictureParameterSetsispan> unsigned int pictureparametersetlength; bit (8*pictureparametersetlength) pictureparametersetnalunit; } } AVCC data structures correspond to SPS and PPS streams.
(2) FFmpeg How to obtain SPS and PPS
FFmpeg obtaining SPS and PPS is very simple. The AVCC data structure corresponds to the avformatcontext->streams[h264index]->codec->extradata.
The code is as follows: if (Ret = avformat_open_input (&ic, InputFileName, NULL, NULL) < 0) { xprintf->trace (0, "******** decode avformat_open_input () function result=%d" , ret); return ret; } if (ret = avformat_find_stream_ Info (ic, null) < 0) { xprintf->trace (0, "******** decode avformat_find_ Stream_info () Function result=%d ", ret); avformat_close_input (&ic); Return ret; } for (int i=0;i<ic->streams[0]->codec->extradata_size;i++) { printf ("%x ",ic->streams[0]-> Codec->extradata[i]); } output printing results are as follows:
Corresponding to the above AVCC structure we know:
7th, 8 bits, the SPS length (0,18) is 24.
The next 24 bits are SPS data, (67,64,0,20,ac,b2,0,a0,b,76,2,20,0,0,3,0,20,0,0,c,81,e3,6,49).
The next 1 means following pps:numofpictureparametersets, 1. The next 2 bits are PPS length: (0,6) is 6.
The next 6 bits are PPS data, (68,EB,C3,CB,22,C0).
Three, the detailed code of the above sections are as follows:
int Geth264stream () {int ret; Avformatcontext *ic=null; Avformatcontext *oc=null; uint8_t sps[100]; uint8_t pps[100]; int spslength=0; int ppslength=0; uint8_t startcode[4]={00,00,00,01};