日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

最简单的基于FFMPEG的视频编码器(YUV编码为H.264)

發(fā)布時間:2024/4/11 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 最简单的基于FFMPEG的视频编码器(YUV编码为H.264) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

=====================================================

最簡單的基于FFmpeg的視頻編碼器文章列表:

最簡單的基于FFMPEG的視頻編碼器(YUV編碼為H.264)

最簡單的基于FFmpeg的視頻編碼器-更新版(YUV編碼為HEVC(H.265))

最簡單的基于FFmpeg的編碼器-純凈版(不包含libavformat)

=====================================================


本文介紹一個最簡單的基于FFMPEG的視頻編碼器。該編碼器實(shí)現(xiàn)了YUV420P的像素數(shù)據(jù)編碼為H.264的壓縮編碼數(shù)據(jù)。編碼器代碼十分簡單,但是每一行代碼都很重要,適合好好研究一下。弄清楚了本代碼也就基本弄清楚了FFMPEG的編碼流程。目前我雖然已經(jīng)調(diào)通了程序,但是還是有些地方?jīng)]有完全搞明白,需要下一步繼續(xù)探究然后補(bǔ)充內(nèi)容。

本程序使用最新版的類庫(編譯時間為2014.5.6),開發(fā)平臺為VC2010。所有的配置都已經(jīng)做好,只需要運(yùn)行就可以了。


流程

下面附一張使用FFmpeg編碼視頻的流程圖。使用該流程,不僅可以編碼H.264的視頻,而且可以編碼MPEG4/MPEG2/VP8等等各種FFmpeg支持的視頻。圖中藍(lán)色背景的函數(shù)是實(shí)際輸出數(shù)據(jù)的函數(shù)。淺綠色的函數(shù)是視頻編碼的函數(shù)。


簡單介紹一下流程中各個函數(shù)的意義:

av_register_all():注冊FFmpeg所有編解碼器。

avformat_alloc_output_context2():初始化輸出碼流的AVFormatContext。

avio_open():打開輸出文件。

av_new_stream():創(chuàng)建輸出碼流的AVStream。

avcodec_find_encoder():查找編碼器。

avcodec_open2():打開編碼器。

avformat_write_header():寫文件頭(對于某些沒有文件頭的封裝格式,不需要此函數(shù)。比如說MPEG2TS)。

avcodec_encode_video2():編碼一幀視頻。即將AVFrame(存儲YUV像素數(shù)據(jù))編碼為AVPacket(存儲H.264等格式的碼流數(shù)據(jù))。

av_write_frame():將編碼后的視頻碼流寫入文件。

flush_encoder():輸入的像素數(shù)據(jù)讀取完成后調(diào)用此函數(shù)。用于輸出編碼器中剩余的AVPacket。

av_write_trailer():寫文件尾(對于某些沒有文件頭的封裝格式,不需要此函數(shù)。比如說MPEG2TS)。


代碼

?

  • /**
  • * 最簡單的基于FFmpeg的視頻編碼器
  • * Simplest FFmpeg Video Encoder
  • *
  • * 雷霄驊 Lei Xiaohua
  • * leixiaohua1020@126.com
  • * 中國傳媒大學(xué)/數(shù)字電視技術(shù)
  • * Communication University of China / Digital TV Technology
  • * http://blog.csdn.net/leixiaohua1020
  • *
  • * 本程序?qū)崿F(xiàn)了YUV像素數(shù)據(jù)編碼為視頻碼流(H264,MPEG2,VP8等等)。
  • * 是最簡單的FFmpeg視頻編碼方面的教程。
  • * 通過學(xué)習(xí)本例子可以了解FFmpeg的編碼流程。
  • * This software encode YUV420P data to H.264 bitstream.
  • * It's the simplest video encoding software based on FFmpeg.
  • * Suitable for beginner of FFmpeg
  • */
  • #include <stdio.h>
  • #define __STDC_CONSTANT_MACROS
  • #ifdef _WIN32
  • //Windows
  • extern "C"
  • {
  • #include "libavutil/opt.h"
  • #include "libavcodec/avcodec.h"
  • #include "libavformat/avformat.h"
  • };
  • #else
  • //Linux...
  • #ifdef __cplusplus
  • extern "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);
  • /* mux encoded frame */
  • 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("src01_480x272.yuv", "rb"); //Input raw YUV data
  • FILE *in_file = fopen("../ds_480x272.yuv", "rb"); //Input raw YUV data
  • int in_w=480,in_h=272; //Input data's width and height
  • int framenum=100; //Frames to encode
  • //const char* out_file = "src01.h264"; //Output Filepath
  • //const char* out_file = "src01.ts";
  • //const char* out_file = "src01.hevc";
  • const char* out_file = "ds.h264";
  • av_register_all();
  • //Method1.
  • pFormatCtx = avformat_alloc_context();
  • //Guess Format
  • fmt = av_guess_format(NULL, out_file, NULL);
  • pFormatCtx->oformat = fmt;
  • //Method 2.
  • //avformat_alloc_output_context2(&pFormatCtx, NULL, NULL, out_file);
  • //fmt = pFormatCtx->oformat;
  • //Open output URL
  • 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);
  • //video_st->time_base.num = 1;
  • //video_st->time_base.den = 25;
  • if (video_st==NULL){
  • return -1;
  • }
  • //Param that must set
  • pCodecCtx = video_st->codec;
  • //pCodecCtx->codec_id =AV_CODEC_ID_HEVC;
  • 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;
  • //H264
  • //pCodecCtx->me_range = 16;
  • //pCodecCtx->max_qdiff = 4;
  • //pCodecCtx->qcompress = 0.6;
  • pCodecCtx->qmin = 10;
  • pCodecCtx->qmax = 51;
  • //Optional Param
  • pCodecCtx->max_b_frames=3;
  • // Set Option
  • AVDictionary *param = 0;
  • //H.264
  • if(pCodecCtx->codec_id == AV_CODEC_ID_H264) {
  • av_dict_set(?m, "preset", "slow", 0);
  • av_dict_set(?m, "tune", "zerolatency", 0);
  • //av_dict_set(?m, "profile", "main", 0);
  • }
  • //H.265
  • if(pCodecCtx->codec_id == AV_CODEC_ID_H265){
  • av_dict_set(?m, "preset", "ultrafast", 0);
  • av_dict_set(?m, "tune", "zero-latency", 0);
  • }
  • //Show some Information
  • 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);
  • //Write File Header
  • avformat_write_header(pFormatCtx,NULL);
  • av_new_packet(&pkt,picture_size);
  • y_size = pCodecCtx->width * pCodecCtx->height;
  • for (int i=0; i<framenum; i++){
  • //Read raw YUV data
  • 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; // Y
  • pFrame->data[1] = picture_buf+ y_size; // U
  • pFrame->data[2] = picture_buf+ y_size*5/4; // V
  • //PTS
  • //pFrame->pts=i;
  • pFrame->pts=i*(video_st->time_base.den)/((video_st->time_base.num)*25);
  • int got_picture=0;
  • //Encode
  • 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);
  • }
  • }
  • //Flush Encoder
  • int ret = flush_encoder(pFormatCtx,0);
  • if (ret < 0) {
  • printf("Flushing encoder failed\n");
  • return -1;
  • }
  • //Write file trailer
  • av_write_trailer(pFormatCtx);
  • //Clean
  • 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;
  • }


  • 結(jié)果

    軟件運(yùn)行截圖(受限于文件體積,原始YUV幀數(shù)很少):


    編碼前的YUV序列:


    編碼后的H.264碼流:



    下載


    Simplest FFmpeg Video Encoder


    項(xiàng)目主頁

    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

    【修正】之前發(fā)現(xiàn)編碼后的H.264碼流與YUV輸入的幀數(shù)不同。經(jīng)過觀察對比其他程序后發(fā)現(xiàn)需要調(diào)用flush_encoder()將編碼器中剩余的視頻幀輸出。已經(jīng)將該問題修正。

    CSDN下載地址(修正后):

    http://download.csdn.net/detail/leixiaohua1020/7466649

    PUDN下載地址(修正后):

    http://www.pudn.com/downloads644/sourcecode/multimedia/detail2605258.html

    SourceForge上已經(jīng)更新。


    更新-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)=========================================

    這次考慮到了跨平臺的要求,調(diào)整了源代碼。經(jīng)過這次調(diào)整之后,源代碼可以在以下平臺編譯通過:

    VC++:打開sln文件即可編譯,無需配置。

    cl.exe:打開compile_cl.bat即可命令行下使用cl.exe進(jìn)行編譯,注意可能需要按照VC的安裝路徑調(diào)整腳本里面的參數(shù)。編譯命令如下。

    ::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命令行下運(yùn)行compile_mingw.sh即可使用MinGW的g++進(jìn)行編譯。編譯命令如下。

    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或者M(jìn)acOS命令行下運(yùn)行compile_gcc.sh即可使用GCC進(jìn)行編譯。編譯命令如下。

    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:相關(guān)的編譯命令已經(jīng)保存到了工程文件夾中


    CSDN下載地址:http://download.csdn.net/detail/leixiaohua1020/8444967

    SourceForge上已經(jīng)更新。

    總結(jié)

    以上是生活随笔為你收集整理的最简单的基于FFMPEG的视频编码器(YUV编码为H.264)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。