編碼過程可以看做解碼的逆過程粱锐,語法、思路基本一致扛邑。
1.導(dǎo)入頭文件,比解碼多用到個image工具類怜浅。
#import <libavformat/avformat.h>
#import <libswscale/swscale.h>
#import <libswresample/swresample.h>
#import <libavutil/pixdesc.h>
#import <libavutil/imgutils.h>
2.注冊協(xié)議、格式鹿榜、編解碼器海雪。
av_register_all();
3.初始化上下文锦爵,獲取輸出文件格式。
AVFormatContext *avformat_context = avformat_alloc_context();
const char *coutFilePath = [outFilePath UTF8String];
AVOutputFormat *avoutput_format = av_guess_format(NULL,coutFilePath,NULL);
avformat_context->oformat = avoutput_format;
4.打開輸出文件奥裸。
if (avio_open(&avformat_context->pb,coutFilePath,AVIO_FLAG_WRITE) < 0) {
NSLog(@"打開輸出文件失敗");
return;
}
5.獲取編碼器上下文并設(shè)置音視頻編碼器险掀。
視頻編碼器:
AVStream *av_video_stream = avformat_new_stream(avformat_context,NULL);
AVCodecContext *avcodec_context = avcodec_alloc_context3(NULL);
if (avcodec_context == NULL) {
NSLog(@"Could not allocate AVCodecContext\n");
return;
}
int avcodec_parameters_to_context_result = avcodec_parameters_to_context(avcodec_context, av_video_stream->codecpar);
if (avcodec_parameters_to_context_result != 0) {
// 0 成功
NSLog(@"獲取解碼器上下文失敗");
return;
}
avcodec_context->codec_id = avoutput_format->video_codec;
avcodec_context->codec_type = AVMEDIA_TYPE_VIDEO;
avcodec_context->pix_fmt = AV_PIX_FMT_YUV420P;
avcodec_context->width = 640;
avcodec_context->height = 352;
//每1秒25幀
avcodec_context->time_base.num = 1;
avcodec_context->time_base.den = 25;
//碼率->單位時間傳送的數(shù)據(jù)位數(shù)
avcodec_context->bit_rate = 468000;
avcodec_context->gop_size = 250;
//量化系數(shù)越小,視頻越是清晰
//一般情況下都是默認(rèn)值湾宙,最小量化系數(shù)默認(rèn)值是10樟氢,最大量化系數(shù)默認(rèn)值是51
avcodec_context->qmin = 10;
avcodec_context->qmax = 51;
//設(shè)置b幀最大值->設(shè)置不需要B幀
avcodec_context->max_b_frames = 0;
// 查找編碼器h264 (默認(rèn)情況下FFmpeg沒有編譯進(jìn)行h264庫 需下載x264編譯)
AVCodec *avcodec = avcodec_find_encoder(avcodec_context->codec_id);
if (avcodec == NULL) {
NSLog(@"找不到編碼器");
return;
}
音頻編碼器:
AVStream *av_video_stream = avformat_new_stream(avformat_context,NULL);
AVCodecContext *avcodec_context = avcodec_alloc_context3(NULL);;
avcodec_parameters_to_context(avcodec_context, av_video_stream->codecpar);
//設(shè)置編解碼器上下文->目標(biāo):設(shè)置為是一個音頻編碼器上下文->指定的是音頻編碼器
avcodec_context->codec_id = avcodec_alloc_context3(NULL);
//設(shè)置編碼器類型->音頻編碼器
//視頻編碼器->AVMEDIA_TYPE_VIDEO
//音頻編碼器->AVMEDIA_TYPE_AUDIO
avcodec_context->codec_type = AVMEDIA_TYPE_AUDIO;
// 設(shè)置讀取音頻采樣數(shù)據(jù)格式->編碼的是音頻采樣數(shù)據(jù)格式->音頻采樣數(shù)據(jù)格式->pcm格式
//注意:這個類型是根據(jù)你解碼的時候指定的解碼的音頻采樣數(shù)據(jù)格式類型
avcodec_context->sample_fmt = AV_SAMPLE_FMT_S16;
//設(shè)置采樣率
avcodec_context->sample_rate = 44100;
//立體聲
avcodec_context->channel_layout = AV_CH_LAYOUT_STEREO;
//聲道數(shù)量
int channels = av_get_channel_layout_nb_channels(avcodec_context->channel_layout);
avcodec_context->channels = channels;
//設(shè)置碼率 基本的算法是:【碼率】(kbps)=【視頻大小 - 音頻大小】(bit位) /【時間】(秒)
avcodec_context->bit_rate = 128000;
6.打開編碼器。
視頻編碼器:
AVDictionary *param = 0;
if (avcodec_context->codec_id == AV_CODEC_ID_H264) {
//需要查看x264源碼->x264.c文件
//第一個值:預(yù)備參數(shù)
//key: preset
//value: slow->慢
//value: superfast->超快
av_dict_set(¶m, "preset", "slow", 0);
//第二個值:調(diào)優(yōu)
//key: tune->調(diào)優(yōu)
//value: zerolatency->零延遲
av_dict_set(¶m, "tune", "zerolatency", 0);
}
if (avcodec_open2(avcodec_context, avcodec, ¶m) < 0) {
NSLog(@"打開編碼器失敗");
return;
}
音頻編碼器:
//查找音頻編碼器->aac libfdk_aac ffmpeg ./configre help 查看
AVCodec *avcodec = avcodec_find_encoder_by_name("libfdk_aac");
if (avcodec == NULL) {
NSLog(@"找不到音頻編碼器");
return;
}
if (avcodec_open2(avcodec_context,avcodec,NULL)<0) {
NSLog(@"打開音頻編碼器失敗");
return;
}
7.寫入文件頭信息侠鳄。
int avformat_write_header_result = avformat_write_header(avformat_context, NULL);
if (avformat_write_header_result != 0) {
NSLog(@"寫入頭部信息失敗");
return;
}
8.設(shè)置緩沖區(qū)埠啃。
視頻緩沖區(qū):
// 獲取緩沖區(qū)大小
int buffer_size = av_image_get_buffer_size(avcodec_context->pix_fmt,
avcodec_context->width,
avcodec_context->height,
1);
//創(chuàng)建一個緩沖區(qū)
int y_size = avcodec_context->width * avcodec_context->height;
uint8_t *out_buffer = (uint8_t *) av_malloc(buffer_size);
//打開輸入文件
const char *cinFilePath = [inFilePath cStringUsingEncoding:NSUTF8StringEncoding];
FILE *in_file = fopen(cinFilePath, "rb");
if (in_file == NULL) {
NSLog(@"文件不存在");
return;
}
//開辟一塊內(nèi)存空間->av_frame_alloc
AVFrame *av_frame = av_frame_alloc();
//設(shè)置緩沖區(qū)和AVFrame類型保持一致->填充數(shù)據(jù) linesize:yuv/rgb這些值
av_image_fill_arrays(av_frame->data,
av_frame->linesize,
out_buffer,
avcodec_context->pix_fmt,
avcodec_context->width,
avcodec_context->height,
1);
音頻緩沖區(qū):
AVFrame *av_frame = av_frame_alloc();
av_frame->nb_samples = avcodec_context->frame_size;
av_frame->format = avcodec_context->sample_fmt;
//得到音頻采樣數(shù)據(jù)緩沖區(qū)大小
int buffer_size = av_samples_get_buffer_size(NULL,
avcodec_context->channels,
avcodec_context->frame_size,
avcodec_context->sample_fmt,
1);
//創(chuàng)建緩沖區(qū)
uint8_t *out_buffer = (uint8_t *) av_malloc(buffer_size);
avcodec_fill_audio_frame(av_frame,
avcodec_context->channels,
avcodec_context->sample_fmt,
(const uint8_t *)out_buffer,
buffer_size,
1);
9.開始編碼。
視頻編碼:
AVPacket *av_packet = (AVPacket *) av_malloc(buffer_size);
int i = 0;
int result = 0;
int current_frame_index = 1;
while (true) {
//從yuv文件里面讀取緩沖區(qū) 讀取大形岸瘛:y_size * 3 / 2
if (fread(out_buffer, 1, y_size * 3 / 2, in_file) <= 0) {
NSLog(@"讀取完畢...");
break;
} else if (feof(in_file)) {
break;
}
// 將緩沖區(qū)數(shù)據(jù)->轉(zhuǎn)成AVFrame類型
//給AVFrame填充數(shù)據(jù) void * restrict->->轉(zhuǎn)成->AVFrame->ffmpeg數(shù)據(jù)類型
//Y值 4
av_frame->data[0] = out_buffer;
//U值
av_frame->data[1] = out_buffer + y_size;
//V值 1
av_frame->data[2] = out_buffer + y_size * 5 / 4;
av_frame->pts = i;
//注意時間戳
i++;
//總結(jié):這樣一來我們的AVFrame就有數(shù)據(jù)了
//發(fā)送一幀視頻像素數(shù)據(jù)
int send_result = avcodec_send_frame(avcodec_context, av_frame);
int receive_result = 0;
if (send_result == AVERROR(EAGAIN)) {
while (receive_result != AVERROR(EAGAIN)) {
receive_result = avcodec_receive_packet(avcodec_context, av_packet);
}
} else {
receive_result = avcodec_receive_packet(avcodec_context, av_packet);
if (receive_result == AVERROR(EAGAIN)) {
continue;
}
}
//編碼成功
//將視頻壓縮數(shù)據(jù)->寫入到輸出文件中->outFilePath
av_packet->stream_index = av_video_stream->index;
result = av_write_frame(avformat_context, av_packet);
NSLog(@"當(dāng)前是第%d幀", current_frame_index);
current_frame_index++;
//是否輸出成功
if (result < 0) {
NSLog(@"輸出一幀數(shù)據(jù)失敗");
return;
}
}
//寫入剩余幀數(shù)據(jù)->可能沒有
flush_encoder(avformat_context, 0);
//寫入文件尾部信息
av_write_trailer(avformat_context);
音頻編碼:
AVPacket *av_packet = (AVPacket *) av_malloc(buffer_size);
//循環(huán)讀取音頻幀
int frame_current = 1;
int i = 0, ret = 0;
//即將AVFrame(存儲pcm采樣數(shù)據(jù))編碼為AVPacket (acc)
while (true) {
// 讀取一幀音頻采樣數(shù)據(jù)
if (fread(out_buffer, 1, buffer_size, in_file) <=0) {
NSLog(@"讀取數(shù)據(jù)失敗");
break;
} else if (feof(in_file)) {
break;
}
//設(shè)置音頻采樣數(shù)據(jù)格式
av_frame->data[0] = out_buffer;
av_frame->pts = i;
i++;
// 編碼一幀音頻采樣數(shù)據(jù)->得到音頻壓縮數(shù)據(jù)->aac
// 發(fā)送一幀音頻采樣數(shù)據(jù)
ret = avcodec_send_frame(avcodec_context, av_frame);
if (ret != 0) {
NSLog(@"發(fā)送數(shù)據(jù)失敗");
}
// 編碼一幀音頻采樣數(shù)據(jù)
ret = avcodec_receive_packet(avcodec_context, av_packet);
if (ret == 0) {
/**第十一步:將編碼后的音頻碼流寫入文件*/
NSLog(@"當(dāng)前編碼到了第%d幀", frame_current);
frame_current++;
av_packet->stream_index = audio_st->index;
ret = av_write_frame(avformat_context, av_packet);
if (ret < 0) {
NSLog(@"main","寫入失敗");
return;
}
} else {
NSLog(@"無采樣數(shù)據(jù)編碼");
return;
}
}
//輸入的像素數(shù)據(jù)讀取完成后調(diào)用此函數(shù)碴开。用于輸出編碼器中剩余的AVPacket。
ret = flush_encoder(avformat_context, 0);
if (ret < 0) {
NSLog(@"無剩余壓縮包");
return;
}
// 寫文件尾(對于某些沒有文件頭的封裝格式博秫,不需要此函數(shù)潦牛。比如說MPEG2TS)
av_write_trailer(avformat_context);
10.釋放內(nèi)存。
avcodec_close(avcodec_context);
av_free(av_frame);
av_free(out_buffer);
av_free_packet(av_packet);
avio_close(avformat_context->pb);
avformat_free_context(avformat_context);
fclose(in_file);