=====================================================
最簡單的基于FFmpeg的視頻編碼器文章列表:
最簡單的基于FFMPEG的視頻編碼器(YUV編碼為H.264)
最簡單的基于FFmpeg的視頻編碼器-更新版(YUV編碼為HEVC(H.265))
最簡單的基于FFmpeg的編碼器-純凈版(不包含libavformat)
=====================================================
本文介紹一個最簡單的基于FFMPEG的視頻編碼器。該編碼器實現了YUV420P的像素數據編碼為H.264的壓縮編碼數據。編碼器代碼十分簡單,但是每一行代碼都很重要,適合好好研究一下。弄清楚了本代碼也就基本弄清楚了FFMPEG的編碼流程。目前我雖然已經調通了程序,但是還是有些地方沒有完全搞明白,需要下一步繼續探究然后補充內容。
本程序使用最新版的類庫(編譯時間為2014.5.6),開發平臺為VC2010。所有的配置都已經做好,只需要運行就可以了。
流程
下面附一張使用FFmpeg編碼視頻的流程圖。使用該流程,不僅可以編碼H.264的視頻,而且可以編碼MPEG4/MPEG2/VP8等等各種FFmpeg支持的視頻。圖中藍色背景的函數是實際輸出數據的函數。淺綠色的函數是視頻編碼的函數。
簡單介紹一下流程中各個函數的意義:
av_register_all():注冊FFmpeg所有編解碼器。
avformat_alloc_output_context2():初始化輸出碼流的AVFormatContext。
avio_open():打開輸出文件。
av_new_stream():創建輸出碼流的AVStream。
avcodec_find_encoder():查找編碼器。
avcodec_open2():打開編碼器。
avformat_write_header():寫文件頭(對于某些沒有文件頭的封裝格式,不需要此函數。比如說MPEG2TS)。
avcodec_encode_video2():編碼一幀視頻。即將AVFrame(存儲YUV像素數據)編碼為AVPacket(存儲H.264等格式的碼流數據)。
av_write_frame():將編碼后的視頻碼流寫入文件。
flush_encoder():輸入的像素數據讀取完成后調用此函數。用于輸出編碼器中剩余的AVPacket。
av_write_trailer():寫文件尾(對于某些沒有文件頭的封裝格式,不需要此函數。比如說MPEG2TS)。
代碼
?
#include <stdio.h> #define __STDC_CONSTANT_MACROS #ifdef _WIN32extern "C"{#include "libavutil/opt.h"#include "libavcodec/avcodec.h"#include "libavformat/avformat.h"};#else#ifdef __cplusplusextern "C"{#endif#include <libavutil/opt.h>#include <libavcodec/avcodec.h>#include <libavformat/avformat.h>#ifdef __cplusplus};#endif#endif int flush_encoder(AVFormatContext *fmt_ctx,unsigned int stream_index){ int ret; int got_frame;AVPacket enc_pkt; if (!(fmt_ctx->streams[stream_index]->codec->codec->capabilities &CODEC_CAP_DELAY)) return 0; while (1) {enc_pkt.data = NULL;enc_pkt.size = 0;av_init_packet(&enc_pkt);ret = avcodec_encode_video2 (fmt_ctx->streams[stream_index]->codec, &enc_pkt, NULL, &got_frame);av_frame_free(NULL); if (ret < 0) break; if (!got_frame){ret=0; break;} printf("Flush Encoder: Succeed to encode 1 frame!\tsize:%5d\n",enc_pkt.size); ret = av_write_frame(fmt_ctx, &enc_pkt); if (ret < 0) break;} return ret;} int main(int argc, char* argv[]){AVFormatContext* pFormatCtx;AVOutputFormat* fmt;AVStream* video_st;AVCodecContext* pCodecCtx;AVCodec* pCodec;AVPacket pkt; uint8_t* picture_buf;AVFrame* pFrame; int picture_size; int y_size; int framecnt=0; FILE *in_file = fopen("../ds_480x272.yuv", "rb"); int in_w=480,in_h=272; int framenum=100; const char* out_file = "ds.h264"; av_register_all(); pFormatCtx = avformat_alloc_context(); fmt = av_guess_format(NULL, out_file, NULL);pFormatCtx->oformat = fmt; if (avio_open(&pFormatCtx->pb,out_file, AVIO_FLAG_READ_WRITE) < 0){ printf("Failed to open output file! \n"); return -1;} video_st = avformat_new_stream(pFormatCtx, 0); if (video_st==NULL){ return -1;} pCodecCtx = video_st->codec; pCodecCtx->codec_id = fmt->video_codec;pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;pCodecCtx->width = in_w; pCodecCtx->height = in_h;pCodecCtx->bit_rate = 400000; pCodecCtx->gop_size=250; pCodecCtx->time_base.num = 1; pCodecCtx->time_base.den = 25; pCodecCtx->qmin = 10;pCodecCtx->qmax = 51; pCodecCtx->max_b_frames=3; AVDictionary *param = 0; if(pCodecCtx->codec_id == AV_CODEC_ID_H264) {av_dict_set(?m, "preset", "slow", 0);av_dict_set(?m, "tune", "zerolatency", 0); } if(pCodecCtx->codec_id == AV_CODEC_ID_H265){av_dict_set(?m, "preset", "ultrafast", 0);av_dict_set(?m, "tune", "zero-latency", 0);} av_dump_format(pFormatCtx, 0, out_file, 1); pCodec = avcodec_find_encoder(pCodecCtx->codec_id); if (!pCodec){ printf("Can not find encoder! \n"); return -1;} if (avcodec_open2(pCodecCtx, pCodec,?m) < 0){ printf("Failed to open encoder! \n"); return -1;} pFrame = av_frame_alloc();picture_size = avpicture_get_size(pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height);picture_buf = (uint8_t *)av_malloc(picture_size);avpicture_fill((AVPicture *)pFrame, picture_buf, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height); avformat_write_header(pFormatCtx,NULL); av_new_packet(&pkt,picture_size); y_size = pCodecCtx->width * pCodecCtx->height; for (int i=0; i<framenum; i++){ if (fread(picture_buf, 1, y_size*3/2, in_file) <= 0){ printf("Failed to read raw data! \n"); return -1;}else if(feof(in_file)){ break;}pFrame->data[0] = picture_buf; pFrame->data[1] = picture_buf+ y_size; pFrame->data[2] = picture_buf+ y_size*5/4; pFrame->pts=i*(video_st->time_base.den)/((video_st->time_base.num)*25); int got_picture=0; int ret = avcodec_encode_video2(pCodecCtx, &pkt,pFrame, &got_picture); if(ret < 0){ printf("Failed to encode! \n"); return -1;} if (got_picture==1){ printf("Succeed to encode frame: %5d\tsize:%5d\n",framecnt,pkt.size);framecnt++;pkt.stream_index = video_st->index;ret = av_write_frame(pFormatCtx, &pkt);av_free_packet(&pkt);}} int ret = flush_encoder(pFormatCtx,0); if (ret < 0) { printf("Flushing encoder failed\n"); return -1;} av_write_trailer(pFormatCtx); if (video_st){avcodec_close(video_st->codec);av_free(pFrame);av_free(picture_buf);}avio_close(pFormatCtx->pb);avformat_free_context(pFormatCtx); fclose(in_file); return 0;}
結果
軟件運行截圖(受限于文件體積,原始YUV幀數很少):
編碼前的YUV序列:
編碼后的H.264碼流:
下載
Simplest FFmpeg Video Encoder
項目主頁
SourceForge:https://sourceforge.net/projects/simplestffmpegvideoencoder/
Github:https://github.com/leixiaohua1020/simplest_ffmpeg_video_encoder
開源中國:http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_video_encoder
下載地址:
http://download.csdn.net/detail/leixiaohua1020/7324115
【修正】之前發現編碼后的H.264碼流與YUV輸入的幀數不同。經過觀察對比其他程序后發現需要調用flush_encoder()將編碼器中剩余的視頻幀輸出。已經將該問題修正。
CSDN下載地址(修正后):
http://download.csdn.net/detail/leixiaohua1020/7466649
PUDN下載地址(修正后):
http://www.pudn.com/downloads644/sourcecode/multimedia/detail2605258.html
SourceForge上已經更新。
更新-1.1 (2015.1.03)=========================================
增加了《最簡單的基于FFmpeg的編碼器-純凈版(不包含libavformat)》中的simplest_ffmpeg_video_encoder_pure工程。
CSDN下載地址:
http://download.csdn.net/detail/leixiaohua1020/8322003
更新-1.2 (2015.2.13)=========================================
這次考慮到了跨平臺的要求,調整了源代碼。經過這次調整之后,源代碼可以在以下平臺編譯通過:
VC++:打開sln文件即可編譯,無需配置。
cl.exe:打開compile_cl.bat即可命令行下使用cl.exe進行編譯,注意可能需要按照VC的安裝路徑調整腳本里面的參數。編譯命令如下。
::VS2010 Environment
call "D:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
::include
@set INCLUDE=include;%INCLUDE%
::lib
@set LIB=lib;%LIB%
::compile and link
cl simplest_ffmpeg_video_encoder.cpp /link avcodec.lib avformat.lib avutil.lib ^
avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib /OPT:NOREF
MinGW:MinGW命令行下運行compile_mingw.sh即可使用MinGW的g++進行編譯。編譯命令如下。
g++ simplest_ffmpeg_video_encoder.cpp -g -o simplest_ffmpeg_video_encoder.exe \
-I /usr/local/include -L /usr/local/lib \
-lavformat -lavcodec -lavutil
GCC:Linux或者MacOS命令行下運行compile_gcc.sh即可使用GCC進行編譯。編譯命令如下。
gcc simplest_ffmpeg_video_encoder.cpp -g -o simplest_ffmpeg_video_encoder.out \
-I /usr/local/include -L /usr/local/lib -lavformat -lavcodec -lavutil
PS:相關的編譯命令已經保存到了工程文件夾中
CSDN下載地址:http://download.csdn.net/detail/leixiaohua1020/8444967
SourceForge上已經更新。
總結
以上是生活随笔為你收集整理的最简单的基于FFMPEG的视频编码器(YUV编码为H.264)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。