ffmpeg視頻的編碼Encode---YUV編碼爲h264

視頻編碼的過程就是將YUV的像素格式編碼成H264的壓縮格式ide

YUV:視頻像素格式
H264:視頻壓縮數據格式工具

流程圖

2791371-f2115d4de2c9a5cf.png
video_encode.png

步驟詳解

一、註冊組件

av_register_all();

二、初始化化封裝格式上下文

AVFormatContext* avformat_context = avformat_alloc_context();

獲取視頻壓縮格式類型(h25四、h26五、mpeg2等)性能

AVOutputFormat *avoutput_format = av_guess_format(NULL, coutFilePath, NULL);

三、打開輸出文件

avio_open(&avformat_context->pb, coutFilePath, AVIO_FLAG_WRITE)

參數一:輸出流
參數二:輸出文件
參數三:權限->輸出到文件中ui

四、建立輸出碼流
AVStream* av_video_stream = avformat_new_stream(avformat_context, NULL);

注意:這裏只是開闢了一塊內存空間,還不知道他是什麼類型編碼

五、查找視頻編碼器(重點)

5.一、獲取上下文
AVCodecContext *avcodec_context = av_video_stream->codec;

上下文種類:視頻解碼器、視頻編碼器、音頻解碼器、音頻編碼器code

5.二、設置爲視頻編碼器上下文

一、設置視頻編碼器IDorm

avcodec_context->codec_id = avoutput_format->video_codec;

二、設置編碼器類型視頻

avcodec_context->codec_type = AVMEDIA_TYPE_VIDEO;

三、設置讀取像素格式blog

//注意:這個類型是根據你解碼的時候指定的解碼的視頻像素數據格式類型
avcodec_context->pix_fmt = AV_PIX_FMT_YUV420P;

四、設置視頻寬高內存

avcodec_context->width = 640;
avcodec_context->height = 352;

這裏的尺寸是經過必定工具查看的,不一樣的視頻不同。
五、設置幀率(重點)

avcodec_context->time_base.num = 1;
avcodec_context->time_base.den = 25;

這兩個參數表示幀率爲25.000fps

幀率越大越流暢。視頻卡頓說明掉幀了。

六、設置碼率(重點)

碼率:也叫比特率,單位bps。也就是每秒傳送的比特數,碼率越高傳送速度越快。
視頻碼率:單位爲kbps,千位每秒

視頻碼率的計算方式:視頻文件大小/視頻時間

注意:一個視頻的總文件包括視頻文件和音頻文件,上面公式中,是指視頻文件的大小。

e.g 一個視頻,視頻文件的大小是1.34MB,時長是24s,那麼他的視頻幀率爲:1.34 * 1024 * 8 / 24 / 1000 = 468 Kbps

每一個文件的碼率不同,都要通過計算獲得

avcodec_context->bit_rate = 468000;

從上面的分析能夠看出:碼率越大,視頻越大

七、設置GOP(重點)

GOP:畫面組,一組連續畫面(一個完整的畫面)

MPEG格式的畫面類型有3種:
I幀:內部編碼幀,原始幀,也叫關鍵幀。視頻的第一幀都是I幀,可獨立編碼。
P幀:向前預測幀。編碼須要依賴前一幀。
B幀:先後預測幀,也叫雙向預測幀。編碼須要依賴本幀與前一幀和後一幀的對比。B幀壓縮率高,但對性能要求高

2791371-a912f78919b1eafd.jpg
701545128389_.pic.jpg
avcodec_context->gop_size = 250;

這裏設置250,表示每250幀插入一個I幀。I幀約少,視頻越小。但過度的少,會致使視頻編碼失敗,因此要適量。

八、設置量化參數(難點,咱們通常設置默認值)

avcodec_context->qmin = 10;
avcodec_context->qmax = 51;

量化係數越小,視頻越是清晰。通常狀況下都是默認值,最小量化係數默認值是10,最大量化係數默認值是51。

九、設置B幀最大值

avcodec_context->max_b_frames = 0;

咱們設置爲0,表示不須要B幀

5.三、查找編碼器h264

查找編碼器h264:找不到???深坑
緣由:編譯庫沒有依賴x264庫(默認狀況下FFmpeg沒有編譯進行h264庫)

如何編譯x264庫?
一、下載x264的庫
二、編譯x264的.a靜態庫,也能夠便以動態庫,根據須要而定
三、從新編譯ffmpeg庫,使ffmpeg依賴2中生成的x264庫
四、替換代碼中以前生成的ffmpeg庫

六、打開視頻編碼器

對於h264解碼器,要多設置參數以下

AVDictionary *param = 0;
    if (avcodec_context->codec_id == AV_CODEC_ID_H264) {
        // 查看h264.c源碼
        av_dict_set(&param, "preset", "slow", 0);
        av_dict_set(&param, "tune", "zerolatency", 0);
    }

打開視頻編碼器

if (avcodec_open2(avcodec_context, avcodec, &param) < 0) {
    NSLog(@"打開編碼器失敗");
    return;
}

七、寫入頭文件信息

avformat_write_header(avformat_context, NULL);

八、循環編碼視頻像素數據爲視頻壓縮數據(YUV-->h264)-- 視頻編碼處理

一、申請緩衝區

av_frame_alloc()
av_image_fill_arrays
(AVPacket *)av_malloc(buffer_size)

二、將緩衝區數據填充到AVFrame中
三、avcodec_send_frame
四、avcodec_receive_packet

九、將編碼後的視頻壓縮數據寫入文件中

av_packet->stream_index = av_video_stream->index;
result = av_write_frame(avformat_context, av_packet);

十、寫入剩餘幀數據(可能沒有)

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;
        }
        NSLog(@"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;
}

十一、寫入文件尾部信息

av_write_trailer(avformat_context);

十二、釋放內存,關閉編碼器等等

avcodec_close(avcodec_context);
av_free(av_frame);
av_free(out_buffer);
av_packet_free(&av_packet);
avio_close(avformat_context->pb);
avformat_free_context(avformat_context);
fclose(in_file);

代碼

- (void)videoEncodeWithInputPath:(NSString *)inputPath outputPath:(NSString *)outputPath {
    
    //第一步:註冊組件->編碼器、解碼器等等…
    av_register_all();
    
    //第二步:初始化封裝格式上下文
    AVFormatContext* avformat_context = avformat_alloc_context();
    const char* coutFilePath = [outputPath UTF8String];
    AVOutputFormat *avoutput_format = av_guess_format(NULL, coutFilePath, NULL);
    avformat_context->oformat = avoutput_format;
    
    //第三步:打開輸出文件
    if (avio_open(&avformat_context->pb, coutFilePath, AVIO_FLAG_WRITE) < 0){
        NSLog(@"打開輸出文件失敗");
        return;
    }
    
    //第四步:建立輸出碼流
    AVStream* av_video_stream = avformat_new_stream(avformat_context, NULL);
    
    //第五步:查找視頻編碼器
    //一、獲取編碼器上下文
    AVCodecContext *avcodec_context = av_video_stream->codec;
    
    //二、設置編解碼器上下文參數
    avcodec_context->codec_id = avoutput_format->video_codec;
    avcodec_context->codec_type = AVMEDIA_TYPE_VIDEO;
    avcodec_context->pix_fmt = AV_PIX_FMT_YUV420P;
    avcodec_context->width = 640;
    avcodec_context->height = 352;
    // 設置幀率25fps
    avcodec_context->time_base.num = 1;
    avcodec_context->time_base.den = 25;
    // 設置碼率
    avcodec_context->bit_rate = 468000;
    // 設置GOP
    avcodec_context->gop_size = 250;
    // 設置量化參數
    avcodec_context->qmin = 10;
    avcodec_context->qmax = 51;
    
    avcodec_context->max_b_frames = 0;
    
    // 第六步:打開編碼器
    // 一、查找編碼器
    AVCodec *avcodec = avcodec_find_encoder(avcodec_context->codec_id);
    if (avcodec == NULL){
        NSLog(@"找不到解碼器");
        return;
    }
    NSLog(@"解碼器名稱爲:%s", avcodec->name);
    
    // 如果h264編碼器,要設置一些參數
    AVDictionary *param = 0;
    if (avcodec_context->codec_id == AV_CODEC_ID_H264) {
        // 查看h264.c源碼
        av_dict_set(&param, "preset", "slow", 0);
        av_dict_set(&param, "tune", "zerolatency", 0);
    }
    // 二、打開編碼器
    if (avcodec_open2(avcodec_context, avcodec, &param) < 0) {
        NSLog(@"打開編碼器失敗");
        return;
    }
    
    // 第七步:寫入頭文件信息
    int flag = avformat_write_header(avformat_context, NULL);
    
    // 第八步:循環編碼YUV文件爲H264
    // 一、開闢緩衝區
    int buffer_size = av_image_get_buffer_size(avcodec_context->pix_fmt,
                                               avcodec_context->width,
                                               avcodec_context->height,
                                               1);
    
    int y_size = avcodec_context->width * avcodec_context->height;
    uint8_t *out_buffer = (uint8_t *)av_malloc(buffer_size);
    
    const char *cinFilePath = [inputPath UTF8String];
    FILE *in_file = fopen(cinFilePath, "rb");
    if (in_file == NULL) {
        NSLog(@"輸入文件不存在");
        return;
    }
    
    // 二、內存空間填充
    AVFrame *av_frame = av_frame_alloc();
    av_image_fill_arrays(av_frame->data,
                         av_frame->linesize,
                         out_buffer,
                         avcodec_context->pix_fmt,
                         avcodec_context->width,
                         avcodec_context->height,
                         1);
    
    // 三、開闢packet
    AVPacket *av_packet = (AVPacket *)av_malloc(buffer_size);
    
    int i = 0;
    int result = 0;
    int current_frame_index = 0;
    
    // 四、循環編碼
    while (true) {
        // 從yuv文件裏面讀取緩衝區
        //讀取大小:y_size * 3 / 2
        if (fread(out_buffer, 1, y_size * 3 / 2, in_file) <= 0) {
            NSLog(@"讀取完畢...");
            break;
        } else if (feof(in_file)) {
            break;
        }
        
        // 將緩衝區數據轉換成AVFrame類型
        //Y值
        av_frame->data[0] = out_buffer;
        //U值
        av_frame->data[1] = out_buffer + y_size;
        //V值
        av_frame->data[2] = out_buffer + y_size * 5 / 4;
        
        av_frame->pts = i;
        
        i++;
        
        // 第九步:視頻編碼處理
        // 一、發送一幀視頻像素數據
        avcodec_send_frame(avcodec_context, av_frame);
        // 二、接收一幀視頻壓縮數據格式(像素數據編碼而來)
        result = avcodec_receive_packet(avcodec_context, av_packet);
        if (result == 0) {
            // 編碼成功
            // 第十步:將數據寫入到輸出文件
            av_packet->stream_index = av_video_stream->index;
            result = av_write_frame(avformat_context, av_packet);
            NSLog(@"當前是第%d幀", current_frame_index);
            current_frame_index++;
            //是否輸出成功
            if (result < 0) {
                NSLog(@"輸出一幀數據失敗");
                return;
            }
        }
        
        
    }
    
    //第11步:寫入剩餘幀數據->可能沒有
    flush_encoder(avformat_context, 0);
    
    //第12步:寫入文件尾部信息
    av_write_trailer(avformat_context);
    
    //第13步:釋放內存
    avcodec_close(avcodec_context);
    av_free(av_frame);
    av_free(out_buffer);
    av_packet_free(&av_packet);
    avio_close(avformat_context->pb);
    avformat_free_context(avformat_context);
    fclose(in_file);
}