3.5 AVCodecontext
3.5.1 音频属性
下面是一些常见的 AVCodecContext 结构体属性,以表格形式展示:
| 属性 | 类型 | 描述 |
|---|---|---|
AVCodec *codec | 指针 | 当前 AVCodecContext 实例使用的编解码器 |
enum AVCodecID codec_id | 枚举 | codec的id |
int sample_rate | 整数 | 音频采样率 |
enum AVSampleFormat sample_fmt | 枚举 | 音频采样格式 |
uint64_t channel_layout | 64位整数 | 音频通道布局 |
int channels | 整数 | 音频通道数,通过 |
int frame_size | 整数 | 音频帧大小,pcm常见1帧1024sample |
bit_rate | ||
profile |
3.5.2 音频设置
- 编码时配置context
- 即,设置codec打开文件的时的参数
- 设置完毕后,各参数需要与codec内置的参数比较,看是否能按要求打开
以下的参数值相等,根据context的值,比较codec值, 同时给frame赋值
// user赋值
codec_ctx->codec_id = codec_id;
codec_ctx->codec_type = AVMEDIA_TYPE_AUDIO;
codec_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
codec_ctx->sample_rate = 48000; //48000;
codec_ctx->channels = av_get_channel_layout_nb_channels(codec_ctx->channel_layout);
codec_ctx->bit_rate = 128*1024;
codec_ctx->profile = FF_PROFILE_AAC_LOW;
// 与 codec比较
if(strcmp(codec->name, "aac") == 0) {
codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
} else if(strcmp(codec->name, "libfdk_aac") == 0) {
codec_ctx->sample_fmt = AV_SAMPLE_FMT_S16;
} else {
codec_ctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
}
// 给frame赋值
frame->nb_samples = codec_ctx->frame_size; // 帧大小
frame->format = codec_ctx->sample_fmt;
frame->channel_layout = codec_ctx->channel_layout;
frame->channels = av_get_channel_layout_nb_channels(frame->channel_layout);
3.5.3 视频属性
| 属性 | 类型 | 描述 |
|---|---|---|
AVCodec *codec | 指针 | 当前 AVCodecContext 实例使用的编解码器 |
enum AVCodecID codec_id | 枚举 | codec的id |
| pix_fmt | 像素格式 | |
| width x height | 分辨率 | |
| framerate | 帧率 =(AVRational){25, 1} | |
| time_base | 频率 =(AVRational){1, 25} | |
| gop_size | I帧间隔 = 25 | |
| max_b_frames | b 帧数量, 不要则=0 | |
| priv_data | 设置 preset 、 profile、 tune | |
| bit_rate |
3.5.4 视频设置
codec_ctx->pix_fmt = AV_PIX_FMT_YUV420P;
/* 设置time base */
codec_ctx->time_base = (AVRational){1, 25};
codec_ctx->framerate = (AVRational){25, 1};
/* 设置分辨率 */
codec_ctx->width = 1280;
codec_ctx->height = 720;
/* 设置I帧间隔
* 如果frame->pict_type设置为AV_PICTURE_TYPE_I, 则忽略gop_size的设置,一直当做I帧进行编码
*/
codec_ctx->gop_size = 25; // I帧间隔
codec_ctx->max_b_frames = 2; // 如果不想包含B帧则设置为0
// option
if (codec->id == AV_CODEC_ID_H264) {
// 相关的参数可以参考libx264.c的 AVOption options
// ultrafast all encode time:2270ms
// medium all encode time:5815ms
// veryslow all encode time:19836ms
ret = av_opt_set(codec_ctx->priv_data, "preset", "medium", 0);
if(ret != 0) {
printf("av_opt_set preset failed\n");
}
ret = av_opt_set(codec_ctx->priv_data, "profile", "main", 0); // 默认是high
if(ret != 0) {
printf("av_opt_set profile failed\n");
}
ret = av_opt_set(codec_ctx->priv_data, "tune","zerolatency",0); // 直播是才使用该设置
// ret = av_opt_set(codec_ctx->priv_data, "tune","film",0); // 画质film
if(ret != 0) {
printf("av_opt_set tune failed\n");
}
}
/* 设置bitrate */
codec_ctx->bit_rate = 3000000;