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);
}