参考自:
音频流
1 #include "stdafx.h"
2
3 #define DDug av_log(NULL, AV_LOG_WARNING, "in loop!\n");
4
5 void cal_adts_header(uint8_t *header, int dataLen) {
6 // aac级别,0: AAC Main 1:AAC LC (Low Complexity) 2:AAC SSR (Scalable Sample Rate) 3:AAC LTP (Long Term Prediction)
7 int aac_type = 1;
8 // 采样率下标,下标7表示采样率为22050
9 int sampling_frequency_index = 4;
10 // 声道数
11 int channel_config = 2;
12
13 // ADTS帧长度,包括ADTS长度和AAC声音数据长度的和。
14 int adtsLen = dataLen + 7;
15
16 // syncword,标识一个帧的开始,固定为0xFFF,占12bit(byte0占8位,byte1占前4位)
17 header[0] = 0xff;
18 header[1] = 0xf0;
19
20 // ID,MPEG 标示符。0表示MPEG-4,1表示MPEG-2。占1bit(byte1第5位)
21 header[1] |= (0 << 3);
22
23 // layer,固定为0,占2bit(byte1第6、7位)
24 header[1] |= (0 << 1);
25
26 // protection_absent,标识是否进行误码校验。0表示有CRC校验,1表示没有CRC校验。占1bit(byte1第8位)
27 header[1] |= 1;
28
29 // profile,标识使用哪个级别的AAC。1: AAC Main 2:AAC LC 3:AAC SSR 4:AAC LTP。占2bit(byte2第1、2位)
30 header[2] = aac_type << 6;
31
32 // sampling_frequency_index,采样率的下标。占4bit(byte2第3、4、5、6位)
33 header[2] |= (sampling_frequency_index & 0x0f) << 2;
34
35 // private_bit,私有位,编码时设置为0,解码时忽略。占1bit(byte2第7位)
36 header[2] |= (0 << 1);
37
38 // channel_configuration,声道数。占3bit(byte2第8位和byte3第1、2位)
39 header[2] |= (channel_config & 0x04) >> 2;
40 header[3] = (channel_config & 0x03) << 6;
41
42 // original_copy,编码时设置为0,解码时忽略。占1bit(byte3第3位)
43 header[3] |= (0 << 5);
44
45 // home,编码时设置为0,解码时忽略。占1bit(byte3第4位)
46 header[3] |= (0 << 4);
47
48 // copyrighted_id_bit,编码时设置为0,解码时忽略。占1bit(byte3第5位)
49 header[3] |= (0 << 3);
50
51 // copyrighted_id_start,编码时设置为0,解码时忽略。占1bit(byte3第6位)
52 header[3] |= (0 << 2);
53
54 // aac_frame_length,ADTS帧长度,包括ADTS长度和AAC声音数据长度的和。占13bit(byte3第7、8位,byte4全部,byte5第1-3位)
55 header[3] |= ((adtsLen & 0x1800) >> 11);
56 header[4] = (uint8_t)((adtsLen & 0x7f8) >> 3);
57 header[5] = (uint8_t)((adtsLen & 0x7) << 5);
58
59 // adts_buffer_fullness,固定为0x7FF。表示是码率可变的码流 。占11bit(byte5后5位,byte6前6位)
60 header[5] |= 0x1f;
61 header[6] = 0xfc;
62
63 // number_of_raw_data_blocks_in_frame,值为a的话表示ADST帧中有a+1个原始帧,(一个AAC原始帧包含一段时间内1024个采样及相关数据)。占2bit(byte6第7、8位)。
64 header[6] |= 0;
65
66 }
67
68 char *src = "../mp4/csgo.mp4";
69 char *dst = "../mp4/csgo.aac";
70
71 int main()
72 {
73 int bst_idx = 0;
74
75 av_register_all();
76 av_log_set_level(AV_LOG_INFO);
77
78 AVFormatContext *fmt_ctx = NULL;
79 AVPacket pkt;
80
81 int ret;
82
83 //1.创建输入格式上下文
84 if ((ret = avformat_open_input(&fmt_ctx, src, NULL, NULL)) < 0)
85 {
86 av_log(NULL, AV_LOG_ERROR, "Can`t open file/n");
87 return -1;
88 }
89
90 //输出信息
91 av_dump_format(fmt_ctx, 0, src, 0);
92
93 //2.用系统库(非ffmpeg)建立二进制输出文件
94 FILE* dst_fs = fopen(dst, "wb");
95
96 if (!dst_fs)
97 {
98 av_log(NULL, AV_LOG_ERROR, "Can`t open out file!\n");
99 avformat_close_input(&fmt_ctx);
100 return -1;
101 }
102
103 //3.获取音频流
104
105 //找到一路最佳流并设置下标 音频type
106
107 if ((ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0)) < 0)
108 {
109 av_log(NULL, AV_LOG_ERROR, "Can`t find best stream!\n");
110 avformat_close_input(&fmt_ctx);
111 fclose(dst_fs);
112 return -1;
113 }
114
115 bst_idx = 1;
116
117 std::cout << bst_idx << '\n';
118
119 av_init_packet(&pkt);
120
121 //遍历格式上下文中的frame
122 while (av_read_frame(fmt_ctx, &pkt) >= 0)
123 {
124 //3.如果找到则向输出文件写入二进制字节流
125 //std::cout << pkt.stream_index << '\n';
126 if (pkt.stream_index == bst_idx)
127 {
128 //std::cout << "done!" << '\n';
129 uint8_t adts_header_buf[7] = { 0 };
130 cal_adts_header(adts_header_buf, pkt.size);
131 fwrite(adts_header_buf, 1, 7, dst_fs);
132 fwrite(pkt.data, 1, pkt.size, dst_fs);
133 /*if (len != pkt.size)
134 {
135 av_log(NULL, AV_LOG_WARNING, "Waning, length of date not equal size of pkt\n");
136 }*/
137 }
138 //对于每次使用后的pkt需要释放,防止内存泄露
139 av_packet_unref(&pkt);
140 }
141
142 //关闭输入流
143 avformat_close_input(&fmt_ctx);
144
145 if (dst_fs)
146 {
147 fclose(dst_fs);
148 }
149
150 DDug;
151
152 return 0;
153 }
ADTS头分析
ADTS头包含了AAC文件的采样率、通道数、帧数据长度等信息。ADTS头分为固定头信息和可变头信息两个部分,固定头信息在每个帧中的是一样的,可变头信息在各个帧中并不是固定值。ADTS头一般是7个字节((28+28)/ 8)长度,如果需要对数据进行CRC校验,则会有2个Byte的校验码,所以ADTS头的实际长度是7个字节或9个字节。
固定头信息:adts_fixed_header()
ADTS头的固定头信息在每个帧中都是一样的。

adts_fixed_header
-
syncword:帧同步标识一个帧的开始,固定为0xFFF
-
ID:MPEG 标示符。0表示MPEG-4,1表示MPEG-2
-
layer:固定为'00'
-
protection_absent:标识是否进行误码校验。0表示有CRC校验,1表示没有CRC校验
-
profile:标识使用哪个级别的AAC。1: AAC Main 2:AAC LC (Low Complexity) 3:AAC SSR (Scalable Sample Rate) 4:AAC LTP (Long Term Prediction)
-
sampling_frequency_index:标识使用的采样率的下标
-
private_bit:私有位,编码时设置为0,解码时忽略
-
channel_configuration:标识声道数
-
original_copy:编码时设置为0,解码时忽略
-
home:编码时设置为0,解码时忽略

sampling_frequency_index

channel_configuration
可变头信息:adts_variable_header()

adts_variable_header.png
-
copyrighted_id_bit:编码时设置为0,解码时忽略
-
copyrighted_id_start:编码时设置为0,解码时忽略
-
aac_frame_length:ADTS帧长度包括ADTS长度和AAC声音数据长度的和。即 aac_frame_length = (protection_absent == 0 ? 9 : 7) + audio_data_length
-
adts_buffer_fullness:固定为0x7FF。表示是码率可变的码流
-
number_of_raw_data_blocks_in_frame:表示当前帧有number_of_raw_data_blocks_in_frame + 1 个原始帧(一个AAC原始帧包含一段时间内1024个采样及相关数据)。
视频
从mp4文件中抽取h264数据步骤如下: 1.打开mp4文件并创建一个空文件用于存储H264数据 2.提取一路视频流资源 3.循环读取流中所有的包(AVPacket),为每个包添加特征码和sps/pps等数据(只有关键帧前面要添加sps/pps数据,其他的只需要添加特征码),都处理完后将数据写入文件保存。
ffmpeg读取mp4中的h264数据,pps及sps并不能从packet中获得,而是保存在AVCodecContext的extradata数据域中,如下所示是一个mp4文件的extradata的前面一部分数据:
01 64 00 16 ff e1 00 18 67 64 00 16 ac d9 80 98 2f a1 00 00 03 00 01 00 00 03 00 2c 0f 16 2d 9a 01 00 06 68 e9 79 4b 22 c0 fd f8 f8 00 01 64 00 16 ff e1 00 18 67 64 00 16 ac d9 80 98 2f a1 00 00 03 00 01 00 00 03 00 2c 0f 16 2d 9a 01 00 06 68 e9 79 4b 22 c0 fd f8 f8 00 01 64 00 16 ff e1 00 18 67 64 00 16 ac d9 80 98 2f a1 00 00 03 00 01 00 00 03 00 2c 0f 16 2d 9a 01
前面4个字节跳过,第5个字节ff的后2位用于指示表示编码数据长度所需字节数。第6个字节e1后5位(结果是1)是表示接下来的sps或pps的个数为1。 第7、8两个字节00 18表示接下来的sps或pps数据的长度,结果是接下来sps或pps长度是24个字节。 第9个字节是67表示这个是sps数据,也就是说从67到9a这24个字节是sps数据。因为sps只有一个,所以接下来是pps数据。 紧接着的那个字节01表示pps的个数是1个,然后紧接着的2个字节00 06表示pps数据长度是6,接下来的字节是68,表明这确实是pps数据,包括68在内的6个字节是pps的内容。 提取到的每个sps/pps数据在写入h264文件时都要在其前面加上4个字节的特征码(0x00000001)。

sps和pps都有的情况

只有pps的情况

sps、pps、关键帧、非关键帧写入h264文件的顺序
代码:
1 #include "stdafx.h"
2
3 char errinfo[1024] = { 0 };
4
5 #define DDug av_log(NULL, AV_LOG_WARNING, "Debug Now!\n");
6
7 char *src = "../mp4/csgo.mp4";
8 char *dst = "../mp4/video_stream.mp4";
9
10 /*
11 在帧前面添加特征码(一般SPS/PPS的帧的特征码用4字节表示,为0X00000001,其他的帧特征码用3个字节表示,为0X000001。也有都用4字节表示的,我们这里采用前面的方式)
12 out是要输出的AVPaket
13 sps_pps是SPS和PPS数据的指针,对于非关键帧就传NULL
14 sps_pps_size是SPS/PPS数据的大小,对于非关键帧传0
15 in是指向当前要处理的帧的头信息的指针
16 in_size是当前要处理的帧大小(nal_size)
17 */
18
19 static int alloc_and_copy(AVPacket *out, const uint8_t *sps_pps, uint32_t sps_pps_size, const uint8_t *in, uint32_t in_size)
20 {
21 uint32_t offset = out->size; // 偏移量,就是out已有数据的大小,后面再写入数据就要从偏移量处开始操作
22 // 特征码的大小,SPS/PPS占4字节,其余占3字节
23 uint8_t nal_header_size = sps_pps == NULL ? 3 : 4;
24 int err;
25
26 // 每次处理前都要对out进行扩容,扩容的大小就是此次要写入的内容的大小,也就是特征码大小加上sps/pps大小加上加上本帧数据大小
27 if ((err = av_grow_packet(out, sps_pps_size + in_size + nal_header_size)) < 0)
28 return err;
29
30 // 1.如果有sps_pps则先将sps_pps拷贝进out(memcpy()函数用于内存拷贝,第一个参数为拷贝要存储的地方,第二个参数是要拷贝的内容,第三个参数是拷贝内容的大小)
31 if (sps_pps)
32 {
33 memcpy(out->data + offset, sps_pps, sps_pps_size);
34 }
35
36 // 2.再设置特征码(sps/pps特征码4位0x00000001,其他的特征码3位0x000001)
37 for (int i = 0; i < nal_header_size; i++)
38 {
39 (out->data + offset + sps_pps_size)[i] = i == nal_header_size - 1 ? 1 : 0;
40 }
41
42 // 3.最后再拷贝NALU数据(当前处理的帧数据)
43 memcpy(out->data + sps_pps_size + nal_header_size + offset, in, in_size);
44
45 return 0;
46 }
47
48 /*
49 读取并拷贝sps/pps数据
50 codec_extradata是codecpar的扩展数据,sps/pps数据就在这个扩展数据里面
51 codec_extradata_size是扩展数据大小
52 out_extradata是输出sps/pps数据的AVPacket包
53 padding:就是宏AV_INPUT_BUFFER_PADDING_SIZE的值(64),是用于解码的输入流的末尾必要的额外字节个数,需要它主要是因为一些优化的流读取器一次读取32或者64比特,可能会读取超过size大小内存的末尾。
54 */
55 int h264_extradata_to_annexb(const uint8_t *codec_extradata, const int codec_extradata_size, AVPacket *out_extradata, int padding)
56 {
57 uint16_t unit_size; // sps/pps数据长度
58 uint64_t total_size = 0; // 所有sps/pps数据长度加上其特征码长度后的总长度
59
60 for (int i = 0; i < codec_extradata_size; ++i)
61 {
62 printf("%02x ", *(codec_extradata + i));
63 }
64
65 /*
66 out:是一个指向一段内存的指针,这段内存用于存放所有拷贝的sps/pps数据和其特征码数据
67 unit_nb:sps/pps个数
68 sps_done:sps数据是否已经处理完毕
69 sps_seen:是否有sps数据
70 pps_seen:是否有pps数据
71 sps_offset:sps数据的偏移,为0
72 pps_offset:pps数据的偏移,因为pps数据在sps后面,所以其偏移就是所有sps数据长度+sps的特征码所占字节数
73 */
74 uint8_t *out = NULL, unit_nb, sps_done = 0,
75 sps_seen = 0, pps_seen = 0, sps_offset = 0, pps_offset = 0;
76 const uint8_t *extradata = codec_extradata + 4; // 扩展数据的前4位是无用的数据,直接跳过拿到真正的扩展数据
77 static const uint8_t nalu_header[4] = { 0, 0, 0, 1 }; // sps/pps数据前面的4bit的特征码
78
79 // extradata第一个字节的最后2位用于指示后面每个sps/pps数据所占字节数。(*extradata表示extradata第一个字节的数据,之后自增1指向下一个字节)
80 int length_size = (*extradata++ & 0x3) + 1;
81
82 sps_offset = pps_offset = -1;
83
84 // extradata第二个字节最后5位用于指示sps的个数,一般情况下一个扩展只有一个sps和pps,之后指针指向下一位
85 unit_nb = *extradata++ & 0x1f;
86 if (!unit_nb) { // unit_nb为0表示没有sps数据,直接跳转到处理pps的地方
87 goto pps;
88 }
89 else { // unit_nb不为0表有sps数据,所以sps_seen赋值1,sps_offset赋值0
90 sps_offset = 0;
91 sps_seen = 1;
92 }
93
94 while (unit_nb--) { // 遍历每个sps或pps(先变量sps,然后再遍历pps)
95 int err;
96
97 // 再接着2个字节表示sps/pps数据的长度
98 unit_size = (extradata[0] << 8) | extradata[1];
99 total_size += unit_size + 4; // 4表示sps/pps特征码长度
100 if (total_size > INT_MAX - padding) { // total_size太大会造成数据溢出,所以要做判断
101 av_log(NULL, AV_LOG_ERROR,
102 "Too big extradata size, corrupted stream or invalid MP4/AVCC bitstream\n");
103 av_free(out);
104 return AVERROR(EINVAL);
105 }
106
107 // extradata + 2 + unit_size比整个扩展数据都长了表明数据是异常的
108 if (extradata + 2 + unit_size > codec_extradata + codec_extradata_size) {
109 av_log(NULL, AV_LOG_ERROR, "Packet header is not contained in global extradata, "
110 "corrupted stream or invalid MP4/AVCC bitstream\n");
111 av_free(out);
112 return AVERROR(EINVAL);
113 }
114
115 // av_reallocp()函数用于内存扩展,给out扩展总长加padding的长度
116 if ((err = av_reallocp(&out, total_size + padding)) < 0)
117 return err;
118
119 // 先将4字节的特征码拷贝进out
120 memcpy(out + total_size - unit_size - 4, nalu_header, 4);
121 // 再将sps/pps数据拷贝进out,extradata + 2是因为那2字节是表示sps/pps长度的,所以要跳过
122 memcpy(out + total_size - unit_size, extradata + 2, unit_size);
123 // 本次sps/pps数据处理完后,指针extradata跳过本次sps/pps数据
124 extradata += 2 + unit_size;
125 pps:
126 if (!unit_nb && !sps_done++) { // 执行到这里表明sps已经处理完了,接下来处理pps数据
127 // pps的个数
128 unit_nb = *extradata++;
129 if (unit_nb) { // 如果pps个数大于0这给pps_seen赋值1表明数据中有pps
130 pps_offset = total_size;
131 pps_seen = 1;
132 }
133 }
134 }
135
136 if (out) // 如果out有数据,那么将out + total_size后面padding(即64)个字节用0替代
137 memset(out + total_size, 0, padding);
138
139 // 如果数据中没有sps或pps则给出提示
140 if (!sps_seen)
141 av_log(NULL, AV_LOG_WARNING,
142 "Warning: SPS NALU missing or invalid. "
143 "The resulting stream may not play.\n");
144
145 if (!pps_seen)
146 av_log(NULL, AV_LOG_WARNING,
147 "Warning: PPS NALU missing or invalid. "
148 "The resulting stream may not play.\n");
149
150 // 给传进来的sps/pps的AVPaket赋值
151 out_extradata->data = out;
152 out_extradata->size = total_size;
153
154 return length_size;
155 }
156
157 /*
158 为包数据添加起始码、SPS/PPS等信息后写入文件。
159 AVPacket数据包可能包含一帧或几帧数据,对于视频来说只有1帧,对音频来说就包含几帧
160 in为要处理的数据包
161 file为输出文件的指针
162 */
163 int h264_mp4toannexb(AVFormatContext *fmt_ctx, AVPacket *in, FILE *file)
164 {
165 AVPacket *out = NULL; // 输出的包
166 AVPacket spspps_pkt; // sps/pps数据的AVPaket
167
168 int len; // fwrite()函数写入文件时的返回值
169 uint8_t unit_type; // NALU头中nal_unit_type,也就是NALU类型,5表示是I帧,7表示SPS,8表示PPS
170 int32_t nal_size; // 一个NALU(也就是一帧,其第一个字节是头信息)的大小,它存放在NALU的前面的4个字节中
171 uint8_t nal_size_len = 4; // 存放nal_size的字节数
172 uint32_t cumul_size = 0; // 已经处理的字节数,当cumul_size==buf_size时表示整个包的数据都处理完了
173 const uint8_t *buf; // 传进来的数据指针
174 const uint8_t *buf_end; // 传进来的数据末尾指针
175 int buf_size; // 传进来的数据大小
176 int ret = 0, i;
177
178 out = av_packet_alloc();
179
180 buf = in->data;
181 buf_size = in->size;
182 buf_end = in->data + in->size; // 数据首地址加上数据大小就是数据尾地址
183
184 do {
185 ret = AVERROR(EINVAL);
186 if (buf + nal_size_len > buf_end) // 说明传进来的数据没有内容,是有问题的
187 {
188 goto fail;
189 }
190
191 // 取出NALU前面的4个字节得到这一帧的数据大小
192 for (nal_size = 0, i = 0; i<nal_size_len; i++)
193 {
194 nal_size = (nal_size << 8) | buf[i];
195 }
196
197 buf += nal_size_len; // buf后移4位指向NALU的头信息(1个字节)
198 unit_type = *buf & 0x1f; // 取出NALU头信息的后面5个bit,这5bit记录NALU的类型
199
200 // 数据有问题就退出
201 if (nal_size > buf_end - buf || nal_size < 0)
202 {
203 goto fail;
204 }
205
206 // unit_type是5表示是关键帧,对于关键帧要在其前面添加SPS和PPS信息
207 if (unit_type == 5) {
208
209 // 添加SPS和PPS信息,找FFmpeg中SPS和PPS信息存放在codecpar->extradata中
210 h264_extradata_to_annexb(fmt_ctx->streams[in->stream_index]->codecpar->extradata,
211 fmt_ctx->streams[in->stream_index]->codecpar->extradata_size,
212 &spspps_pkt,
213 AV_INPUT_BUFFER_PADDING_SIZE);
214
215 // 为数据添加特征码(起始码,用于分隔一帧一帧的数据)
216 if ((ret = alloc_and_copy(out,
217 spspps_pkt.data, spspps_pkt.size,
218 buf, nal_size)) < 0)
219 goto fail;
220 }
221 else {
222 // 非关键帧只需要添加特征码
223 if ((ret = alloc_and_copy(out, NULL, 0, buf, nal_size)) < 0)
224 goto fail;
225 }
226
227
228 buf += nal_size; // 一帧处理完后将指针移到下一帧
229 cumul_size += nal_size + nal_size_len;// 累计已经处理好的数据长度
230 } while (cumul_size < buf_size);
231
232 // SPS、PPS和特征码都添加后将其写入文件
233 len = fwrite(out->data, 1, out->size, file);
234 if (len != out->size) {
235 av_log(NULL, AV_LOG_DEBUG, "warning, length of writed data isn't equal pkt.size(%d, %d)\n", len, out->size);
236 }
237 // fwrite()只是将数据写入缓存,fflush()才将数据正在写入文件
238 fflush(file);
239
240 fail:
241 av_packet_free(&out); // 凡是中途处理失败退出之前都要将促使的out释放,否则会出现内存泄露
242
243 return ret;
244
245 }
246
247 int main()
248 {
249 int err_code = 0;
250 int vdo_stm_idx = 0;
251
252 av_register_all();
253 av_log_set_level(AV_LOG_INFO);
254
255 AVFormatContext *fmt_ctx = NULL;
256 AVPacket pkt;
257
258 if (!src || !dst)
259 {
260 av_log(NULL, AV_LOG_ERROR, "file is null!\n");
261 return -1;
262 }
263
264 //打开输入文件格式上下文
265 if (err_code = avformat_open_input(&fmt_ctx, src, NULL, NULL) < 0)
266 {
267 av_strerror(err_code, errinfo, 1024);
268 av_log(NULL, AV_LOG_ERROR, "Can`t open file! ( %s )\n", errinfo);
269 return -1;
270 }
271
272 //判断非空
273 if (err_code = avformat_find_stream_info(fmt_ctx, NULL) < 0)
274 {
275 av_strerror(err_code, errinfo, 1024);
276 av_log(NULL, AV_LOG_ERROR, "Can`t open file! ( %s )\n", errinfo);
277 return -1;
278 }
279
280 FILE *out = fopen(dst, "wb");
281
282 av_dump_format(fmt_ctx, 0, src, 0);
283
284 av_init_packet(&pkt);
285
286 //找最佳视频流下标
287 if (vdo_stm_idx = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0) < 0)
288 {
289 av_log(NULL, AV_LOG_ERROR, "Can`t find best stream!\n");
290 return -1;
291 }
292
293 while (av_read_frame(fmt_ctx, &pkt) >= 0)
294 {
295 if (pkt.stream_index == vdo_stm_idx)
296 {
297 h264_mp4toannexb(fmt_ctx, &pkt, out);
298 }
299 av_packet_unref(&pkt);
300 }
301
302 return 0;
303 }

来源:https://www.cnblogs.com/zeolim/p/12344979.html