最簡單的基於FFmpeg的解碼器-純淨版(不包含libavformat),

來源:互聯網
上載者:User

最簡單的基於FFmpeg的解碼器-純淨版(不包含libavformat),

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

最簡單的基於FFmpeg的視頻播放器系列文章列表:

100行代碼實現最簡單的基於FFMPEG+SDL的視頻播放器(SDL1.x)

最簡單的基於FFMPEG+SDL的視頻播放器 ver2 (採用SDL2.0)

最簡單的基於FFmpeg的解碼器-純淨版(不包含libavformat)

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


本文記錄一個更加“純淨”的基於FFmpeg的視頻解碼器。此前記錄過基於FFmpeg的視頻播放器實際上就是一個解碼器:

《最簡單的基於FFMPEG+SDL的視頻播放器 ver2 (採用SDL2.0)》

這個播放器調用了FFmpeg中的libavformat和libavcodec兩個庫完成了視頻解碼工作。但是這不是一個“純淨”的解碼器。該解碼器中libavformat完成封裝格式的解析,而libavcodec完成解碼工作。一個“純淨”的解碼器,理論上說只需要使用libavcodec就足夠了,並不需要使用libavformat。本文記錄的解碼器就是這樣的一個“純淨”的解碼器,它僅僅通過調用libavcodec將H.264/HEVC等格式的壓縮視頻碼流解碼成為YUV資料。

流程圖

本文記錄的純淨版本的基於FFmpeg的解碼器的函數調用流程圖如所示。需要注意的是,此解碼器的輸入必須是只包含視頻編碼資料“裸流”(例如H.264、HEVC碼流檔案),而不能是包含封裝格式的媒體資料(例如AVI、MKV、MP4)。


流程圖中關鍵函數的作用如下所列:
avcodec_register_all():註冊所有的轉碼器。
avcodec_find_decoder():尋找解碼器。
avcodec_alloc_context3():為AVCodecContext分配記憶體。
avcodec_open2():開啟解碼器。
avcodec_decode_video2():解碼一幀資料。
有兩個平時“不太常見”的函數:
av_parser_init():初始化AVCodecParserContext。
av_parser_parse2():解析獲得一個Packet。

兩個儲存資料的結構體如下所列:
AVFrame:儲存一幀解碼後的像素資料
AVPacket:儲存一幀(一般情況下)壓縮編碼資料

AVCodecParser

AVCodecParser用於解析輸入的資料流並把它分成一幀一幀的壓縮編碼資料。比較形象的說法就是把長長的一段連續的資料“切割”成一段段的資料。他的核心函數是av_parser_parse2()。它的定義如下所示。

/** * Parse a packet. * * @param s             parser context. * @param avctx         codec context. * @param poutbuf       set to pointer to parsed buffer or NULL if not yet finished. * @param poutbuf_size  set to size of parsed buffer or zero if not yet finished. * @param buf           input buffer. * @param buf_size      input length, to signal EOF, this should be 0 (so that the last frame can be output). * @param pts           input presentation timestamp. * @param dts           input decoding timestamp. * @param pos           input byte position in stream. * @return the number of bytes of the input bitstream used. * * Example: * @code *   while(in_len){ *       len = av_parser_parse2(myparser, AVCodecContext, &data, &size, *                                        in_data, in_len, *                                        pts, dts, pos); *       in_data += len; *       in_len  -= len; * *       if(size) *          decode_frame(data, size); *   } * @endcode */int av_parser_parse2(AVCodecParserContext *s,                     AVCodecContext *avctx,                     uint8_t **poutbuf, int *poutbuf_size,                     const uint8_t *buf, int buf_size,                     int64_t pts, int64_t dts,                     int64_t pos);

其中poutbuf指向解析後輸出的壓縮編碼資料幀,buf指向輸入的壓縮編碼資料。如果函數執行完後輸出資料為空白(poutbuf_size為0),則代表解析還沒有完成,還需要再次調用av_parser_parse2()解析一部分資料才可以得到解析後的資料幀。當函數執行完後輸出資料不為空白的時候,代表解析完成,可以將poutbuf中的這幀資料取出來做後續處理。

對比

簡單記錄一下這個只使用libavcodec的“純淨版”視頻解碼器和使用libavcodec+libavformat的視頻解碼器的不同。

PS:使用libavcodec+libavformat的解碼器參考文章《》
(1)下列與libavformat相關的函數在“純淨版”視頻解碼器中都不存在。
av_register_all():註冊所有的轉碼器,複用/解複用器等等組件。其中調用了avcodec_register_all()註冊所有轉碼器相關的組件。
avformat_alloc_context():建立AVFormatContext結構體。
avformat_open_input():開啟一個輸入資料流(檔案或者網路地址)。其中會調用avformat_new_stream()建立AVStream結構體。avformat_new_stream()中會調用avcodec_alloc_context3()建立AVCodecContext結構體。
avformat_find_stream_info():擷取媒體的資訊。
av_read_frame():擷取媒體的一幀壓縮編碼資料。其中調用了av_parser_parse2()。
(2)新增了如下幾個函數。
avcodec_register_all():只註冊轉碼器有關的組件。比如說編碼器、解碼器、位元流濾鏡等,但是不註冊複用/解複用器這些和轉碼器無關的組件。
avcodec_alloc_context3():建立AVCodecContext結構體。
av_parser_init():初始化AVCodecParserContext結構體。
av_parser_parse2():使用AVCodecParser從輸入的資料流中分離出一幀一幀的壓縮編碼資料。
(3)程式的流程發生了變化。
在“libavcodec+libavformat”的視頻解碼器中,使用avformat_open_input()和avformat_find_stream_info()就可以解析出輸入視頻的資訊(例如視頻的寬、高)並且賦值給相關的結構體。因此我們在初始化的時候就可以通過讀取相應的欄位擷取到這些資訊。
在“純淨”的解碼器則不能這樣,由於沒有上述的函數,所以不能在初始化的時候獲得視頻的參數。“純淨”的解碼器中,可以通過avcodec_decode_video2()獲得這些資訊。因此我們只有在成功解碼第一幀之後,才能通過讀取相應的欄位擷取到這些資訊。


原始碼
/** * 最簡單的基於FFmpeg的視頻解碼器(純淨版) * Simplest FFmpeg Decoder Pure * * 雷霄驊 Lei Xiaohua * leixiaohua1020@126.com * 中國傳媒大學/數字電視技術 * Communication University of China / Digital TV Technology * http://blog.csdn.net/leixiaohua1020 * * * 本程式實現了視頻碼流(支援HEVC,H.264,MPEG2等)解碼為YUV資料。 * 它僅僅使用了libavcodec(而沒有使用libavformat)。 * 是最簡單的FFmpeg視頻解碼方面的教程。 * 通過學習本例子可以瞭解FFmpeg的解碼流程。 * This software is a simplest decoder based on FFmpeg. * It decode bitstreams to YUV pixel data. * It just use libavcodec (do not contains libavformat). * Suitable for beginner of FFmpeg. */#include <stdio.h>extern "C"{#include "libavcodec/avcodec.h"#include "libswscale/swscale.h"};//test different codec#define TEST_H264  0#define TEST_HEVC  1int main(int argc, char* argv[]){AVCodec *pCodec;    AVCodecContext *pCodecCtx= NULL;AVCodecParserContext *pCodecParserCtx=NULL;    int frame_count;    FILE *fp_in;FILE *fp_out;    AVFrame*pFrame,*pFrameYUV;uint8_t *out_buffer;const int in_buffer_size=4096;uint8_t in_buffer[in_buffer_size + FF_INPUT_BUFFER_PADDING_SIZE]={0};uint8_t *cur_ptr;int cur_size;    AVPacket packet;int ret, got_picture;int y_size;#if TEST_HEVCAVCodecID codec_id=AV_CODEC_ID_HEVC;char filepath_in[]="bigbuckbunny_480x272.hevc";#elseAVCodecID codec_id=AV_CODEC_ID_H264;char filepath_in[]="bigbuckbunny_480x272.h264";#endifchar filepath_out[]="bigbuckbunny_480x272.yuv";int first_time=1;struct SwsContext *img_convert_ctx;//av_log_set_level(AV_LOG_DEBUG);avcodec_register_all();    pCodec = avcodec_find_decoder(codec_id);    if (!pCodec) {        printf("Codec not found\n");        return -1;    }    pCodecCtx = avcodec_alloc_context3(pCodec);    if (!pCodecCtx){        printf("Could not allocate video codec context\n");        return -1;    }pCodecParserCtx=av_parser_init(codec_id);if (!pCodecParserCtx){printf("Could not allocate video parser context\n");return -1;}    if(pCodec->capabilities&CODEC_CAP_TRUNCATED)        pCodecCtx->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */        if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0) {        printf("Could not open codec\n");        return -1;    }//Input File    fp_in = fopen(filepath_in, "rb");    if (!fp_in) {        printf("Could not open input stream\n");        return -1;    }//Output Filefp_out = fopen(filepath_out, "wb");if (!fp_out) {printf("Could not open output YUV file\n");return -1;}    pFrame = av_frame_alloc();av_init_packet(&packet);while (1) {        cur_size = fread(in_buffer, 1, in_buffer_size, fp_in);        if (cur_size == 0)            break;        cur_ptr=in_buffer;        while (cur_size>0){int len = av_parser_parse2(pCodecParserCtx, pCodecCtx,&packet.data, &packet.size,cur_ptr , cur_size ,AV_NOPTS_VALUE, AV_NOPTS_VALUE, AV_NOPTS_VALUE);cur_ptr += len;cur_size -= len;if(packet.size==0)continue;//Some Info from AVCodecParserContextprintf("Packet Size:%6d\t",packet.size);switch(pCodecParserCtx->pict_type){case AV_PICTURE_TYPE_I: printf("Type: I\t");break;case AV_PICTURE_TYPE_P: printf("Type: P\t");break;case AV_PICTURE_TYPE_B: printf("Type: B\t");break;default: printf("Type: Other\t");break;}printf("Output Number:%4d\t",pCodecParserCtx->output_picture_number);printf("Offset:%8ld\n",pCodecParserCtx->cur_offset);ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, &packet);if (ret < 0) {printf("Decode Error.(解碼錯誤)\n");return ret;}if (got_picture) {if(first_time){printf("\nCodec Full Name:%s\n",pCodecCtx->codec->long_name);printf("width:%d\nheight:%d\n\n",pCodecCtx->width,pCodecCtx->height);//SwsContextimg_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); pFrameYUV=avcodec_alloc_frame();out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);y_size=pCodecCtx->width*pCodecCtx->height;first_time=0;}printf("Succeed to decode 1 frame!\n");sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);fwrite(pFrameYUV->data[0],1,y_size,fp_out);     //Y fwrite(pFrameYUV->data[1],1,y_size/4,fp_out);   //Ufwrite(pFrameYUV->data[2],1,y_size/4,fp_out);   //V}}    }//Flush Decoder    packet.data = NULL;    packet.size = 0;while(1){ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, &packet);if (ret < 0) {printf("Decode Error.(解碼錯誤)\n");return ret;}if (!got_picture)break;if (got_picture) {printf("Flush Decoder: Succeed to decode 1 frame!\n");sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);fwrite(pFrameYUV->data[0],1,y_size,fp_out);     //Yfwrite(pFrameYUV->data[1],1,y_size/4,fp_out);   //Ufwrite(pFrameYUV->data[2],1,y_size/4,fp_out);   //V}}    fclose(fp_in);fclose(fp_out);    sws_freeContext(img_convert_ctx);av_parser_close(pCodecParserCtx);av_frame_free(&pFrameYUV);av_frame_free(&pFrame);avcodec_close(pCodecCtx);av_free(pCodecCtx);return 0;}


運行結果通過設定定義在程式開始的宏,確定需要使用的解碼器。
//test different codec#define TEST_H264  0#define TEST_HEVC  1

當TEST_H264設定為1的時候,解碼H.264檔案“bigbuckbunny_480x272.h264”。
當TEST_HEVC設定為1的時候,解碼HEVC檔案“bigbuckbunny_480x272.hevc”。

解碼後的資料儲存成YUV420P格式的檔案“bigbuckbunny_480x272.yuv”。

此外,程式在啟動並執行過程中,會列印出AVCodecParserContext中的一些資訊,比如說框架類型等等,如所示。


輸入H.264碼流如下所示。


輸出YUV420P像素資料如所示。



下載Simplest ffmpeg decoder pure工程被作為子工程添加到了simplest ffmpeg player 2工程中。新版的simplest ffmpeg player 2工程的資訊如下。

Simplest ffmpeg player 2

 version 2.3

SourceForge首頁:https://sourceforge.net/projects/simplestffmpegplayer/

CSDN:http://download.csdn.net/detail/leixiaohua1020/8322307

本程式實現了視頻檔案的解碼和顯示(支援HEVC,H.264,MPEG2等)。
是最簡單的FFmpeg視頻解碼方面的教程。
通過學習本例子可以瞭解FFmpeg的解碼流程。
項目包含3個工程:
simplest_ffmpeg_player:標準版,FFmpeg學習的開始。
simplest_ffmpeg_player_su:SU(SDL Update)版,加入了簡單的SDL的Event。
simplest_ffmpeg_decoder_pure:一個純淨的解碼器。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.