參考自:
音頻流
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 }

