avcodec_init(); // 初始化codec库
avcodec_register_all(); // 注册编码器
{
AVCodec *codec; // 编码器
AVCodecContext *c= NULL; // 编解码环境
int i, out_size, size, x, y, outbuf_size;
FILE *f== fopen("C:\\mpeg4_dec1.yuv", "rb");; //视频源文件
AVFrame *picture; // 当前帧
uint8_t *outbuf, *picture_buf;
codec = avcodec_find_encoder(CODEC_ID_MPEG4); // 初始化编码器
if (!codec) {
fprintf(stderr, "codec not found/n");
exit(1);
}
c= avcodec_alloc_context(); // 初始化编解码环境
picture= avcodec_alloc_frame(); // 初始化帧
// 初始化采样率
c->bit_rate = 400000;
// 分辨率
c->width = 352;
c->height = 288;
// 帧数
c->time_base= (AVRational){1,25};
c->gop_size = 10; /* emit one intra frame every ten frames */
c->max_b_frames=1;
c->pix_fmt = PIX_FMT_YUV420P;
// 打开编码器
if (avcodec_open(c, codec) < 0) {
fprintf(stderr, "could not open codec/n");
exit(1);
}
// 打开输出文件
f = fopen(filename, "wb");
if (!f) {
fprintf(stderr, "could not open %s/n", filename);
exit(1);
}
// 分配输出缓存
outbuf_size = 100000;
outbuf = malloc(outbuf_size);
// 分配图像缓存
size = c->width * c->height;
picture_buf = malloc((size * 3) / 2); /* size for YUV 420 */
while (true)
{
if (fread(picture_buf, 1, c->width*c->height*3/2, infile) <=0)
break;
picture->data[0] = picture_buf; // 亮度
picture->data[1] = picture_buf+ size; // 色度
picture->data[2] = picture_buf+ size*5/4; // 色度
picture->linesize[0] = c->width;
picture->linesize[1] = c->width/ 2;
picture->linesize[2] = c->width/ 2;
int iEncSize = avcodec_encode_video(c, outbuf, outbuf_size, picture);
Sleep(10);
}
fclose(f);
free(picture_buf);
free(outbuf);
// 关闭解码器
avcodec_close(c);
av_free(c);
av_free(picture);
}