ffmpeg視頻編解碼課程教學視頻:https://edu.csdn.net/course/detail/27795
課件裏面提供源碼資料
一、ffmpeg初始化
av_register_all(); //初始化FFMPEG
二、查找編碼器
//==================================== 查找編碼器 ===============================//
AVCodecID codec_id=AV_CODEC_ID_H264;
pCodec = avcodec_find_encoder(codec_id);
if (!pCodec)
{
printf("Codec not found\n");
return ;
}
三、編碼器分配空間、屬性設置
pCodecCtx = avcodec_alloc_context3(pCodec);
if (!pCodecCtx) {
printf("Could not allocate video codec context\n");
return ;
}
pCodecCtx->bit_rate = 400000;
pCodecCtx->width = w;
pCodecCtx->height = h;
pCodecCtx->time_base.num= 1; //每秒25幀
pCodecCtx->time_base.den= 25;
pCodecCtx->gop_size = 10;
pCodecCtx->max_b_frames = 1;
pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P; //原視頻格式
av_opt_set(pCodecCtx->priv_data, "preset", "slow", 0); //屬性設置
四、打開編碼器
if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {
printf("Could not open codec\n");
return ;
}
五、pFrame屬性設置
pFrame = av_frame_alloc();
if (!pFrame) {
printf("Could not allocate video frame\n");
return ;
}
pFrame->format = pCodecCtx->pix_fmt;
pFrame->width = pCodecCtx->width;
pFrame->height = pCodecCtx->height;
int ret = av_image_alloc(pFrame->data, pFrame->linesize, pCodecCtx->width, pCodecCtx->height,
pCodecCtx->pix_fmt, 16);
if (ret < 0) {
printf("Could not allocate raw picture buffer\n");
return ;
}
六、輸入輸出文件打開
//Input raw data
fp_in = fopen(filename_in, "rb");
if (!fp_in) {
printf("Could not open %s\n", filename_in);
return ;
}
//Output bitstream
fp_out = fopen(filename_out, "wb");
if (!fp_out) {
printf("Could not open %s\n", filename_out);
return ;
}
七、編碼主循環過程
7.1 初始化packet
av_init_packet(&pkt);
7.2 讀取輸入視頻數據
if (fread(pFrame->data[0],1,y_size, fp_in)<= 0|| // Y
fread(pFrame->data[1],1,y_size/4,fp_in)<= 0|| // U
fread(pFrame->data[2],1,y_size/4,fp_in)<= 0) // V
{
return ;
}
7.3 解碼
ret = avcodec_encode_video2(pCodecCtx, &pkt, pFrame, &got_output);
if (ret < 0)
{
printf("Error encoding frame\n");
return ;
}
7.4 寫入輸出文件
fwrite(pkt.data, 1, pkt.size, fp_out);
av_free_packet(&pkt);
ffmpeg視頻編解碼課程教學視頻:https://edu.csdn.net/course/detail/27795
課件裏面提供源碼資料
ffmpeg相關文章請看專欄:
ffmpeg專題——ffmpeg實現視頻播放,存儲,H264編、解碼,RTSP推流,RTSP解碼
微信公衆號:玩轉電子世界